在ASP.NET Core授权策略中不带.RequireAuthenticatedUser()使用.RequireRole()是否安全? [英] Is it safe to use .RequireRole() without .RequireAuthenticatedUser() in ASP.NET Core authorization policies?
问题描述
在 Startup.cs 中定义了一些策略,例如:
There are some policies defines in Startup.cs like:
services.AddAuthorization(options =>
{
options.AddPolicy("UsersEdit", policy => policy
.RequireAuthenticatedUser()
.RequireRole("Admin"));
});
将这段代码重写为以下内容是否安全:
Is it safe to rewrote this code to:
services.AddAuthorization(options =>
{
options.AddPolicy("UsersEdit", policy => policy.RequireRole("Admin"));
});
我想未经授权的用户不能具有任何角色.
I guess that unauthorized user can't have any roles.
推荐答案
如果我们在
If we check the source code for the authorization requirement that gets added by RequireAuthenticatedUser
at https://github.com/aspnet/AspNetCore/blob/c376e833e46497fbec4bd7b39632f8c8e13360b2/src/Security/Authorization/Core/src/DenyAnonymousAuthorizationRequirement.cs:
var user = context.User;
var userIsAnonymous =
user?.Identity == null ||
!user.Identities.Any(i => i.IsAuthenticated);
if (!userIsAnonymous)
{
context.Succeed(requirement);
}
它添加了一个检查,确认用户必须具有身份,并且其中之一必须说出该用户已通过身份验证.
It adds a check that user must have an identity, and that one of them must say the user is authenticated.