简体   繁体   中英

How to extract claims from token in Resource Server, in Spring Boot

My authentication server is configured to retrieve check credentials against a table on my database, with a token enhancer which I use to pass additional claims - access control related stuff.

As such, I've written it like this:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Value("${security.signing-key}")
    private String signingKey;
    private @Autowired TokenStore tokenStore;
    private @Autowired AuthenticationManager authenticationManager;
    private @Autowired CustomUserDetailsService userDetailsService;

    private @Autowired JwtAccessTokenConverter accessTokenConverter;

    private static final Logger LOGGER = LogManager.getLogger(AuthorizationServerConfig.class);

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource oauthDataSource() {
        DataSource ds = null;
        try {
            Context initialContex = new InitialContext();
            ds = (DataSource) (initialContex.lookup("java:/jdbc/oauthdatasource"));
            if (ds != null) {
                ds.getConnection();
            }
        } catch (NamingException ex) {
            LOGGER.error("Naming exception thrown: ", ex);
        } catch (SQLException ex) {
            LOGGER.info("SQL exception thrown: ", ex);
        }
        return ds;
    }

    @Bean
    public JdbcClientDetailsService clientDetailsServices() {
        return new JdbcClientDetailsService(oauthDataSource());
    }

    @Bean
    public TokenStore tokenStore() {
        return new CustomJdbcTokenStore(oauthDataSource());
    }

    @Bean
    public ApprovalStore approvalStore() {
        return new JdbcApprovalStore(oauthDataSource());
    }

    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new JdbcAuthorizationCodeServices(oauthDataSource());
    }

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsServices());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(authenticationManager)
                .accessTokenConverter(accessTokenConverter)
                .userDetailsService(userDetailsService)
                .reuseRefreshTokens(false);
    }
}

This works very fine. When I make a call via POSTMAN, I get something like this:

{
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsic2hhcmVwb3J0YWwiXSwiaW5mb19maXJzdCI6IlRoaXMgaXMgdGhlIGZpcnN0IEluZm8iLCJ1c2VyX25hbWUiOiJBdXRoZW50aWNhdGlvbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSIsInRydXN0Il0sImluZm9fc2Vjb25kIjoiVGhpcyBpcyB0aGUgc2Vjb25kIGluZm8iLCJleHAiOjE1ODA3MTMyOTQsImF1dGhvcml0aWVzIjpbIlJPTEVfVVNFUiJdLCJqdGkiOiI1MTg4MGJhZC00MGJiLTQ3ZTItODRjZS1lNDUyNGY1Y2Y3MzciLCJjbGllbnRfaWQiOiJzaGFyZXBvcnRhbC1jbGllbnQifQ.ABmBjwmVDb2acZtGSQrjKcCwfZwhw4R_rpW4y5JA1jY",
    "token_type": "bearer",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsic2hhcmVwb3J0YWwiXSwiaW5mb19maXJzdCI6IlRoaXMgaXMgdGhlIGZpcnN0IEluZm8iLCJ1c2VyX25hbWUiOiJBdXRoZW50aWNhdGlvbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSIsInRydXN0Il0sImF0aSI6IjUxODgwYmFkLTQwYmItNDdlMi04NGNlLWU0NTI0ZjVjZjczNyIsImluZm9fc2Vjb25kIjoiVGhpcyBpcyB0aGUgc2Vjb25kIGluZm8iLCJleHAiOjE1ODA3MTM0MzQsImF1dGhvcml0aWVzIjpbIlJPTEVfVVNFUiJdLCJqdGkiOiIyZDYxMDU2ZC01ZDMwLTRhZTQtOWMxZC0zZjliYjRiOWYxOGIiLCJjbGllbnRfaWQiOiJzaGFyZXBvcnRhbC1jbGllbnQifQ.qSLpJm4QxZTIVn1WYWH7EFBS8ryjF1hsD6RSRrEBZd0",
    "expires_in": 359,
    "scope": "read write trust"
}

The problem now is my resource server. This is how it used to be before I added a token enhancer to my authentication server:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private @Autowired CustomAuthenticationEntryPoint entryPoint;
    private @Autowired TokenStore tokenStore;
    private static final String RESOURCE_ID = "resourceid";

    private static final Logger LOGGER = LogManager.getLogger(ResourceServerConfig.class);

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource oauthDataSource() {
        DataSource ds = null;
        try {
            Context initialContex = new InitialContext();
            ds = (DataSource) (initialContex.lookup("java:/jdbc/oauthdatasource"));
            if (ds != null) {
                ds.getConnection();
            }
        } catch (NamingException ex) {
            LOGGER.error("Naming exception thrown: ", ex);
        } catch (SQLException ex) {
            LOGGER.info("SQL exception thrown: ", ex);
        }
        return ds;
    }

    @Bean
    public TokenStore getTokenStore() {
        return new JdbcTokenStore(oauthDataSource());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/**").access("#oauth2.hasScope('read')")
                .antMatchers(HttpMethod.POST, "/**").access("#oauth2.hasScope('write')")
                .antMatchers(HttpMethod.PATCH, "/**").access("#oauth2.hasScope('write')")
                .antMatchers(HttpMethod.PUT, "/**").access("#oauth2.hasScope('write')")
                .antMatchers(HttpMethod.DELETE, "/**").access("#oauth2.hasScope('write')")
                .and()
                .headers().addHeaderWriter((request, response) -> {
                    response.addHeader("Access-Control-Allow-Origin", "*");
                    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                    response.setHeader("Access-Control-Max-Age", "3600");
                    response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
                    if (request.getMethod().equals("OPTIONS")) {
                        response.setStatus(HttpServletResponse.SC_OK);
                    }
                })
                .and().exceptionHandling().authenticationEntryPoint(entryPoint);
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID).tokenStore(tokenStore).authenticationEntryPoint(entryPoint);
    }
}

I wish to retrieve the access control information I've placed as additional claims via the authentication server, but I don't know how to go about it.

I saw a couple of examples on the internet, including this: How to extract claims from Spring Security OAuht2 Boot in the Resource Server? , but none of them are working for me. Or maybe I'm missing something.

Please, what do I have to add to make this possible?

I had to use a third-party library to achieve this.

This is the link to the library: https://github.com/auth0/java-jwt

It works really well.

In my resource server, I can get my token value, and then using the java-jwt library, I can extract any claims I've set in my authorization server:

public Map<String, Claim> getClaims() {
        Map<String, Claim> claims = new HashMap<>();

        String tokenValue = ((OAuth2AuthenticationDetails)((OAuth2Authentication) authenticationFacade.getAuthentication()).getDetails()).getTokenValue();
        try {
            DecodedJWT jwt = JWT.decode(tokenValue);
            claims = jwt.getClaims();
        } catch (JWTDecodeException ex) {
            LOGGER.info("Error decoding token value");
            LOGGER.error("Error decoding token value", ex);
        }

        return claims;
}

You should look at the documentation for java-jwt to learn more.

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