首页 > 解决方案 > Auth0 + Asp.Net Core 2.1 + 禁止错误 403

问题描述

这是我第一次使用 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 的仪表板中创建了用户,并为它分配了一个我这样创建的角色:

在此处输入图像描述

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

请帮助寻找解决方案

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

解决方案


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

本教程解释了角色基础身份验证所需的所有内容


推荐阅读