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;
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
add a comment |
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
add a comment |
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
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
c# core auth0
asked Aug 29 '18 at 12:32
PeaceDealerPeaceDealer
3671 gold badge3 silver badges12 bronze badges
3671 gold badge3 silver badges12 bronze badges
add a comment |
add a comment |
5 Answers
5
active
oldest
votes
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.
add a comment |
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
Then create role that represent each application and make sure the relevant permission is selected.
In this example: The role name is” SampleClientAccess”
- Then create the group and link the role that you have created. Add relevant users to the group
- 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.
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
add a comment |
I have decided to drop auth0's Authorization and work out a system myself.
Can't wrap my head around the documentation.
add a comment |
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.
add a comment |
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>>
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
add a comment |
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.
add a comment |
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.
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.
answered Nov 6 '18 at 23:03
StVStV
1047 bronze badges
1047 bronze badges
add a comment |
add a comment |
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
Then create role that represent each application and make sure the relevant permission is selected.
In this example: The role name is” SampleClientAccess”
- Then create the group and link the role that you have created. Add relevant users to the group
- 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.
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
add a comment |
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
Then create role that represent each application and make sure the relevant permission is selected.
In this example: The role name is” SampleClientAccess”
- Then create the group and link the role that you have created. Add relevant users to the group
- 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.
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
add a comment |
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
Then create role that represent each application and make sure the relevant permission is selected.
In this example: The role name is” SampleClientAccess”
- Then create the group and link the role that you have created. Add relevant users to the group
- 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.
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
Then create role that represent each application and make sure the relevant permission is selected.
In this example: The role name is” SampleClientAccess”
- Then create the group and link the role that you have created. Add relevant users to the group
- 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);
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
add a comment |
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
add a comment |
I have decided to drop auth0's Authorization and work out a system myself.
Can't wrap my head around the documentation.
add a comment |
I have decided to drop auth0's Authorization and work out a system myself.
Can't wrap my head around the documentation.
add a comment |
I have decided to drop auth0's Authorization and work out a system myself.
Can't wrap my head around the documentation.
I have decided to drop auth0's Authorization and work out a system myself.
Can't wrap my head around the documentation.
answered Sep 6 '18 at 12:18
PeaceDealerPeaceDealer
3671 gold badge3 silver badges12 bronze badges
3671 gold badge3 silver badges12 bronze badges
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Mar 28 at 6:06
Ben ThomsonBen Thomson
4522 silver badges18 bronze badges
4522 silver badges18 bronze badges
add a comment |
add a comment |
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>>
add a comment |
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>>
add a comment |
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>>
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>>
answered Jul 12 at 13:33
vvuservvuser
1
1
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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