I'm implementing Auth0 to use in my ASP.NET Core 2.1 app with React frontend and haven't been able to make API calls using the token obtained from Auth0. I keep getting unauthorized error.
Here's the code in ConfigureServices()
method in my Startup.cs
:
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwtOptions => {
jwtOptions.Authority = "https://myapp.auth0.com/";
jwtOptions.Audience = "https://myapp.com/api/";
});
string domain = $"https://myapp.auth0.com/";
services.AddAuthorization(options =>
{
options.AddPolicy("read:data", policy => policy.Requirements.Add(new HasScopeRequirement("read:data", domain)));
});
services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();
I have the following to handle scope:
public class HasScopeRequirement : IAuthorizationRequirement
{
public string Issuer { get; }
public string Scope { get; }
public HasScopeRequirement(string scope, string issuer)
{
Scope = scope ?? throw new ArgumentNullException(nameof(scope));
Issuer = issuer ?? throw new ArgumentNullException(nameof(issuer));
}
}
public class HasScopeHandler : AuthorizationHandler<HasScopeRequirement>
{
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;
}
}
Also, in the Configure()
method, I have app.UseAuthentication();
Here's the code in my auth0.js
service:
auth0 = new auth0.WebAuth({
domain: 'myapp.auth0.com',
clientID: 'client_id_copied_from_application_settings_on_auth0',
redirectUri: 'http://localhost:49065/member/callback',
audience: 'https://myapp.com/api/',
responseType: 'token id_token',
scope: 'openid'
});
My frontend is successfully obtaining access_token
, expires_at
and id_token
. Using Postman, I make an API call to one of my API methods but I keep getting 401 Unauthorized
error. I'm posting a screen shot of what I'm seeing in Postman below. Looks like it doesn't like the audience.
Any idea what I'm doing wrong?
We at Auth0 put together a blog tutorial series on this using .Net Core 2.0 which might be helpful to track back on.
https://auth0.com/blog/developing-web-apps-with-asp-dot-net-core-2-dot-0-and-react-part-1/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.