Spring Security OAuth2 with custom TokenGranter in version 2.0.+

前端 未结 4 869
无人及你
无人及你 2021-01-17 17:50

In previous versions of OAuth2 it was possible to add a custom token granter by adding it to the xml configuration in the element.<

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-17 18:18

    I couldn't find a way to do it because of the dependency on ClientDetailService making it difficult to get the default granters from the getTokenGranter method. I copied over the code from AuthorizationServerEndpointsConfigurer#tokenGranter() and passed in my clientDetailService and other beans directly to the constructors. Note that I add to create a DefaultOAuth2RequestFactory to pass to the granters and to the endpoints:

    public TokenGranter tokenGranter() {
    
                ClientDetailsService clientDetails = clientDetailsService;
                AuthorizationServerTokenServices tokenServices = tokenServices();
                AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices();
                OAuth2RequestFactory requestFactory = requestFactory();
    
                List tokenGranters = new ArrayList();
    
                tokenGranters.add(new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices,
                        clientDetails, requestFactory));
                tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetails, requestFactory));
                tokenGranters.add(new ImplicitTokenGranter(tokenServices, clientDetails, requestFactory));
                tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices, clientDetails, requestFactory));
                tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices,
                            clientDetails, requestFactory));
                tokenGranters.add(new CustomTokenGranter(authenticationManager, tokenServices(), clientDetailsService,
                        requestFactory));
    
                return new CompositeTokenGranter(tokenGranters);
        }
    
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    
            endpoints
                    .tokenServices(tokenServices())
                    .tokenStore(tokenStore())
                    .tokenEnhancer(tokenEnhancer())
                    .authorizationCodeServices(authorizationCodeServices())
                    .userApprovalHandler(userApprovalHandler())
                    .authenticationManager(authenticationManager)
                    .requestFactory(requestFactory())
                    .tokenGranter(tokenGranter());
        }
    

    That being said, I ended up removing that code and simply added another AuthenticationProvider instead because my new grant type was using a subclass of UsernamePasswordAuthenticationToken anyway, which is the Authentication type used by the password grant by default.

提交回复
热议问题