asp.net-core - 如何创建代表登录用户的 Asp.Net 身份策略?
问题描述
我有一个稍微不寻常的要求:我需要在 Asp.Net Identity 中创建一个代表登录用户的策略。我希望这个优先于实际检查用户是否登录,所以我希望能够做到:
<SomeContent>
// This should be visible to anyone, whether logged in or not
</SomeContent
<AuthorizeView Policy="LoggedInUser">
// This should be visible only to logged in users
// unless the 'no policies' config option is enabled
</AuthorizeView>
<MoreContent>
// This should be visible to anyone, whether logged in or not
</MoreContent
我想使用策略的原因是我的应用程序可以选择禁用策略和角色(对于不关心它们的人)。我可以通过在启动时检查配置来做到这一点,如果启用了“无角色/策略”配置设置,我可以这样做:
if( opts.UseRolesAndPolicies() == true )
{
// Roles/policies are disabled, so return true whenever the policy is checked
config.AddPolicy("LoggedInUser, policy =>
policy.RequireAssertion(context => true));
}
else
{
// Define a policy that only returns true if the user is logged in
config.AddPolicy("LoggedInUser, policy =>
policy.RequireAssertion(context =>
/* WHAT GOES HERE?!? */ ));
}
这将允许每个人访问授权内容,无论他们是否已登录、成员或角色等。
问题是,当未设置“无角色/策略”选项时,如何定义表示“如果用户登录则允许”的策略?我将在 AddPolicy 检查中使用什么来查看用户是否已登录?我想我可以使用该RequireAssertion
方法,并在函数中检查用户的 authenticationStateProvider,但是有更好的方法吗?我在 Blazor 服务器应用程序中执行此操作,如果它有所作为(可能不是......)。
解决方案
实际上......我看到你在这里做了config.AddPolicy("LoggedInUser, policy => policy.RequireAssertion(context => true));
,这就是你添加策略的方式。
如果你想根据你的一些配置修改策略appSettings
,这描述了这个想法
// Define policies, you can have multiple policy, register as many as you want
services.AddAuthorization(opts =>
{
var section = configuration.GetSection("yourSection");
if (string.IsNullOrEmpty(section["haveConfigRole?"]))
{
opts.AddPolicy("DefaultPolicy", p =>
{
p.RequireAuthenticatedUser();
p.RequireRole(section["haveConfigRole?"]);
p.RequireRole(section["haveConfigRole?"]);
p.RequireRole(section["haveConfigRole?"]);
});
}
else
{
opts.AddPolicy("DefaultPolicy", p =>
{
p.RequireAuthenticatedUser();
});
}
});
// Using some specific policy:
[Authorize(Policy = "DefaultPolicy")]
推荐阅读
- java - 逐字读取一个文本文件,并将这个单词放在一个列表中,然后用 java 放到另一个文本文件中
- flutter - 对 DropdownButtons 的项目列表的边缘进行四舍五入
- android-fragments - ArrayAdapter.ArrayAdapter(Context,int,int) 不适用 | 怎么修
- javascript - 通过机器人框架运行验证时,如何确保属于验证器所在类的属性是可变的?
- java - SQL 错误:17068 在休眠中插入记录时
- android-permissions - 我应该请求读取或写入权限以访问 Android Q 中的 Mediastore 图像吗?
- github - 通过 ssh 推送;连接关闭。fata:无法从远程存储库中读取
- elasticsearch - 如何在 Elasticsearch 中使用 search_analyzer 替换希腊字母同义词
- linux - linux在其他文件夹中重命名和移动具有特定扩展名的文件并对每个文件执行命令 - ocrmypdf
- system-verilog - 如何将队列中的值添加到 systemverilog 功能覆盖 ignore_bins/illegal_bins?