简体   繁体   中英

Spring Security OAuth2 - JWT's with Database for Clients and Users

To my understanding of the Spring OAuth2 implementation, the ClientDetailsConfiguration and TokenStore are not necessarily dependent. Essentially, I thought one should be able to use a JWTokenStore (where the tokens themselves are not stored in a database) with a database to house client credentials. However, while I have referenced multiple articles on the topic, most (for illustation/simplicity), simply hard code the client credentials or place them in a properties file.

For example ( source ):

      @Override
   public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
      configurer
              .inMemory()
              .withClient(clientId)
              .secret(clientSecret)
              .authorizedGrantTypes(grantType)
              .scopes(scopeRead, scopeWrite)
              .resourceIds(resourceIds);
   }

However, I am needing to actually store the client details in a database. I thought it would pretty straight forward; that is, I thought I could achieve the desired result by setting a JWTokenStore and a JDBC client back-end.

AppConfig

@Configuration
public class AppConfig {


    @Value("${spring.datasource.url}")
    private String datasourceUrl;

    @Value("${spring.datasource.driverClassName}")
    private String dbDriverClassName;

    @Value("${spring.datasource.username}")
    private String dbUsername;

    @Value("${spring.datasource.password}")
    private String dbPassword;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DataSource dataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(dbDriverClassName);
        dataSource.setUrl(datasourceUrl);
        dataSource.setUsername(dbUsername);
        dataSource.setPassword(dbPassword);

        return dataSource;
    }    

       @Bean
       public JwtAccessTokenConverter accessTokenConverter() {
          JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
          converter.setSigningKey("123");
          return converter;
       }


       @Bean
       public TokenStore tokenStore() {
          return new JwtTokenStore(accessTokenConverter());
       }

AuthServerConfig

 @EnableAuthorizationServer
@Configuration
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter{
    @Autowired
private TokenStore tokenStore;

 private final AppConfig appConfig; 

private AuthenticationManager authenticationManager;

@Autowired
public AuthServerConfig(AuthenticationManager authenticationManager, AppConfig appConfig) {
    this.authenticationManager = authenticationManager;
    this.appConfig = appConfig;
}

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    security.checkTokenAccess("permitAll()");
}

@Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {


    configurer.jdbc(appConfig.dataSource());
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
    endpoints.tokenStore(tokenStore)
            .tokenEnhancer(enhancerChain)
        .authenticationManager(authenticationManager);
}



   @Bean
   @Primary //Making this primary to avoid any accidental duplication with another token service instance of the same name
   public DefaultTokenServices tokenServices() {
      DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
      defaultTokenServices.setTokenStore(tokenStore);
      defaultTokenServices.setSupportRefreshToken(true);
      return defaultTokenServices;
   }

Rather than return a JWT, it is returning a "normal" (for lack of better term) access token:

    {
    "access_token": "11129068-ad5f-4440-a4d1-6501f01e100b",
    "token_type": "bearer",
    "expires_in": 899,
    "scope": "read"
}

How can I use JWTs with client-credentials stored in a database?

Thanks.

You should also set accessTokenConverter to the endpoint as below.

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
    endpoints.tokenStore(tokenStore)
             .accessTokenConverter(accessTokenConverter())
             .tokenEnhancer(enhancerChain)
             .authenticationManager(authenticationManager);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM