【问题标题】:Change Authorize attribute to return 401 - .net core 3.1更改授权属性以返回 401 - .net core 3.1
【发布时间】:2020-12-03 09:59:12
【问题描述】:

我想用 Authorize 属性保护我的控制器。 然后简单地拥有一个对 401s 做出反应的全局 axios 拦截器

似乎 Authorize 属性默认返回 302 到 /account/login。我怎样才能覆盖它?

代码: Startup.cs / ConfigureServices

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();

Startup.cs / 配置

app.UseAuthorization();
app.UseAuthentication();

main.ts

axios.interceptors.response.use(undefined, function (error) {
    if (error.response.status === 401) {
       // I'll do something here
       return Promise.reject(error);
    }
});

【问题讨论】:

  • 在配置方法中,app.useauthorization 和 app.useauthentication 必须互换。身份验证先于授权。
  • 返回401是默认的,你的配置有问题,如上所述,你的configure方法的顺序很重要
  • 我已经更改了订单,但我仍然收到 302。谢谢
  • 我用VS 2019创建了一个全新的.net核心网站,只在startup.cs中添加了3行,在WeatherForecastController中添加了[Authorize]。去 /weatherforecast 仍然会重定向 /account/login

标签: asp.net-core .net-core asp.net-core-3.1


【解决方案1】:

您可以更改您的services.AddCookie,如下所示:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.Events.OnRedirectToLogin = context =>
            {
                context.Response.StatusCode = 401;
                return Task.CompletedTask;
            };
        });

确保您的中间件顺序如下:

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

【讨论】:

    猜你喜欢
    • 2019-08-10
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2019-06-05
    • 2020-08-02
    • 2020-03-28
    • 2020-10-27
    • 2020-12-01
    相关资源
    最近更新 更多