使用ASP.Net Core中的Authorize属性返回HTTP 403 [英] Return HTTP 403 using Authorize attribute in ASP.Net Core
问题描述
使用ASP.Net WebAPI时,我曾经有一个自定义Authorize
属性我将根据情况返回HTTP 403
或401
.例如如果用户未通过身份验证,则返回401
;否则,返回401
.如果用户已通过身份验证但没有适当的权限,则返回403
. 请参阅此处以获取更多讨论.
现在看来,在新的ASP.Net Core中,它们不希望您覆盖Authorize
属性不再支持基于策略的方法.但是,Core MVC似乎也遭受了其前辈同样的仅对所有auth错误返回401
"的方法.
如何覆盖框架以获得所需的行为?
在打开问题在此处,看来这实际上应该可以工作.
在您的Startup.Configure
中,如果您只是调用app.UseMvc()
而没有注册任何其他中间件,则对于任何与auth相关的错误(未认证,已认证但没有权限),您都会得到401
.
但是,如果您注册了支持它的身份验证中间件之一,则未经身份验证的将正确获得401
,而对于没有权限的则会获得403
.对我来说,我使用了JwtBearerMiddleware
,它允许通过 JSON Web令牌进行身份验证.关键部分是在创建中间件时设置AutomaticChallenge
选项:
Startup.Configure
中:app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
app.UseMvc();
AutomaticAuthenticate
将自动设置ClaimsPrincipal
,以便您可以在控制器中访问User
. AutomaticChallenge
允许auth中间件在发生auth错误时修改响应(在这种情况下,请适当地设置401
或403
).
如果要实现自己的身份验证方案,则可以从AuthenticationMiddleware
和AuthenticationHandler
继承,类似于custom Authorize
attribute I would use to return either an HTTP 403
or 401
depending on the situation. e.g. if the user is not authenticated, return a 401
; if the user is authenticated but doesn't have the appropriate permissions, return a 403
. See here for more discussion on that.
It seems now, in the new ASP.Net Core, they don't want you overriding the Authorize
attribute anymore instead favoring a policy-based approach. However, it seems Core MVC suffers from the same "just return 401
for all auth errors" approach its predecessors have.
How do I override the framework to get the behavior I want?
After opening an issue here, it appears this actually should work...sort of.
In your Startup.Configure
, if you just call app.UseMvc()
and don't register any other middleware, you will get 401
for any auth-related errors (not authenticated, authenticated but no permission).
If, however, you register one of the authentication middlewares that support it, you will correctly get 401
for unauthenticated and 403
for no permissions. For me, I used the JwtBearerMiddleware
which allows authentication via a JSON Web Token. The key part is to set the AutomaticChallenge
option when creating the middleware:
in Startup.Configure
:
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
app.UseMvc();
AutomaticAuthenticate
will set the ClaimsPrincipal
automatically so you can access User
in a controller. AutomaticChallenge
allows the auth middleware to modify the response when auth errors happen (in this case setting 401
or 403
appropriately).
If you have your own authentication scheme to implement, you would inherit from AuthenticationMiddleware
and AuthenticationHandler
similar to how the JWT implementation works.
这篇关于使用ASP.Net Core中的Authorize属性返回HTTP 403的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!