Home > Back-end >  Spring security config for oauth2Login using user's roles instead of scope
Spring security config for oauth2Login using user's roles instead of scope

Time:02-03

The decoded jwt is

{
  "dateTime": 1643825042420,
  "aud": [
    "documentRepository",
    "user"
  ],
  "user_name": "admin",
  "scope": [
    "read",
    "write"
  ],
  "exp": 1643826842,
  "userDetails": {
    "userName": "admin",
    "enable": true,
    "department": null,
    "empId": null,
    "email": null
  },
  "authorities": [
    "ROLE_ADMIN_USER",
    "ROLE_OFFICE_USER"
  ],
  "jti": "8c548137-1f55-4177-a562-8f333a905ee5",
  "client_id": "xyz"
}

The security config is

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

     http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers(
                "/", "/login**"
            )
            .permitAll()
            .antMatchers("/**")
                .access("user's role OFFICE_USER") // this is where only ROLE_USER / SCOPE_read / SCOPE_write works
            .anyRequest()
            .authenticated()
            .and()
            .oauth2Login();
}

Tried manually adding the role

.successHandler(new AuthenticationSuccessHandler() {

    @Override
    public void onAuthenticationSuccess(
        HttpServletRequest request,
        HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException
    {
        OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) authentication;

        token.getAuthorities().addAll(
            AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_OFFICE_USER,ROLE_ADMIN_USER")
        );

    }
});

Results in error

2-02-03 Thu 01:35:08.955 ERROR o.a.c.c.C.[.[.[.[dispatcherServlet]      Java : 175   : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
java.lang.UnsupportedOperationException: null
        at java.util.Collections$UnmodifiableCollection.addAll(Collections.java:1067) ~[na:1.8.0_312]

The OAuth2AuthenticationToken in log is

22-02-03 Thu 01:35:08.953 DEBUG w.c.HttpSessionSecurityContextRepository Java : 361   : Stored SecurityContextImpl [Authentication=OAuth2AuthenticationToken [Principal=Name: [admin], Granted Authorities: [[ROLE_USER, SCOPE_read, SCOPE_write]], User Attributes: [{userName=admin, enable=true, department=null, empId=null, email=null, authorities=ROLE_ADMIN_USER,ROLE_OFFICE_USER}], Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=3724E2FBB58B689FB60A306CD18F7F5A], Granted Authorities=[ROLE_USER, SCOPE_read, SCOPE_write]]] to HttpSession [org.apache.catalina.session.StandardSessionFacade@3487af93]

Is it possible to have .access in HttpSecurity based on authorities present in the decoded JWT. If yes how it can be done

CodePudding user response:

Check out the section of the docs on Using a GrantedAuthoritiesMapper. You can provide a custom mapper implementation following the example in the docs.

Note: It isn't obvious at first, but because OIDC authentication receives an id_token, Spring Security places the id_token in a special authority of type OidcUserAuthority. That's what enables you to then extract the contents of the JWT and further enhance your authorities list in the mapper.

  •  Tags:  
  • Related