Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring boot OAuth2 role based authorization

We have a dedicated authorization server extending AuthorizationServerConfigurerAdapter, where we have set authorities overriding void configure(ClientDetailsServiceConfigurer clients) method.

    @Configuration
    @EnableAuthorizationServer
    protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Value('${oauth.clientId}')
    private String clientId

    @Value('${oauth.secret:}')
    private String secret

    @Value('${oauth.resourceId}')
    private String resourceId

    @Autowired
    @Qualifier('authenticationManagerBean')
    private AuthenticationManager authenticationManager

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        return new JwtAccessTokenConverter();
    }

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

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .accessTokenConverter(accessTokenConverter())
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient(clientId)
                .secret(secret)
                .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
                .authorities("USER", "ADMIN")
                .scopes("read", "write", "trust")
                .resourceIds(resourceId)
    }

Now how to use the authorities in the resource server for role based authorization. We are able to authenticate via authorization server generated token. Need help.

like image 235
pinaki Avatar asked Dec 17 '15 13:12

pinaki


People also ask

What is Spring Security OAuth2?

In this Spring security oauth2 tutorial, learn to build an authorization server to authenticate your identity to provide access_token, which you can use to request data from resource server. 1. Introduction to OAuth 2 OAuth 2 is an authorization method to provide access to protected resources over the HTTP protocol.

What is Auth0 for Spring Boot API server authorization?

This tutorial covered the most common authorization use cases for a Spring Boot API server. However, Auth0 is an extensible and flexible platform that can help you achieve even more.

How to secure REST APIs with role based OAuth2 implementation?

In this article, we will be securing REST APIs with role based OAUTH2 implementation. To do so, we will be creating two custom roles as ADMIN and USER and we will use @secured annotation provided by spring security to secure our controller methods based on role.

What is the authorization code flow in OAuth?

“The Authorization Code Flow in OAuth 2.0 is a process in which a client obtains an authorization code from an authorization server and then uses the code to acquire access tokens from the token server.” — GPT-3. With that, Let’s take a step back and compare the flow in real-world objects to visualize it better: Imagine walking into a Hotel.


Video Answer


2 Answers

In the resource server you should extend the ResourceServerConfigurerAdapter to configure the requestMatchers and set the role for each resource.

@Configuration
@EnableResourceServer
public class OAuth2Config extends ResourceServerConfigurerAdapter {

    @Value("${keys.public}")
    private String publicKey;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers()
                .antMatchers("/**")
                .and()
                .authorizeRequests()
                .antMatchers("/service1/**").access("#oauth2.hasScope('ADMIN')")
                .antMatchers("/service2/**").access("#oauth2.hasScope('USER')");
    }

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

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

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
        tokenConverter.setVerifierKey(publicKey);
        return tokenConverter;
    }
}
like image 95
Rafael Zeffa Avatar answered Oct 20 '22 04:10

Rafael Zeffa


You have received a token from the auth server. You can now use that token to make another request to the auth server to retrieve the user object. This json object would contain roles(authority). The request would look like as follows.

    curl -H "Authorization: Bearer 2a953581-e9c9-4278-b42e-8af925f49a99"  
    http://localhost:9999/uaa/user

In order to do this, you need to create user service endpoint and implement UserDetailsService also.

    @RequestMapping("/user")
public Principal user(Principal user) {
    return user;
}
    @Bean
     UserDetailsService userDetailsService.....

The role list is created and set in the org.springframework.security.core.userdetailsin the UserDetailsService.User as follows.

AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
like image 1
Hari Avatar answered Oct 20 '22 03:10

Hari