Auth0 Home Blog Docs

How do I restrict scopes in auth_token based on user profile?



These are my business rules:

  1. Registered users have:
    app_metadata: { "projects": "test", "test2", "test3" ] }
  2. If a user is requesting access_token for audience “my.secret.api” then:
  • The user may request at most one scope
  • The requested scope must be an exact match to an item in the projects array of the user’s app_metadata .

Here is my current implementation which appears to work:

function (user, context, callback) {   if (context.request.query.audience === 'my.secret.api' && context.request.query.scope) {  
    var requestedScopes = context.request.query.scope.split(' ');  
    if (requestedScopes.length === 1 && user.app_metadata.projects.indexOf(requestedScopes[0]) !== -1) {  
      context.accessToken.scope = requestedScopes;  
    } else {  
      context.accessToken.scope = ];  
callback(null, user, context); 

Is my implementation the correct way to achieve this? It appears to work even if ‘my.secret.api’ does not have scope ‘project3’ (which is a nice side effect). I am confused by when to modify the context.accessToken.scope vs. jwtConfiguration , the documentation is not clear at all on this.


Judging correctness is very difficult because what’s correct for one scenario may not be for another. However, here’s some notes in relation to the implementation in question:

  • using context.accessToken.scope is what you should use when you want to influence the scopes of the issued token; jwtConfiguration is not applicable for this situation.
  • using rules to define custom authorization policies that influence the issued scopes based on the current user is the currently recommended approach; however, have in mind that recommended may be too much of a strong word because, at this time, it’s the only option available.
  • when you use rules to implement the authorization policy you have a lot of control, including issuing scopes that don’t map to predefined ones, however, with that control comes more responsibility.