在ASP.NET Core授权策略中不带.RequireAuthenticatedUser()使用.RequireRole()是否安全? [英] Is it safe to use .RequireRole() without .RequireAuthenticatedUser() in ASP.NET Core authorization policies?

查看:48
本文介绍了在ASP.NET Core授权策略中不带.RequireAuthenticatedUser()使用.RequireRole()是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

推荐答案

如果我们在RequireAuthenticatedUser 添加的授权要求的源代码.com/aspnet/AspNetCore/blob/c376e833e46497fbec4bd7b39632f8c8e13360b2/src/Security/Authorization/Core/src/DenyAnonymousAuthorizationRequirement.cs"rel =" nofollow noreferrer> https://github.com/aspnet/AspNetCore/blob/c3394ef3c/fbc4e8f3c8e8f3c8e8e8fc3e8e8e8e安全性/授权/核心/src/DenyAnonymousAuthorizationRequirement.cs :

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.

IsAuthenticated

如果AuthenticationType属性不为null或为空字符串,则为true.

true if the AuthenticationType property is not null or an empty string.

因此,从理论上讲,用户可以通过具有没有身份验证类型的身份来扮演角色.但实际上,这不应该发生.任何合理的身份验证处理程序都不会将AuthenticationType保留为空,因为这样 IsAuthenticated 会返回 false .

So in theory a user could have a role by having an identity that has no authentication type. But in practice, that should not happen. Any reasonable authentication handler would not leave AuthenticationType empty, since then IsAuthenticated would return false.

这篇关于在ASP.NET Core授权策略中不带.RequireAuthenticatedUser()使用.RequireRole()是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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