在Asp.Net Core 2中使用JwtBearer身份验证时,返回401而不是重定向到登录页面 [英] Return 401 instead of redirect to login page when using JwtBearer authentication in Asp.Net Core 2

查看:611
本文介绍了在Asp.Net Core 2中使用JwtBearer身份验证时,返回401而不是重定向到登录页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在启动我有

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = Configuration["Jwt:Issuer"],
        ValidAudience = Configuration["Jwt:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
    };
});

及以后的

app.UseAuthentication();

两个问题

  1. 如何将授权设置为默认启用,但具有[AllowAnonymous]的控制器/操作除外?
  2. 如何使代码返回401,而不是重定向到登录"页面?

对此有很多问题和答案,但它们似乎总是与具有许多身份验证方案的网站有关,例如cookie和jwt.我有一个纯jwt身份验证的后端,只有令牌发行者终结点可以进行匿名访问,其他所有内容都经过身份验证和授权.

There are many questions and answers regarding this but they always seems to be about site with many authentication schemes, like both cookie and jwt. I have a pure jwt authenticated backend and only the token issuer endpoint will have anonymous access, everything else is authenticated and authorized.

推荐答案

我需要配置 StatusCodePages 中间件,以避免重定向.

I needed to configure the StatusCodePages middleware to avoid the redirect.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    app.UseStatusCodePages();
    ...
}

这篇关于在Asp.Net Core 2中使用JwtBearer身份验证时,返回401而不是重定向到登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆