Maro
Maro

Reputation: 2629

perform authorization check in code behind

In a blazor page, i want to (show/hide/set to read only/change style...etc) a text box if user has specific policy so to achieve (show and hide) i did the following:

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

but the problem i have to repeat this for every policy, also what if same user is in multiple policies

So i thought of moving this logic to the code behind and use attributes to set the text box, but i couln't find a away to do the authorization check in the code behind

so i should have something like this

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

any idea if possible to perform the authorize check in code behind

Upvotes: 5

Views: 3741

Answers (1)

enet
enet

Reputation: 45626

Here's a code snippet how you can do it:

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.
    }
}
}

Note:

  1. The InputText component must resides within an EditForm component.
  2. It's @bind-Value not @Bind-Value
  3. A policy can evaluate multiple requirements... You can still use the AuthorizeView to evaluate multiple requirements in a single policy.

Upvotes: 9

Related Questions