1.OAuth2分四种模式目前只了解常用的授权码模式和密码模式
1.授权码模式:授权码模式一般用于第三方登录,主要解决了用户登录时密码不会被客户端获取
比较安全.
执行流程:
1;用户打开客户端后,客户端要求用户授权,
具体到实际流程就是登录gitee,点击微信第三方授权登录获取用户授权二维码.
2.用户同意给客户端授权,
具体流程是用户拿微信扫描二维码点击确认授权并用配置好的回调url携带code码跳转到客户端
3.客户端用上一步获取的code去授权服务申请Access_token
4.申请完token就可以向资源服务申请资源
2.密码式
1.A网站携带B网站的用户名和密码访问B网站,直接返回access_token到A网站,A网站再携带Access_token访问资源
2.Spring Security OAuth2源码流程解析
1.AuthorizationServerConfigurerAdapter是配置OAuth2的一个核心配置类,下面我们解析一下这个配置类的相关方法
public class AuthorizationServerConfigurerAdapter implements AuthorizationServerConfigurer {
public AuthorizationServerConfigurerAdapter() {
}
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
}
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
}
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
}
}
1.配置AuthorizationServer安全认证的相关信息,创建ClientCredentialsTokenEndpointFilter核心过滤器
2.配置OAuth客户端的配置
3.配置AuthorizationServerEndpoints的配置类包括配置身份认证器,配置认证方式,TokenStore,TokenGranter,OAuth2RequestFactory
1.ClientCredentialsTokenEndpointFilter的源码解析
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
if (this.allowOnlyPost && !"POST".equalsIgnoreCase(request.getMethod())) {
throw new HttpRequestMethodNotSupportedException(request.getMethod(), new String[]{"POST"});
} else {
String clientId = request.getParameter("client_id");
String clientSecret = request.getParameter("client_secret");
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
return authentication;
} else if (clientId == null) {
throw new BadCredentialsException("No client credentials presented");
} else {
if (clientSecret == null) {
clientSecret = "";
}
clientId = clientId.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, clientSecret);
return this.getAuthenticationManager().authenticate(authRequest);
}
}
}
这个类的核心方法就是attemptAuthentication主要的作用就是将传过来的客户端信息进行封装,封装成后面认证器需要的对象Authentication
AbstractEndpoint类有那个子类分别是AuthorizationEndpoint和TokenEndpoint其中AuthorizationEndpoint负责/oauth/authorize请求授权码,TokenEndpoint负责/oauth/token验证授权码颁发令牌