【问题标题】:Auth0 + Asp.Net Core 2.1 + Error 403 forbiddenAuth0 + Asp.Net Core 2.1 + 禁止错误 403
【发布时间】:2020-12-05 19:22:27
【问题描述】:

这是我第一次使用 Auth0 ,我创建了 My Asp.net Core Web API 2.1 ,当我完成了我的 Controllers ,我会用 Auth0 保护它们。 我按照 Auth0 的文档在 Startup.cs 中配置它,就像在 ConfigureServices 方法中一样:

    // 1. Add Authentication Services
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

    }).AddJwtBearer(options =>
    {
        options.Authority = "https://studentdz.eu.auth0.com/";
        options.Audience = "https://api.studentdz.com";
    });

    services.AddMvc()
         .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

在配置方法中:

        // 2. Enable authentication middleware
        app.UseAuthentication();


        app.UseHttpsRedirection();


        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });

之后,我在 Auth0 的仪表板中创建用户,并为其分配一个我创建的角色:

enter image description here

如果我只是在我的控制器中使用 Attribut [Authorize] 这是正常的。
但是如果我像这样将角色添加到 yhis 属性中:[Authorize(Roles = "Admin")]
结果将是禁止错误 403

请帮助寻找解决方案

【问题讨论】:

  • 我建议去 asp.net core 3.1。您会发现更多示例/教程

标签: c# oauth-2.0 auth0 asp.net-core-2.1


【解决方案1】:

请查看本教程的所有内容 ASP.NET Core v2.1: Authorization

本教程解释了角色基础身份验证所需的一切

【讨论】:

  • 他们提供的控制器示例和我的代码一样非常简单,但在我的项目中仍然无法使用。
  • 好的,回顾一下:1 - 您需要从 Auth0 创建一个新规则,此规则允许您验证角色,在示例中他们验证域以识别角色是什么,然后在相同的规则中他们使用命名空间 https://schemas.quickstarts.com/roles 将角色添加到令牌 2- 从您的项目中的 Startup 类添加 TokenValidationParameters 并在里面添加角色声明并非所有责任都来自控制器
  • 我解决了,当我使用错误的授权类型请求访问令牌时,问题出在 Postman 中,所以当我在 jwt.io 中转换令牌时,我没有找到角色。
  • 我遇到了同样的问题。 Witch grant_type 你用过/需要吗?
猜你喜欢
  • 1970-01-01
  • 2019-08-29
  • 1970-01-01
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
  • 2019-11-29
相关资源
最近更新 更多