未经授权时,始终返回401

时间:2018-08-29 08:54:58

标签: c# authentication asp.net-core asp.net-core-2.1

未经授权时,我想始终返回401,目前仅当我转到存在的路径时才会发生。 如何做到这一点,以便当我走到一条不存在的路径时,它也会返回401。

注意:我目前仅使用1个实现AuthenticationHandler<T>的自定义身份验证处理程序。

public void ConfigureServices (IServiceCollection services)
 {
     services
         .AddMvc (options =>
         {
             var policy = new AuthorizationPolicyBuilder ().RequireAuthenticatedUser ().Build ();
             options.Filters.Add (new AuthorizeFilter (policy));
         })
         .SetCompatibilityVersion (CompatibilityVersion.Version_2_1);

     services
         .AddAuthentication (options =>
         {
             options.DefaultAuthenticateScheme = CustomAuthenticationHandler.AuthenticationScheme;
             options.DefaultChallengeScheme = CustomAuthenticationHandler.AuthenticationScheme;
         })
         .AddScheme<TicketAuthenticationOptions, CustomAuthenticationHandler> (CustomAuthenticationHandler.AuthenticationScheme, null);
 }

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

1 个答案:

答案 0 :(得分:1)

如果您只是对用户是否经过身份验证感兴趣,可以向管道中添加自定义中间件,以将404转换为401。下面是一个简单的示例:

public void Configure(IApplicationBuilder app)
{
    app.UseAuthentication();

    app.Use(async (ctx, next) =>
    {
        await next();

        if (ctx.Response.StatusCode == 404 && !ctx.User.Identity.IsAuthenticated)
            ctx.Response.StatusCode = 401;
    });

    app.UseMvc();
}

自定义中间件位于MVC中间件的前面,等待 运行,如果用户未通过身份验证,则将404转换为401。

相关问题