【问题标题】:How do I fix a 403 using JwtBearerAuthentication?如何使用 JwtBearerAuthentication 修复 403?
【发布时间】:2016-10-14 11:57:34
【问题描述】:

我试图了解如何深入研究当我从 asp.net 配置地狱时获得的自动魔法。我目前正在将一个小的 api 从 asp.net web-api 2 转换为 asp.net core。我不确定 403 在此配置中来自何处或如何修复它。现在大多数 api 端点只需要一个有效的令牌,不需要检查令牌中的任何特定声明。因此,对于我所有经过身份验证的控制器,当使用有效的不记名令牌时,我会收到一个 403 响应,该响应应该是 200。现在我也使用 Auth0 作为提供者的非对称密钥。

我用来验证 JWT 不记名令牌的 Startup.cs 配置方法。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        //Middleware added here order matters

        //TODO formatter settings https://docs.asp.net/en/latest/mvc/models/formatting.html

        //samples to check
        //https://auth0.com/docs/server-apis/webapi-owin
        //https://github.com/auth0-samples/auth0-aspnetcore-webapi-rs256
        var options = new JwtBearerOptions
        {
            Audience = Configuration["auth0:clientId"]
            ,Authority = $"https://{Configuration["auth0:domain"]}/"
            ,Events = new JwtBearerEvents() // just a pass through to log events
        };

        app.UseJwtBearerAuthentication(options);
        // Very hacky to catch invaild tokens https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/issues/191
        // issue says the need for the required hack is fixed but it's been still happening. Issue about the fix https://github.com/aspnet/Security/issues/411
        app.Use(next => async context => {
            try
            {
                await next(context);
            }
            catch
            {
                // If the headers have already been sent, you can't replace the status code.
                // In this case, throw an exception to close the connection.
                if (context.Response.HasStarted)
                {
                    throw;
                }
                context.Response.StatusCode = 401;
            }
        });
        app.UseMvc();

        // TODO global exception handling https://github.com/dotnet/corefx/issues/6398
        app.UseSwaggerGen();
        app.UseSwaggerUi();
    }

}

【问题讨论】:

    标签: c# asp.net-core openid jwt


    【解决方案1】:

    您的令牌中间件似乎没有被执行来验证传入的请求。 尝试将令牌中间件设置为自动运行。

        var options = new JwtBearerOptions
        {
            //other configurations..
            AutomaticAuthenticate = true;
        };
    

    您还可以使用属性在控制器中指定身份验证方案。

    [Authorize(AuthenticationSchemes = "MyAuthenticationScheme")]
    

    在此处了解更多信息:Limiting identity by scheme

    【讨论】:

    • 自动认证=真;是默认的
    【解决方案2】:

    问题出在 ConfigureServices 部分中的策略上。最简单的策略就是我目前所需要的。

        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc(c =>
            {
                // TODO implement this abstract class c.Filters.Add(typeof(ExceptionFilterAttribute));
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                c.Filters.Add(new AuthorizeFilter(policy));
                c.Filters.Add(typeof(ValidateModelFilter));
            });
    

    【讨论】:

      猜你喜欢
      • 2015-07-20
      • 2021-11-11
      • 2020-08-16
      • 1970-01-01
      • 2017-03-28
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      相关资源
      最近更新 更多