Auth0, with Authorization Extension & ASP.NET AuthorizationDoes C# have extension properties?File Upload ASP.NET MVC 3.0Why not inherit from List<T>?Why can i easily decode auth0 id_token on jwt.io?Auth0 - Rules & Groups && User ManagementOpenshift Open ID Identity Provider with lookup mapping methodHow to authorize user to access to resource based on OR rulesCustom Authorization Filter vs Policy in ASP.Net Core 2.1Authenticate Firebase with Auth0 using Netlify Lambda FunctionsConfusion over auth0 Authorisation options

Why are some hotels asking you to book through Booking.com instead of matching the price at the front desk?

Should I tip on the Amtrak train?

Why is it that I have to play this note on the piano as A sharp?

Do you need to burn fuel between gravity assists?

Why is Sojdlg123aljg a common password?

Supervisor wants me to support a diploma-thesis SW tool after I graduated

Is there some sort of French saying for "a person's signature move"?

What makes an ending "happy"?

What is the "Brake to Exit" feature on the Boeing 777X?

How to best explain that you are taking pictures in a space for practice reasons?

Male viewpoint in an erotic novel

When does order matter in probability?

Are fast interviews red flags?

Laptop failure due to constant fluctuation of AC frequency and voltage

How invisible hand adjusts stock prices if company is listed on multiple exchanges, under multiple currencies, and one of the currencies plunges?

How to accelerate progress in mathematical research

Were there any contemporary sources (prior to RotJ) that confirmed that Darth Vader was telling the truth to Luke?

What can we do about our 9-month-old putting fingers down his throat?

k times Fold with 3 changing extra variables

Is every sentence we write or utter either true or false?

Why does 8 bit truecolor use only 2 bits for blue?

Examples where "thin + thin = nice and thick"

Why do the Brexit opposition parties not want a new election?

What quests do you need to stop at before you make an enemy of a faction for each faction?



Auth0, with Authorization Extension & ASP.NET Authorization


Does C# have extension properties?File Upload ASP.NET MVC 3.0Why not inherit from List<T>?Why can i easily decode auth0 id_token on jwt.io?Auth0 - Rules & Groups && User ManagementOpenshift Open ID Identity Provider with lookup mapping methodHow to authorize user to access to resource based on OR rulesCustom Authorization Filter vs Policy in ASP.Net Core 2.1Authenticate Firebase with Auth0 using Netlify Lambda FunctionsConfusion over auth0 Authorisation options






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I'm working at a project using Auth0. We wish to use the permission system in the Authorization Extension to set it up.



E.g.
Role Admin:
users:viewAll
users:edit
users:xyz



Role User:
users:editOwn
users:viewOwn
users:ect



And then in the Project if possible use the [Authorize(Policy = "users:kvm")] tag.



How-ever, I cannot find any resources on how to actually use the Authorization Extension from Auth0. I'm at a complete loss, so if anyone could guide me on where to even look for these, I'd be very happy.










share|improve this question






























    1















    I'm working at a project using Auth0. We wish to use the permission system in the Authorization Extension to set it up.



    E.g.
    Role Admin:
    users:viewAll
    users:edit
    users:xyz



    Role User:
    users:editOwn
    users:viewOwn
    users:ect



    And then in the Project if possible use the [Authorize(Policy = "users:kvm")] tag.



    How-ever, I cannot find any resources on how to actually use the Authorization Extension from Auth0. I'm at a complete loss, so if anyone could guide me on where to even look for these, I'd be very happy.










    share|improve this question


























      1












      1








      1








      I'm working at a project using Auth0. We wish to use the permission system in the Authorization Extension to set it up.



      E.g.
      Role Admin:
      users:viewAll
      users:edit
      users:xyz



      Role User:
      users:editOwn
      users:viewOwn
      users:ect



      And then in the Project if possible use the [Authorize(Policy = "users:kvm")] tag.



      How-ever, I cannot find any resources on how to actually use the Authorization Extension from Auth0. I'm at a complete loss, so if anyone could guide me on where to even look for these, I'd be very happy.










      share|improve this question














      I'm working at a project using Auth0. We wish to use the permission system in the Authorization Extension to set it up.



      E.g.
      Role Admin:
      users:viewAll
      users:edit
      users:xyz



      Role User:
      users:editOwn
      users:viewOwn
      users:ect



      And then in the Project if possible use the [Authorize(Policy = "users:kvm")] tag.



      How-ever, I cannot find any resources on how to actually use the Authorization Extension from Auth0. I'm at a complete loss, so if anyone could guide me on where to even look for these, I'd be very happy.







      c# core auth0






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Aug 29 '18 at 12:32









      PeaceDealerPeaceDealer

      3671 gold badge3 silver badges12 bronze badges




      3671 gold badge3 silver badges12 bronze badges

























          5 Answers
          5






          active

          oldest

          votes


















          1
















          The authorization extension is accessible via API



          You have to enable the API access and set up a machine to machine communication so that you can hit the endpoints. (like described in the link)



          Then use this documentation to manage permissions, roles, groups etc.



          Each request has to include a token (JWT) which you have to get beforehand from https://yourdomain.auth0.com/oauth/token via a POST request.



          You have to provide four parameters:



          grant_type = client_credentials 
          client_id = from your auth0 application
          client_secret = from your auth0 application
          audience=urn:auth0-authz-api


          Put the token into the header of each request as "Authorization" : "Bearer #YOURTOKEN#"



          You can use any REST client to hit the endpoints. For the start I'd recommend Postman to test the endpoints and check which calls you need. There is a handy collection you can use with some adjustments.






          share|improve this answer
































            2
















            you can use the Authorization Extension to create a permission that represents access to each application.



            Note: While creating permission “Name” should reflect the client id of the application



            Example image below



            enter image description here



            Then create role that represent each application and make sure the relevant permission is selected.



            In this example: The role name is” SampleClientAccess”



            enter image description here



            1. Then create the group and link the role that you have created. Add relevant users to the group

            enter image description here



            1. final step. Go to Dashboard > Rules > create custom rule and the following code.




            function (user, context, callback) 
            // Assume that permission for an application is the client_id of the permission then
             
            if (user.permissions.indexOf(context.clientID) === -1 )
            callback(new UnauthorizedError('You are not allowed to access ' + context.clientName + JSON.stringify(user)));

            callback(null, user, context);





            Hope this will help you in some way.






            share|improve this answer

























            • Not exactly what I was gunning for. My idea was, within Auth0 Authorization extension to set up permissions like: editOtherAccount - and then in my application do like: If(LoggedIn.HasPermission("editOtherAccount")) or the like. Main problem right now, is that the user has to log out, and log back in before a permission is updated, so if i derank a user it does not affet them imeediatly

              – PeaceDealer
              Sep 5 '18 at 12:27


















            1
















            I have decided to drop auth0's Authorization and work out a system myself.



            Can't wrap my head around the documentation.






            share|improve this answer
































              0
















              I want to add how I'm using it in both legacy .NET MVC applications and .NET Core 2.0 APIs as I hope it'll save someone a lot of time that I've spent trying to figure this out.



              If what you want is just to get the groups, permissions, roles and update user accounts in auth0 then follow the steps in the answer by @StV.



              But if you want to check permissions/roles etc in .NET then this is how I've done it:



              Add the groups, roles and permissions to either the access or Id token (or both). To do this follow the instructions here



              Once you publish the rules from the above config step you have to create another rule yourself in Auth0 to copy the info in to the tokens (this got me for a while). this has to run after the rule published/created by Auth0. Mine looks like this:



              function (user, context, callback) 
              if(user.app_metadata)
              var namespace = 'https://visionplatform.com/';
              context.accessToken[namespace + 'roles'] = user.roles;
              context.accessToken[namespace + 'permissions'] = user.permissions;
              context.idToken[namespace + 'roles'] = user.roles;
              context.idToken[namespace + 'permissions'] = user.permissions;

              callback(null, user, context);



              Now if you the user logs in they will have their groups, roles and permissions in their tokens. However keep in mind that ONLY the groups, roles and permissions for the specific client you authenticated against will show (I lost hours to this).



              So now you can get/check the permissions in code be decoding the JWT. Here's a few snippets of code how I've done this in a library method (i.e. not an authorize attribute):



              First get your TokenValidationPrams



              public TokenValidationParameters GetTokenValidationParameter(string domain, string audience)

              IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"domain.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
              var openIdConfig = AsyncHelper.RunSync(async () => await configurationManager.GetConfigurationAsync(CancellationToken.None));

              return new TokenValidationParameters

              ValidIssuer = $"domain",
              ValidAudiences = new[] audience ,
              IssuerSigningKeys = openIdConfig.SigningKeys
              ;



              Then decode your JWT to get the claims



              private ClaimsPrincipal GetValidatedToken(string token, TokenValidationParameters validationParameters)

              var handler = new JwtSecurityTokenHandler();
              return handler.ValidateToken(token, validationParameters, out var _);



              Now you can check that claims principle to see if it includes your group, permission or whatever (please note I just check the permission).



              public bool ValidateTokenClaimsPermissionExists(string token, string domain, string audience, string permission)

              var claimsPrincipal = GetValidatedToken(token, _tokenValidationParameters);

              var scopePermission = claimsPrincipal.FindFirst(c => c.Type == Constants.PermissionsClaimTypeName && c.Value == permission);
              return scopePermission != null;



              I use the above to make separate calls to check permissions but you could (and probably should) write your own authorize attribute or if you're using .NET Core you can write an AuthorizationHandler middleware to check whatever claims you want as per the documentation here. The one below checks the scopes but you could adapt it to check the permissions as per the above code:



              protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)

              // If user does not have the scope claim, get out of here
              if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == requirement.Issuer))

              return Task.CompletedTask;


              // Split the scopes string into an array
              var scopes = context.User.FindFirst(c => c.Type == "scope" && c.Issuer == requirement.Issuer).Value.Split(' ');

              // Succeed if the scope array contains the required scope
              if (scopes.Any(s => s == requirement.Scope))
              context.Succeed(requirement);

              return Task.CompletedTask;



              I'm going to use bits from all of the above to write an authorize attribute for my .NET MVC applications too.






              share|improve this answer
































                0
















                For a simple setup you can set the roles through the Auth0 GUI and use a rule to apply that to the user:



                function (user, context, callback) 

                // Roles should only be set to verified users.
                if (!user.email


                Your startup.cs should have something like this:



                services.AddAuthorization(options =>

                options.AddPolicy("Administrator", authBuilder => authBuilder.RequireRole("Administrator"); );
                options.AddPolicy("User", authBuilder => authBuilder.RequireRole("Administrator", "User"); );



                And in the Controller for example:



                [Authorize(Roles = "Administrator, User")]
                <<your code>>





                share|improve this answer



























                  Your Answer






                  StackExchange.ifUsing("editor", function ()
                  StackExchange.using("externalEditor", function ()
                  StackExchange.using("snippets", function ()
                  StackExchange.snippets.init();
                  );
                  );
                  , "code-snippets");

                  StackExchange.ready(function()
                  var channelOptions =
                  tags: "".split(" "),
                  id: "1"
                  ;
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function()
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled)
                  StackExchange.using("snippets", function()
                  createEditor();
                  );

                  else
                  createEditor();

                  );

                  function createEditor()
                  StackExchange.prepareEditor(
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader:
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  ,
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  );



                  );














                  draft saved

                  draft discarded
















                  StackExchange.ready(
                  function ()
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52077564%2fauth0-with-authorization-extension-asp-net-authorization%23new-answer', 'question_page');

                  );

                  Post as a guest















                  Required, but never shown

























                  5 Answers
                  5






                  active

                  oldest

                  votes








                  5 Answers
                  5






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  1
















                  The authorization extension is accessible via API



                  You have to enable the API access and set up a machine to machine communication so that you can hit the endpoints. (like described in the link)



                  Then use this documentation to manage permissions, roles, groups etc.



                  Each request has to include a token (JWT) which you have to get beforehand from https://yourdomain.auth0.com/oauth/token via a POST request.



                  You have to provide four parameters:



                  grant_type = client_credentials 
                  client_id = from your auth0 application
                  client_secret = from your auth0 application
                  audience=urn:auth0-authz-api


                  Put the token into the header of each request as "Authorization" : "Bearer #YOURTOKEN#"



                  You can use any REST client to hit the endpoints. For the start I'd recommend Postman to test the endpoints and check which calls you need. There is a handy collection you can use with some adjustments.






                  share|improve this answer





























                    1
















                    The authorization extension is accessible via API



                    You have to enable the API access and set up a machine to machine communication so that you can hit the endpoints. (like described in the link)



                    Then use this documentation to manage permissions, roles, groups etc.



                    Each request has to include a token (JWT) which you have to get beforehand from https://yourdomain.auth0.com/oauth/token via a POST request.



                    You have to provide four parameters:



                    grant_type = client_credentials 
                    client_id = from your auth0 application
                    client_secret = from your auth0 application
                    audience=urn:auth0-authz-api


                    Put the token into the header of each request as "Authorization" : "Bearer #YOURTOKEN#"



                    You can use any REST client to hit the endpoints. For the start I'd recommend Postman to test the endpoints and check which calls you need. There is a handy collection you can use with some adjustments.






                    share|improve this answer



























                      1














                      1










                      1









                      The authorization extension is accessible via API



                      You have to enable the API access and set up a machine to machine communication so that you can hit the endpoints. (like described in the link)



                      Then use this documentation to manage permissions, roles, groups etc.



                      Each request has to include a token (JWT) which you have to get beforehand from https://yourdomain.auth0.com/oauth/token via a POST request.



                      You have to provide four parameters:



                      grant_type = client_credentials 
                      client_id = from your auth0 application
                      client_secret = from your auth0 application
                      audience=urn:auth0-authz-api


                      Put the token into the header of each request as "Authorization" : "Bearer #YOURTOKEN#"



                      You can use any REST client to hit the endpoints. For the start I'd recommend Postman to test the endpoints and check which calls you need. There is a handy collection you can use with some adjustments.






                      share|improve this answer













                      The authorization extension is accessible via API



                      You have to enable the API access and set up a machine to machine communication so that you can hit the endpoints. (like described in the link)



                      Then use this documentation to manage permissions, roles, groups etc.



                      Each request has to include a token (JWT) which you have to get beforehand from https://yourdomain.auth0.com/oauth/token via a POST request.



                      You have to provide four parameters:



                      grant_type = client_credentials 
                      client_id = from your auth0 application
                      client_secret = from your auth0 application
                      audience=urn:auth0-authz-api


                      Put the token into the header of each request as "Authorization" : "Bearer #YOURTOKEN#"



                      You can use any REST client to hit the endpoints. For the start I'd recommend Postman to test the endpoints and check which calls you need. There is a handy collection you can use with some adjustments.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 6 '18 at 23:03









                      StVStV

                      1047 bronze badges




                      1047 bronze badges


























                          2
















                          you can use the Authorization Extension to create a permission that represents access to each application.



                          Note: While creating permission “Name” should reflect the client id of the application



                          Example image below



                          enter image description here



                          Then create role that represent each application and make sure the relevant permission is selected.



                          In this example: The role name is” SampleClientAccess”



                          enter image description here



                          1. Then create the group and link the role that you have created. Add relevant users to the group

                          enter image description here



                          1. final step. Go to Dashboard > Rules > create custom rule and the following code.




                          function (user, context, callback) 
                          // Assume that permission for an application is the client_id of the permission then
                           
                          if (user.permissions.indexOf(context.clientID) === -1 )
                          callback(new UnauthorizedError('You are not allowed to access ' + context.clientName + JSON.stringify(user)));

                          callback(null, user, context);





                          Hope this will help you in some way.






                          share|improve this answer

























                          • Not exactly what I was gunning for. My idea was, within Auth0 Authorization extension to set up permissions like: editOtherAccount - and then in my application do like: If(LoggedIn.HasPermission("editOtherAccount")) or the like. Main problem right now, is that the user has to log out, and log back in before a permission is updated, so if i derank a user it does not affet them imeediatly

                            – PeaceDealer
                            Sep 5 '18 at 12:27















                          2
















                          you can use the Authorization Extension to create a permission that represents access to each application.



                          Note: While creating permission “Name” should reflect the client id of the application



                          Example image below



                          enter image description here



                          Then create role that represent each application and make sure the relevant permission is selected.



                          In this example: The role name is” SampleClientAccess”



                          enter image description here



                          1. Then create the group and link the role that you have created. Add relevant users to the group

                          enter image description here



                          1. final step. Go to Dashboard > Rules > create custom rule and the following code.




                          function (user, context, callback) 
                          // Assume that permission for an application is the client_id of the permission then
                           
                          if (user.permissions.indexOf(context.clientID) === -1 )
                          callback(new UnauthorizedError('You are not allowed to access ' + context.clientName + JSON.stringify(user)));

                          callback(null, user, context);





                          Hope this will help you in some way.






                          share|improve this answer

























                          • Not exactly what I was gunning for. My idea was, within Auth0 Authorization extension to set up permissions like: editOtherAccount - and then in my application do like: If(LoggedIn.HasPermission("editOtherAccount")) or the like. Main problem right now, is that the user has to log out, and log back in before a permission is updated, so if i derank a user it does not affet them imeediatly

                            – PeaceDealer
                            Sep 5 '18 at 12:27













                          2














                          2










                          2









                          you can use the Authorization Extension to create a permission that represents access to each application.



                          Note: While creating permission “Name” should reflect the client id of the application



                          Example image below



                          enter image description here



                          Then create role that represent each application and make sure the relevant permission is selected.



                          In this example: The role name is” SampleClientAccess”



                          enter image description here



                          1. Then create the group and link the role that you have created. Add relevant users to the group

                          enter image description here



                          1. final step. Go to Dashboard > Rules > create custom rule and the following code.




                          function (user, context, callback) 
                          // Assume that permission for an application is the client_id of the permission then
                           
                          if (user.permissions.indexOf(context.clientID) === -1 )
                          callback(new UnauthorizedError('You are not allowed to access ' + context.clientName + JSON.stringify(user)));

                          callback(null, user, context);





                          Hope this will help you in some way.






                          share|improve this answer













                          you can use the Authorization Extension to create a permission that represents access to each application.



                          Note: While creating permission “Name” should reflect the client id of the application



                          Example image below



                          enter image description here



                          Then create role that represent each application and make sure the relevant permission is selected.



                          In this example: The role name is” SampleClientAccess”



                          enter image description here



                          1. Then create the group and link the role that you have created. Add relevant users to the group

                          enter image description here



                          1. final step. Go to Dashboard > Rules > create custom rule and the following code.




                          function (user, context, callback) 
                          // Assume that permission for an application is the client_id of the permission then
                           
                          if (user.permissions.indexOf(context.clientID) === -1 )
                          callback(new UnauthorizedError('You are not allowed to access ' + context.clientName + JSON.stringify(user)));

                          callback(null, user, context);





                          Hope this will help you in some way.






                          function (user, context, callback) 
                          // Assume that permission for an application is the client_id of the permission then
                           
                          if (user.permissions.indexOf(context.clientID) === -1 )
                          callback(new UnauthorizedError('You are not allowed to access ' + context.clientName + JSON.stringify(user)));

                          callback(null, user, context);





                          function (user, context, callback) 
                          // Assume that permission for an application is the client_id of the permission then
                           
                          if (user.permissions.indexOf(context.clientID) === -1 )
                          callback(new UnauthorizedError('You are not allowed to access ' + context.clientName + JSON.stringify(user)));

                          callback(null, user, context);






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Aug 30 '18 at 23:11









                          Ragavan RajanRagavan Rajan

                          8435 silver badges17 bronze badges




                          8435 silver badges17 bronze badges















                          • Not exactly what I was gunning for. My idea was, within Auth0 Authorization extension to set up permissions like: editOtherAccount - and then in my application do like: If(LoggedIn.HasPermission("editOtherAccount")) or the like. Main problem right now, is that the user has to log out, and log back in before a permission is updated, so if i derank a user it does not affet them imeediatly

                            – PeaceDealer
                            Sep 5 '18 at 12:27

















                          • Not exactly what I was gunning for. My idea was, within Auth0 Authorization extension to set up permissions like: editOtherAccount - and then in my application do like: If(LoggedIn.HasPermission("editOtherAccount")) or the like. Main problem right now, is that the user has to log out, and log back in before a permission is updated, so if i derank a user it does not affet them imeediatly

                            – PeaceDealer
                            Sep 5 '18 at 12:27
















                          Not exactly what I was gunning for. My idea was, within Auth0 Authorization extension to set up permissions like: editOtherAccount - and then in my application do like: If(LoggedIn.HasPermission("editOtherAccount")) or the like. Main problem right now, is that the user has to log out, and log back in before a permission is updated, so if i derank a user it does not affet them imeediatly

                          – PeaceDealer
                          Sep 5 '18 at 12:27





                          Not exactly what I was gunning for. My idea was, within Auth0 Authorization extension to set up permissions like: editOtherAccount - and then in my application do like: If(LoggedIn.HasPermission("editOtherAccount")) or the like. Main problem right now, is that the user has to log out, and log back in before a permission is updated, so if i derank a user it does not affet them imeediatly

                          – PeaceDealer
                          Sep 5 '18 at 12:27











                          1
















                          I have decided to drop auth0's Authorization and work out a system myself.



                          Can't wrap my head around the documentation.






                          share|improve this answer





























                            1
















                            I have decided to drop auth0's Authorization and work out a system myself.



                            Can't wrap my head around the documentation.






                            share|improve this answer



























                              1














                              1










                              1









                              I have decided to drop auth0's Authorization and work out a system myself.



                              Can't wrap my head around the documentation.






                              share|improve this answer













                              I have decided to drop auth0's Authorization and work out a system myself.



                              Can't wrap my head around the documentation.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Sep 6 '18 at 12:18









                              PeaceDealerPeaceDealer

                              3671 gold badge3 silver badges12 bronze badges




                              3671 gold badge3 silver badges12 bronze badges
























                                  0
















                                  I want to add how I'm using it in both legacy .NET MVC applications and .NET Core 2.0 APIs as I hope it'll save someone a lot of time that I've spent trying to figure this out.



                                  If what you want is just to get the groups, permissions, roles and update user accounts in auth0 then follow the steps in the answer by @StV.



                                  But if you want to check permissions/roles etc in .NET then this is how I've done it:



                                  Add the groups, roles and permissions to either the access or Id token (or both). To do this follow the instructions here



                                  Once you publish the rules from the above config step you have to create another rule yourself in Auth0 to copy the info in to the tokens (this got me for a while). this has to run after the rule published/created by Auth0. Mine looks like this:



                                  function (user, context, callback) 
                                  if(user.app_metadata)
                                  var namespace = 'https://visionplatform.com/';
                                  context.accessToken[namespace + 'roles'] = user.roles;
                                  context.accessToken[namespace + 'permissions'] = user.permissions;
                                  context.idToken[namespace + 'roles'] = user.roles;
                                  context.idToken[namespace + 'permissions'] = user.permissions;

                                  callback(null, user, context);



                                  Now if you the user logs in they will have their groups, roles and permissions in their tokens. However keep in mind that ONLY the groups, roles and permissions for the specific client you authenticated against will show (I lost hours to this).



                                  So now you can get/check the permissions in code be decoding the JWT. Here's a few snippets of code how I've done this in a library method (i.e. not an authorize attribute):



                                  First get your TokenValidationPrams



                                  public TokenValidationParameters GetTokenValidationParameter(string domain, string audience)

                                  IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"domain.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
                                  var openIdConfig = AsyncHelper.RunSync(async () => await configurationManager.GetConfigurationAsync(CancellationToken.None));

                                  return new TokenValidationParameters

                                  ValidIssuer = $"domain",
                                  ValidAudiences = new[] audience ,
                                  IssuerSigningKeys = openIdConfig.SigningKeys
                                  ;



                                  Then decode your JWT to get the claims



                                  private ClaimsPrincipal GetValidatedToken(string token, TokenValidationParameters validationParameters)

                                  var handler = new JwtSecurityTokenHandler();
                                  return handler.ValidateToken(token, validationParameters, out var _);



                                  Now you can check that claims principle to see if it includes your group, permission or whatever (please note I just check the permission).



                                  public bool ValidateTokenClaimsPermissionExists(string token, string domain, string audience, string permission)

                                  var claimsPrincipal = GetValidatedToken(token, _tokenValidationParameters);

                                  var scopePermission = claimsPrincipal.FindFirst(c => c.Type == Constants.PermissionsClaimTypeName && c.Value == permission);
                                  return scopePermission != null;



                                  I use the above to make separate calls to check permissions but you could (and probably should) write your own authorize attribute or if you're using .NET Core you can write an AuthorizationHandler middleware to check whatever claims you want as per the documentation here. The one below checks the scopes but you could adapt it to check the permissions as per the above code:



                                  protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)

                                  // If user does not have the scope claim, get out of here
                                  if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == requirement.Issuer))

                                  return Task.CompletedTask;


                                  // Split the scopes string into an array
                                  var scopes = context.User.FindFirst(c => c.Type == "scope" && c.Issuer == requirement.Issuer).Value.Split(' ');

                                  // Succeed if the scope array contains the required scope
                                  if (scopes.Any(s => s == requirement.Scope))
                                  context.Succeed(requirement);

                                  return Task.CompletedTask;



                                  I'm going to use bits from all of the above to write an authorize attribute for my .NET MVC applications too.






                                  share|improve this answer





























                                    0
















                                    I want to add how I'm using it in both legacy .NET MVC applications and .NET Core 2.0 APIs as I hope it'll save someone a lot of time that I've spent trying to figure this out.



                                    If what you want is just to get the groups, permissions, roles and update user accounts in auth0 then follow the steps in the answer by @StV.



                                    But if you want to check permissions/roles etc in .NET then this is how I've done it:



                                    Add the groups, roles and permissions to either the access or Id token (or both). To do this follow the instructions here



                                    Once you publish the rules from the above config step you have to create another rule yourself in Auth0 to copy the info in to the tokens (this got me for a while). this has to run after the rule published/created by Auth0. Mine looks like this:



                                    function (user, context, callback) 
                                    if(user.app_metadata)
                                    var namespace = 'https://visionplatform.com/';
                                    context.accessToken[namespace + 'roles'] = user.roles;
                                    context.accessToken[namespace + 'permissions'] = user.permissions;
                                    context.idToken[namespace + 'roles'] = user.roles;
                                    context.idToken[namespace + 'permissions'] = user.permissions;

                                    callback(null, user, context);



                                    Now if you the user logs in they will have their groups, roles and permissions in their tokens. However keep in mind that ONLY the groups, roles and permissions for the specific client you authenticated against will show (I lost hours to this).



                                    So now you can get/check the permissions in code be decoding the JWT. Here's a few snippets of code how I've done this in a library method (i.e. not an authorize attribute):



                                    First get your TokenValidationPrams



                                    public TokenValidationParameters GetTokenValidationParameter(string domain, string audience)

                                    IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"domain.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
                                    var openIdConfig = AsyncHelper.RunSync(async () => await configurationManager.GetConfigurationAsync(CancellationToken.None));

                                    return new TokenValidationParameters

                                    ValidIssuer = $"domain",
                                    ValidAudiences = new[] audience ,
                                    IssuerSigningKeys = openIdConfig.SigningKeys
                                    ;



                                    Then decode your JWT to get the claims



                                    private ClaimsPrincipal GetValidatedToken(string token, TokenValidationParameters validationParameters)

                                    var handler = new JwtSecurityTokenHandler();
                                    return handler.ValidateToken(token, validationParameters, out var _);



                                    Now you can check that claims principle to see if it includes your group, permission or whatever (please note I just check the permission).



                                    public bool ValidateTokenClaimsPermissionExists(string token, string domain, string audience, string permission)

                                    var claimsPrincipal = GetValidatedToken(token, _tokenValidationParameters);

                                    var scopePermission = claimsPrincipal.FindFirst(c => c.Type == Constants.PermissionsClaimTypeName && c.Value == permission);
                                    return scopePermission != null;



                                    I use the above to make separate calls to check permissions but you could (and probably should) write your own authorize attribute or if you're using .NET Core you can write an AuthorizationHandler middleware to check whatever claims you want as per the documentation here. The one below checks the scopes but you could adapt it to check the permissions as per the above code:



                                    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)

                                    // If user does not have the scope claim, get out of here
                                    if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == requirement.Issuer))

                                    return Task.CompletedTask;


                                    // Split the scopes string into an array
                                    var scopes = context.User.FindFirst(c => c.Type == "scope" && c.Issuer == requirement.Issuer).Value.Split(' ');

                                    // Succeed if the scope array contains the required scope
                                    if (scopes.Any(s => s == requirement.Scope))
                                    context.Succeed(requirement);

                                    return Task.CompletedTask;



                                    I'm going to use bits from all of the above to write an authorize attribute for my .NET MVC applications too.






                                    share|improve this answer



























                                      0














                                      0










                                      0









                                      I want to add how I'm using it in both legacy .NET MVC applications and .NET Core 2.0 APIs as I hope it'll save someone a lot of time that I've spent trying to figure this out.



                                      If what you want is just to get the groups, permissions, roles and update user accounts in auth0 then follow the steps in the answer by @StV.



                                      But if you want to check permissions/roles etc in .NET then this is how I've done it:



                                      Add the groups, roles and permissions to either the access or Id token (or both). To do this follow the instructions here



                                      Once you publish the rules from the above config step you have to create another rule yourself in Auth0 to copy the info in to the tokens (this got me for a while). this has to run after the rule published/created by Auth0. Mine looks like this:



                                      function (user, context, callback) 
                                      if(user.app_metadata)
                                      var namespace = 'https://visionplatform.com/';
                                      context.accessToken[namespace + 'roles'] = user.roles;
                                      context.accessToken[namespace + 'permissions'] = user.permissions;
                                      context.idToken[namespace + 'roles'] = user.roles;
                                      context.idToken[namespace + 'permissions'] = user.permissions;

                                      callback(null, user, context);



                                      Now if you the user logs in they will have their groups, roles and permissions in their tokens. However keep in mind that ONLY the groups, roles and permissions for the specific client you authenticated against will show (I lost hours to this).



                                      So now you can get/check the permissions in code be decoding the JWT. Here's a few snippets of code how I've done this in a library method (i.e. not an authorize attribute):



                                      First get your TokenValidationPrams



                                      public TokenValidationParameters GetTokenValidationParameter(string domain, string audience)

                                      IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"domain.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
                                      var openIdConfig = AsyncHelper.RunSync(async () => await configurationManager.GetConfigurationAsync(CancellationToken.None));

                                      return new TokenValidationParameters

                                      ValidIssuer = $"domain",
                                      ValidAudiences = new[] audience ,
                                      IssuerSigningKeys = openIdConfig.SigningKeys
                                      ;



                                      Then decode your JWT to get the claims



                                      private ClaimsPrincipal GetValidatedToken(string token, TokenValidationParameters validationParameters)

                                      var handler = new JwtSecurityTokenHandler();
                                      return handler.ValidateToken(token, validationParameters, out var _);



                                      Now you can check that claims principle to see if it includes your group, permission or whatever (please note I just check the permission).



                                      public bool ValidateTokenClaimsPermissionExists(string token, string domain, string audience, string permission)

                                      var claimsPrincipal = GetValidatedToken(token, _tokenValidationParameters);

                                      var scopePermission = claimsPrincipal.FindFirst(c => c.Type == Constants.PermissionsClaimTypeName && c.Value == permission);
                                      return scopePermission != null;



                                      I use the above to make separate calls to check permissions but you could (and probably should) write your own authorize attribute or if you're using .NET Core you can write an AuthorizationHandler middleware to check whatever claims you want as per the documentation here. The one below checks the scopes but you could adapt it to check the permissions as per the above code:



                                      protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)

                                      // If user does not have the scope claim, get out of here
                                      if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == requirement.Issuer))

                                      return Task.CompletedTask;


                                      // Split the scopes string into an array
                                      var scopes = context.User.FindFirst(c => c.Type == "scope" && c.Issuer == requirement.Issuer).Value.Split(' ');

                                      // Succeed if the scope array contains the required scope
                                      if (scopes.Any(s => s == requirement.Scope))
                                      context.Succeed(requirement);

                                      return Task.CompletedTask;



                                      I'm going to use bits from all of the above to write an authorize attribute for my .NET MVC applications too.






                                      share|improve this answer













                                      I want to add how I'm using it in both legacy .NET MVC applications and .NET Core 2.0 APIs as I hope it'll save someone a lot of time that I've spent trying to figure this out.



                                      If what you want is just to get the groups, permissions, roles and update user accounts in auth0 then follow the steps in the answer by @StV.



                                      But if you want to check permissions/roles etc in .NET then this is how I've done it:



                                      Add the groups, roles and permissions to either the access or Id token (or both). To do this follow the instructions here



                                      Once you publish the rules from the above config step you have to create another rule yourself in Auth0 to copy the info in to the tokens (this got me for a while). this has to run after the rule published/created by Auth0. Mine looks like this:



                                      function (user, context, callback) 
                                      if(user.app_metadata)
                                      var namespace = 'https://visionplatform.com/';
                                      context.accessToken[namespace + 'roles'] = user.roles;
                                      context.accessToken[namespace + 'permissions'] = user.permissions;
                                      context.idToken[namespace + 'roles'] = user.roles;
                                      context.idToken[namespace + 'permissions'] = user.permissions;

                                      callback(null, user, context);



                                      Now if you the user logs in they will have their groups, roles and permissions in their tokens. However keep in mind that ONLY the groups, roles and permissions for the specific client you authenticated against will show (I lost hours to this).



                                      So now you can get/check the permissions in code be decoding the JWT. Here's a few snippets of code how I've done this in a library method (i.e. not an authorize attribute):



                                      First get your TokenValidationPrams



                                      public TokenValidationParameters GetTokenValidationParameter(string domain, string audience)

                                      IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"domain.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
                                      var openIdConfig = AsyncHelper.RunSync(async () => await configurationManager.GetConfigurationAsync(CancellationToken.None));

                                      return new TokenValidationParameters

                                      ValidIssuer = $"domain",
                                      ValidAudiences = new[] audience ,
                                      IssuerSigningKeys = openIdConfig.SigningKeys
                                      ;



                                      Then decode your JWT to get the claims



                                      private ClaimsPrincipal GetValidatedToken(string token, TokenValidationParameters validationParameters)

                                      var handler = new JwtSecurityTokenHandler();
                                      return handler.ValidateToken(token, validationParameters, out var _);



                                      Now you can check that claims principle to see if it includes your group, permission or whatever (please note I just check the permission).



                                      public bool ValidateTokenClaimsPermissionExists(string token, string domain, string audience, string permission)

                                      var claimsPrincipal = GetValidatedToken(token, _tokenValidationParameters);

                                      var scopePermission = claimsPrincipal.FindFirst(c => c.Type == Constants.PermissionsClaimTypeName && c.Value == permission);
                                      return scopePermission != null;



                                      I use the above to make separate calls to check permissions but you could (and probably should) write your own authorize attribute or if you're using .NET Core you can write an AuthorizationHandler middleware to check whatever claims you want as per the documentation here. The one below checks the scopes but you could adapt it to check the permissions as per the above code:



                                      protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)

                                      // If user does not have the scope claim, get out of here
                                      if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == requirement.Issuer))

                                      return Task.CompletedTask;


                                      // Split the scopes string into an array
                                      var scopes = context.User.FindFirst(c => c.Type == "scope" && c.Issuer == requirement.Issuer).Value.Split(' ');

                                      // Succeed if the scope array contains the required scope
                                      if (scopes.Any(s => s == requirement.Scope))
                                      context.Succeed(requirement);

                                      return Task.CompletedTask;



                                      I'm going to use bits from all of the above to write an authorize attribute for my .NET MVC applications too.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Mar 28 at 6:06









                                      Ben ThomsonBen Thomson

                                      4522 silver badges18 bronze badges




                                      4522 silver badges18 bronze badges
























                                          0
















                                          For a simple setup you can set the roles through the Auth0 GUI and use a rule to apply that to the user:



                                          function (user, context, callback) 

                                          // Roles should only be set to verified users.
                                          if (!user.email


                                          Your startup.cs should have something like this:



                                          services.AddAuthorization(options =>

                                          options.AddPolicy("Administrator", authBuilder => authBuilder.RequireRole("Administrator"); );
                                          options.AddPolicy("User", authBuilder => authBuilder.RequireRole("Administrator", "User"); );



                                          And in the Controller for example:



                                          [Authorize(Roles = "Administrator, User")]
                                          <<your code>>





                                          share|improve this answer





























                                            0
















                                            For a simple setup you can set the roles through the Auth0 GUI and use a rule to apply that to the user:



                                            function (user, context, callback) 

                                            // Roles should only be set to verified users.
                                            if (!user.email


                                            Your startup.cs should have something like this:



                                            services.AddAuthorization(options =>

                                            options.AddPolicy("Administrator", authBuilder => authBuilder.RequireRole("Administrator"); );
                                            options.AddPolicy("User", authBuilder => authBuilder.RequireRole("Administrator", "User"); );



                                            And in the Controller for example:



                                            [Authorize(Roles = "Administrator, User")]
                                            <<your code>>





                                            share|improve this answer



























                                              0














                                              0










                                              0









                                              For a simple setup you can set the roles through the Auth0 GUI and use a rule to apply that to the user:



                                              function (user, context, callback) 

                                              // Roles should only be set to verified users.
                                              if (!user.email


                                              Your startup.cs should have something like this:



                                              services.AddAuthorization(options =>

                                              options.AddPolicy("Administrator", authBuilder => authBuilder.RequireRole("Administrator"); );
                                              options.AddPolicy("User", authBuilder => authBuilder.RequireRole("Administrator", "User"); );



                                              And in the Controller for example:



                                              [Authorize(Roles = "Administrator, User")]
                                              <<your code>>





                                              share|improve this answer













                                              For a simple setup you can set the roles through the Auth0 GUI and use a rule to apply that to the user:



                                              function (user, context, callback) 

                                              // Roles should only be set to verified users.
                                              if (!user.email


                                              Your startup.cs should have something like this:



                                              services.AddAuthorization(options =>

                                              options.AddPolicy("Administrator", authBuilder => authBuilder.RequireRole("Administrator"); );
                                              options.AddPolicy("User", authBuilder => authBuilder.RequireRole("Administrator", "User"); );



                                              And in the Controller for example:



                                              [Authorize(Roles = "Administrator, User")]
                                              <<your code>>






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Jul 12 at 13:33









                                              vvuservvuser

                                              1




                                              1































                                                  draft saved

                                                  draft discarded















































                                                  Thanks for contributing an answer to Stack Overflow!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid


                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.

                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function ()
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52077564%2fauth0-with-authorization-extension-asp-net-authorization%23new-answer', 'question_page');

                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                                  Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                                  Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript