Update user authorities in database Spring boot OAuth 2.0

Viewed 224

We can dynamically update a logged-in user's authorities, without having to log out and log in, by resetting the Authentication object (security token) in the Spring SecurityContextHolder by using this code.

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

List<GrantedAuthority> updatedAuthorities = new ArrayList<>(auth.getAuthorities());
updatedAuthorities.add(...); //add your role here [e.g., new SimpleGrantedAuthority("ROLE_NEW_ROLE")]

Authentication newAuth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), updatedAuthorities);

SecurityContextHolder.getContext().setAuthentication(newAuth);

But this code doesn't update authorities in database and I want to update the authorities in database tables of OAuth oauth_access_token and oauth_refresh_token tables. Actually I am working on a social app where user authorities change frequently.

Does Spring provide this feature out of the box?

Or do you have any custom Logic?

1 Answers

You can use TokenStore::storeAccessToken

This worked for my app, when autorities can be chaneged without user logout/login

private final TokenStore tokenStore;

public void updateAuthorities() {
        var auth = (OAuth2Authentication)SecurityContextHolder.getContext().getAuthentication();
        List<GrantedAuthority> newAuthorities = <Your autorities list>;
        var newAuth = new UsernamePasswordAuthenticationToken(
                auth.getPrincipal(),
                auth.getCredentials(),
                newAuthorities
        );
        newAuth.setDetails(auth.getDetails());
        var oauth2Auth = new OAuth2Authentication(auth.getOAuth2Request(), newAuth);
        oauth2Auth.setDetails(auth.getDetails());
        oauth2Auth.setAuthenticated(true);
        OAuth2AccessToken existingAccessToken = this.tokenStore.getAccessToken(auth);
        tokenStore.storeAccessToken(existingAccessToken, oauth2Auth);
        SecurityContextHolder.getContext().setAuthentication(oauth2Auth);
    }
Related