首页 > 解决方案 > 如何创建代表登录用户的 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 服务器应用程序中执行此操作,如果它有所作为(可能不是......)。

标签: asp.net-coreasp.net-identity

解决方案


实际上......我看到你在这里做了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")]

推荐阅读