通过令牌从Auth0

时间:2018-09-03 16:31:40

标签: asp.net-core jwt auth0

我正在实现Auth0以在我的ASP.NET Core 2.1应用中与React前端一起使用,并且无法使用从Auth0获得的令牌进行API调用。我不断收到未经授权的错误。

这是我的ConfigureServices()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>();

我要处理以下范围:

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;
    }
}

此外,在Configure()方法中,我有app.UseAuthentication();

这是我的auth0.js服务中的代码:

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'
    });

我的前端已成功获取access_tokenexpires_atid_token。使用Postman,我对自己的一种API方法进行了API调用,但始终收到401 Unauthorized错误。我将在下面发布我在Postman中看到的屏幕截图。看起来不喜欢听众。

enter image description here

知道我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

我们在Auth0上使用.Net Core 2.0编写了有关此主题的博客教程系列,这可能有助于追溯。

https://auth0.com/blog/developing-web-apps-with-asp-dot-net-core-2-dot-0-and-react-part-1/