gpt4 book ai didi

c# - 在代码后面执行授权检查

转载 作者:行者123 更新时间:2023-12-03 08:48:21 25 4
gpt4 key购买 nike

在 blazor 页面中,如果用户有特定策略,我想(显示/隐藏/设置为只读/更改样式...等)文本框因此,为了实现(显示和隐藏),我执行了以下操作:

 <AuthorizeView Policy="CanReadNamePolicy">
<Authorized Context="test">
<inputText @Bind-Value="@Name"/>
</Authorized>
</AuthorizeView>

但问题是我必须对每个策略重复此操作,如果同一用户处于多个策略中怎么办

所以我想到将这个逻辑移到后面的代码并使用属性来设置文本框,但是我找不到在后面的代码中进行授权检查的方法

所以我应该有这样的东西

 if ((await Authorize("PolicyName")).Succeeded)
{
ReadOnlyAttr = "readonly";
}

是否有可能在代码后面执行授权检查

最佳答案

以下是如何执行此操作的代码片段:

If the app is required to check authorization rules as part of procedural logic, use a cascaded parameter of type Task to obtain the user's ClaimsPrincipal. Task can be combined with other services, such as IAuthorizationService, to evaluate policies.

@inject IAuthorizationService AuthorizationService

<button @onclick="@DoSomething">Do something important</button>

@code {
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }

private async Task DoSomething()
{
var user = (await authenticationStateTask).User;

if ((await AuthorizationService.AuthorizeAsync(user, "CanReadNamePolicy"))
.Succeeded)
{
// Perform an action only available to users satisfying the
// 'CanReadNamePolicy' policy.
}
}
}

注意:

  1. InputText 组件必须驻留在 EditForm 组件内。
  2. 这是@bind-Value而不是@Bind-Value
  3. 一项政策可以评估多项要求...您仍然可以使用 AuthorizeView 评估一项政策中的多项要求。

关于c# - 在代码后面执行授权检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60470656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com