DEV Community

JL
JL

Posted on

OAuth 2.0 - Scope-based Access Control

The control is done via Scope. The whitepaper said it enough:

Image description

To do this, all 3 components in OAuth are involed in play:
1. Security layer in Resource server
the code will need to use additional layer of spring web security, to make sure the client user of token has the right authority(profile) or role, before accessing the resource (path).

@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .authorizeRequests()
                    .antMatchers(HttpMethod.GET, "/users/status/check")
                    .hasAuthority("SCOPE_profile")
                .anyRequest().authenticated()
                .and()
            .oauth2ResourceServer()
            .jwt();
    }

}
Enter fullscreen mode Exit fullscreen mode

2. Define scopes in Authorization Server
The Authorization Server will need to have the corresponding scopes for the fine-grained access control.
E.g. make sure the scope "profile" will not be granted by default.

Image description

3. Client requests for the right scope in token
If the client did not request for scope "profile", when they use the token to access "/user/status/check", an error 403 Forbidden will occur:

Image description

But if they did request for scope "profile",

Image description

200 OK:

Image description

Now wrapping up the notes by the source code:

Resource Server
Repository: https://github.com/simplyi/ResourceServer

Zip: https://github.com/simplyi/ResourceServer/archive/master.zip

Reference for the notes:
https://www.appsdeveloperblog.com/creating-oauth-2-scope-in-keycloak/

Top comments (0)