Auth0 WebApi asp.net 核心设置

时间:2021-04-19 18:10:26

标签: c# asp.net-core auth0

我正在尝试使用 auth0 服务实现 oauth 流程的基本版本。我遵循了基本设置并获取了不记名令牌,但由于某种原因我无法访问我的控制器。 这是我的创业班:

   namespace Webapi
{
    public class Startup
    {
        
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddControllers();
           
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Authority = "https://groep5.eu.auth0.com/";
                options.Audience = "https://localhost:44346/home/";
            });
        }

        
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            app.UseAuthorization();
            app.UseAuthentication();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }
    }
}

这是我的控制器:

namespace Webapi.Controllers
{
    public class HomeController : Controller
    {
        [Authorize]
        public string Leden()
        {
            return "retlok";
        }
        public string Test()
        {
            return "random tekst";
        }
    }
}

我的第一个想法是我的权限错误,但我已经通过多种方式添加了我的方法。 我已经完成了“leden”、“https://localhost:44346/home/leden”和“read:leden”。我的问题可能很简单,但我已经解决了太久了,所以我认为在这个网站上问更容易。

2 个答案:

答案 0 :(得分:1)

代码对我来说看起来不错,您肯定配置了错误,请阅读 auth0 文档以了解 asp.net 核心 Web api。 https://auth0.com/docs/quickstart/backend/aspnet-core-webapi/01-authorization 非常直接。

答案 1 :(得分:1)

感谢用户 Dave Cluderay,我找到了答案。事实证明,您添加中间件的顺序很重要。所以 app.UseAuthorization(); 的顺序和 app.UseAuthentication();应该颠倒过来,我的配置方法应该是这样的:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
        });
    }