Search code examples
javaangularspringspring-bootoauth-2.0

Is possible to create a role based application with OAuth2?


What I'm trying to do is to create an application with Angular frontend and Spring Boot backend with OAuth2 authentication.

The issue is that I don't know how to get on the frontend the ROLES user has so that I'll be able, for instance, to show something role-based on the page.
Yes, there are scopes that OAuth provides in the response but the problem is that these scopes are for the CLIENT but not for the specific USER itself. And that CLIENT is my frontend side (correct me if I'm wrong) which basically means that every user operating my application(client) going to have the same scopes(roles).
Moreover, I can specify roles on the backend with the help of Spring and UserDetailsService and then use those roles with @PreAuthorize, etc. But not on the frontend side.

Just as an example, if I simply used single JWT then with a token itself I'd return both the username and roles to frontend. And then I could store that data and use it on the frontend side according to my needs.

So what I'm asking is if it's actually possible and if this is correct to do so? And how can I possibly implement such behavior?


Solution

  • In OAuth terms a role is a claim in the access token that is calculated dynamically per user:

    • A role claim can enable Role Based Access Control (RBAC)
    • More generally, you can use Attribute Based Access Control (ABAC), which is a superset of RBAC

    Claims are issued when scopes are requested by clients. Scopes are strings that are fixed at design time but they provide a mechanism for one client (eg a web app) to gain different API access to another client (eg a mobile app). So you might design an orders scope to contain a role claim.

    Typically, an API validates a JWT access token and forms a claims principal object that includes the role. This object can be injected into API business code and used for authorization. When required, an API can look up finer grained business permissions associated to roles (finer grained permissions are not usually issued to tokens).

    APIs can return response data to frontends that they also use. This data tends to be focused on what the UI needs. It might contain token claims or other data. My blog post contains more on these topics. Ultimately you should aim to be in control of the data so that it provides what both APIs and clients need, along with good manageability.