[英]When not authorized always return a 401
When not authorized I want to always return a 401, currently this only happens when I go to a path that is exists.如果未获得授权,我想始终返回 401,目前这仅在我转到存在的路径时发生。 How do I make it so that when I go to a path that doesn't exist it also returns a 401.
我如何做到这一点,以便当我转到不存在的路径时,它也会返回 401。
Note: I am currently using only 1 custom authentication handler that implements AuthenticationHandler<T>
.注意:我目前只使用 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 ();
}
If you're just interested in whether or not the user is authenticated , you could add a custom middleware to the pipeline that converts a 404 into a 401. Here's a simple example:如果您只对用户是否通过身份验证感兴趣,您可以向管道添加一个自定义中间件,将 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();
}
The custom middleware sits in front of the MVC middleware, waits for that to run and then converts the 404 into a 401 if the user has not been authenticated.自定义中间件位于 MVC 中间件前面,等待它运行,然后如果用户尚未通过身份验证,则将 404 转换为 401。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.