There are multiple things to consider here
User authentication: When the user credentials are verified, we mark the user authenticated and register it in SecurityContext
You must be using AuthenticationProvider to authenticate the token received.
Ex:
public class SSOAuthenticationProvider implements AuthenticationProvider {
public Authentication authenticate(Authentication authentication) {
// verified the authentication token
authentication.setAuthenticated(true);
// make the database call, get roles for the user
authentication.setAuthorities(<authorities - discussed below>);
SecurityContextHolder.getContext().setAuthentication(authentication);
return authentication;
}
}
Authorities: Once the user is authenticated, we need to get the granted authorities for the user and set them. For that, we need a custom class to represent the granted authorities.
public class CustomAuthority implements GrantedAuthority {
private String role;
public CustomAuthority(String role) {
this.role = role;
}
@Override
public String getAuthority() {
return role;
}
}
We create these custom authority instances from the roles we receive from the database. So in previous SSOAuthenticationProvider, we do the following
// make the database call, get roles for the user
List<String> roles = <db call to get roles>
authentication.setAuthorities(Collections.unmodifiableCollection(roles.stream().map(CustomAuthority::new).collect(Collectors.toList()));
SecurityContextHolder.getContext().setAuthentication(authentication);
This results in currently authenticated user holding all the roles they are entitled to.
The only pending step is to hardcode the authority/role for each endpoint. Now, when the user authentication process is done and an endpoint verification is performed, Spring looks at the authorities needed for the current endpoint and looks for them in the currently authenticated user. If it's present, the endpoint code gets executed. If not, AccessDeniedException is thrown