美文网首页Spring 学习
Spring Oauth2源码分析

Spring Oauth2源码分析

作者: 一起来看雷阵雨 | 来源:发表于2019-03-04 20:25 被阅读39次

    一般来说对于使用@Enable*注解启动的框架,源码的入口就在@Enable注解里。
    所以我们先从AuthorizationServer开始,@EnableAuthoirzationServer注解源码如下。

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Import({AuthorizationServerEndpointsConfiguration.class, 
              AuthorizationServerSecurityConfiguration.class})
    public @interface EnableAuthorizationServer {
    }
    

    注解导入了两个配置类,AuthorizationServerEndpointsConfiguration.class和AuthorizationServerSecurityConfiguration.class。
    从名字就可以大致猜出各自的作用,前面是用来配置OauthEndpoints的,也就是签发,刷新token的处理类。后者是配置Oauth安全的,继承于WebSecurityConfigurerAdapter,和普通的Security配置类一样。

    @Configuration
    @Order(0)
    @Import({ ClientDetailsServiceConfiguration.class, 
    AuthorizationServerEndpointsConfiguration.class })
    public class AuthorizationServerSecurityConfiguration extends WebSecurityConfigurerAdapter {
    }
    

    其中又导入了新的配置类,ClientDetailsServiceConfiguration.class,源码很简单:

    @Configuration
    public class ClientDetailsServiceConfiguration {
    
        @SuppressWarnings("rawtypes")
        private ClientDetailsServiceConfigurer configurer = new
    ClientDetailsServiceConfigurer(new ClientDetailsServiceBuilder())
    
        @Bean
        public ClientDetailsServiceConfigurer clientDetailsServiceConfigurer() {
            return configurer;
        }
    
        @Bean
        @Lazy
        @Scope(proxyMode=ScopedProxyMode.INTERFACES)
        public ClientDetailsService clientDetailsService() throws Exception {
            return configurer.and().build();
        }
    
    }
    

    主要作用就是注册ClientDetailsService,该类的作用就是根据clientId来查找已经注册的Client,至于已Builder类就不多说了,有常见的InMemory,Jdbc等等。
    到此AuthorizationServerSecurityConfiguration.class这条线就完了。

    来看AuthorizationServerEndpointsConfiguration.class这条线:
    源码太多就不全贴了,这里面有几个重要的类要提一下:

    @Configuration
    @Import(TokenKeyEndpointRegistrar.class)
    public class AuthorizationServerEndpointsConfiguration {
    
        private AuthorizationServerEndpointsConfigurer endpoints = new 
    AuthorizationServerEndpointsConfigurer();
    
    ......其它省略代码    
    
    @Bean
    public AuthorizationEndpoint authorizationEndpoint() throws Exception {
            AuthorizationEndpoint authorizationEndpoint = new AuthorizationEndpoint();
            FrameworkEndpointHandlerMapping mapping=
    getEndpointsConfigurer().getFrameworkEndpointHandlerMapping();
            authorizationEndpoint.setUserApprovalPage(extractPath(mapping, 
    "/oauth/confirm_access"));
            authorizationEndpoint.setProviderExceptionHandler(exceptionTranslator());
        authorizationEndpoint.setTokenGranter(tokenGranter());
        authorizationEndpoint.setClientDetailsService(clientDetailsService);    
        authorizationEndpoint.setAuthorizationCodeServices(authorizationCodeServices());
        authorizationEndpoint.setOAuth2RequestFactory(oauth2RequestFactory());
        authorizationEndpoint.setOAuth2RequestValidator(oauth2RequestValidator());
        authorizationEndpoint.setUserApprovalHandler(userApprovalHandler());
        authorizationEndpoint.setRedirectResolver(redirectResolver());
         return authorizationEndpoint;
      }
    
    @Bean
    public TokenEndpoint tokenEndpoint() throws Exception {
        TokenEndpoint tokenEndpoint = new TokenEndpoint();
        tokenEndpoint.setClientDetailsService(clientDetailsService);
        tokenEndpoint.setProviderExceptionHandler(exceptionTranslator());
        tokenEndpoint.setTokenGranter(tokenGranter());
        tokenEndpoint.setOAuth2RequestFactory(oauth2RequestFactory());
        tokenEndpoint.setOAuth2RequestValidator(oauth2RequestValidator());
            tokenEndpoint.setAllowedRequestMethods(allowedTokenEndpointRequestMethods());
        return tokenEndpoint;
      }
    }
    

    AuthoirzationEndpoint是用来授权的,TokenEndpoint是用来签发token的,重点说一下TokenEndpoint类,授权内容有兴趣的自己去翻一下。
    从代码里可以看到初始化TokenEndpoint时设置了几个对象:

    • ClientDetailsService 根据ClientId查找client
    • ExceptionTranslator 处理异常,将异常翻译为合适的格式。
    • TokenGranter 签发Token,这里每种授权类型会对应不同的Granter。
    • Oauth2RequestFactory 认证生成OauthRequest
    • Oauth2RequestValitor 校验Request
    • AllowedTokenEndpointRequestMethods 支持的方法

    在AuthorizationServerEndpointsConfigurer中会生成对应的Granter:

    private List<TokenGranter> getDefaultTokenGranters() {
            ClientDetailsService clientDetails = clientDetailsService();
            AuthorizationServerTokenServices tokenServices = tokenServices();
            AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices();
            OAuth2RequestFactory requestFactory = requestFactory();
    
            List<TokenGranter> tokenGranters = new ArrayList<TokenGranter>();
            tokenGranters.add(new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetails,
                    requestFactory));
            tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetails, requestFactory));
            ImplicitTokenGranter implicit = new ImplicitTokenGranter(tokenServices, clientDetails, requestFactory);
            tokenGranters.add(implicit);
            tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices, clientDetails, requestFactory));
            if (authenticationManager != null) {
                tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices,
                        clientDetails, requestFactory));
            }
            return tokenGranters;
        }
    这里要注意一点,Password模式需要配置AuthencationManager。
    

    TokenEndpoint类

    回到TokenEndpoint类,继续查看处理请求的细节

    @RequestMapping(value = "/oauth/token", method=RequestMethod.POST)
        public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam
        Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
    
            if (!(principal instanceof Authentication)) {
                throw new InsufficientAuthenticationException(
                        "There is no client authentication. Try adding an appropriate authentication filter.");
            }
    
            String clientId = getClientId(principal);
            ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);
    
            TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);
    
            if (clientId != null && !clientId.equals("")) {
                // Only validate the client details if a client authenticated during this
                // request.
                if (!clientId.equals(tokenRequest.getClientId())) {
                    // double check to make sure that the client ID in the token request is the same as that in the
                    // authenticated client
                    throw new InvalidClientException("Given client ID does not match authenticated client");
                }
            }
            if (authenticatedClient != null) {
                oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
            }
            if (!StringUtils.hasText(tokenRequest.getGrantType())) {
                throw new InvalidRequestException("Missing grant type");
            }
            if (tokenRequest.getGrantType().equals("implicit")) {
                throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
            }
    
            if (isAuthCodeRequest(parameters)) {
                // The scope was requested or determined during the authorization step
                if (!tokenRequest.getScope().isEmpty()) {
                    logger.debug("Clearing scope of incoming token request");
                    tokenRequest.setScope(Collections.<String> emptySet());
                }
            }
    
            if (isRefreshTokenRequest(parameters)) {
                // A refresh token has its own default scopes, so we should ignore any added by the factory here.
                tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
            }
    
            OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
            if (token == null) {
                throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
            }
    
            return getResponse(token);
    
        }
    

    熟悉的RequestMapping和路径"/oauth/token"。这里就是签发、刷新token的地方了。
    基本流程就是:
    通过ClientDetailsSevice根据ClientId查找对应的Client,由Oauth2RequestFactory生成TokenRequest。检查是否能对应的找到Client,没有就抛出异常。
    检查参数,都没问题了最后就调用Ganter的grant方法来生成Token并返回。
    到这里基本上就结束了,因为篇幅问题其它细节就需要自己去看源码。
    细心读者可能会发现这个源代码中少了最重要的一环,没有注册对应的Filter!!!!
    Spring security都是一系列重要的Filter组成的,OauthAuthorizationServer相关的Filter为ClientCredentialsTokenEndpointFilter.class。
    在AuthorizationServerSecurityConfiguration的中进入AuthorizationServerSecurityConfigurer里注册,源码自己查看吧,也很简单。

    相关文章

      网友评论

        本文标题:Spring Oauth2源码分析

        本文链接:https://www.haomeiwen.com/subject/fnhwuqtx.html