A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

4.3.6 Controller
AuthController代码如下:
[AppleScript] 纯文本查看 复制代码
@RestController public class AuthController implements AuthControllerApi {    
 @Value("${auth.clientId}")  
   String clientId;   
  @Value("${auth.clientSecret}")   
  String clientSecret;
@Value("${auth.cookieDomain}")    
 String cookieDomain;    
 @Value("${auth.cookieMaxAge}")   
  int cookieMaxAge;  
   @Value("${auth.tokenValiditySeconds}")   
  int tokenValiditySeconds; 
    @Autowired 
    AuthService authService;   
       @Override  
   @PostMapping("/userlogin")   
  public LoginResult login(LoginRequest loginRequest) {    
     //校验账号是否输入  
       if(loginRequest == null || StringUtils.isEmpty(loginRequest.getUsername())){     
        ExceptionCast.cast(AuthCode.AUTH_USERNAME_NONE);    
     }    
     //校验密码是否输入  
       if(StringUtils.isEmpty(loginRequest.getPassword())){      
       ExceptionCast.cast(AuthCode.AUTH_PASSWORD_NONE);    
     }     
    AuthToken authToken = authService.login(loginRequest.getUsername(),  loginRequest.getPassword(), clientId, clientSecret);     
    //将令牌写入cookie    
     //访问token     
    String access_token = authToken.getAccess_token();    
     //将访问令牌存储到cookie      
   saveCookie(access_token); 
        return new LoginResult(CommonCode.SUCCESS,access_token);   
  }    
       //将令牌保存到cookie  
   private void saveCookie(String token){    
     HttpServletResponse response = ((ServletRequestAttributes)  RequestContextHolder.getRequestAttributes()).getResponse();     
    //添加cookie 认证令牌,最后一个参数设置为false,表示允许浏览器获取    
     CookieUtil.addCookie(response, cookieDomain, "/", "uid", token, cookieMaxAge, false);  
   }        
  @Override   
  @PostMapping("/userlogout")     
public ResponseResult logout() {      
   return null;  
   } } 

4.3.7 登录url放行
认证服务默认都要校验用户的身份信息,这里需要将登录url放行。

在WebSecurityConfig类中重写 configure(WebSecurity web)方法,如下:

[AppleScript] 纯文本查看 复制代码
@Override      
    public void configure(WebSecurity web) throws Exception {  
       web.ignoring().antMatchers("/userlogin");     
  } 

4.3.8 测试认证接口
使用postman测试:
Post请求:http://localhost:40400/auth/userlogin

1561445683(1).jpg
4.3.9 测试写入Cookie
cookie最终会写到xuecheng.com域名下,可通过nginx代理进行认证,测试cookie是否写成功。
1、配置nginx代理 在ucenter.xuecheng.com下配置代理路径

[AppleScript] 纯文本查看 复制代码
#认证 location ^~ /openapi/auth/ {   proxy_pass http://auth_server_pool/auth/;        } 

添加:

[AppleScript] 纯文本查看 复制代码
#认证服务 upstream auth_server_pool{ server 127.0.0.1:40400 weight=10;   
   }

2、请求:http://ucenter.xuecheng.com/openapi/auth/userlogin
观察cookie写入结果

1561445758(1).jpg


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马