Replies: 1 comment 1 reply
|
There are two separate concerns here: composing layouts and enforcing authorization. Blazor supports the first directly, but a layout should not be your only security boundary. If the check is a normal policyPrefer ASP.NET Core authorization and leave the existing layout alone: @page "/secured-page"
@attribute [Authorize(Policy = "CanViewSecuredPage")]
@layout MainLayoutWith If the decision needs a runtime resource/contextAn attribute runs before a page-specific resource has been loaded, so use resource-based authorization with @using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@inject IAuthorizationService Authorization
@if (_allowed is null)
{
<p>Checking access...</p>
}
else if (_allowed.Value)
{
<PageContent />
}
else
{
<AccessDenied />
}
@code {
[CascadingParameter]
private Task<AuthenticationState> AuthenticationState { get; set; } = default!;
[Parameter]
public MySecurityContext Context { get; set; } = default!;
private bool? _allowed;
protected override async Task OnParametersSetAsync()
{
var user = (await AuthenticationState).User;
var result = await Authorization.AuthorizeAsync(
user, Context, "CanAccessContext");
_allowed = result.Succeeded;
}
}The policy handler can internally call your A small reusable If you only need to preserve both visual layoutsLayouts can be nested. Your access layout can itself use the existing layout: @* AccessLayout.razor *@
@inherits LayoutComponentBase
@layout MainLayout
<PermissionView Context="CurrentContext">
<Authorized>
@Body
</Authorized>
<NotAuthorized>
<AccessDenied />
</NotAuthorized>
</PermissionView>Then the page selects The nested-layout option is useful for shared presentation, but there are two important security rules:
So the usual choice is: policy + If this gives you the structure you need, you can mark it as the accepted answer so the authorization/layout distinction is easy for future readers to find. |
Uh oh!
There was an error while loading. Please reload this page.
I need to use my own layout component on a page, derived from LayoutComponentBase, to perform access checks. The idea was to create something similar to the Authorize attribute, but one that accepts my context and required permissions, and the check itself would simply call my SecurityManager.HasAccess. If access is denied, it would render an AccessDenied component; otherwise, it would render the Body.
The problem is that the page already uses a specific layout responsible for the overall page structure, and I cannot remove it. Because of that, I cannot apply my own layout through layout attribute. The way with inheritance also doesn't work. Moreover, the option using a separate wrapper component is not a very beautiful option.
Question:
What is the correct way to implement this kind of access check when the page already uses a layout?
All reactions