Blazor页面元素授权——AuthorizeView 组件的使用

Blazor页面元素授权——AuthorizeView 组件的使用

上篇博客我们说到了blazor的身份认证的实现,对于AuthorizeView 组件来说,可以通过级联参数来获取包含了用户信息的AuthenticationState对象。

请注意,你需要引用Microsoft.AspNetCore.Components.Authorization Nuget包,并且在启动类中添加服务Services.AddAuthorizationCore();
使用CascadingAuthenticationState组件包裹App.razor中的代码:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" 
                DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

如果未指定授权条件,则 AuthorizeView 使用默认策略:

  • 将经过身份验证(已登录)的用户视为已授权。
  • 将未经过身份验证(已注销)的用户视为未授权。

基于角色的授权方式

角色的获取方式是多样的,可以来自项目本身,也可以来自外部的权限系统。总之,你需要清楚角色对应的权限本身范围,比如控制了哪些页面可以访问,哪些按钮是可见的。
请记住,仅在客户端进行权限控制并不是安全的。

在AuthorizeView组件中包裹需要验证角色才可以查看的组件

<AuthorizeView Roles="admin">
    <p>You can only see this if you're an admin or superuser.</p>
</AuthorizeView>

我个人是将认证与授权作为两个服务。授权服务根据系统码以及模块Id,调用权限管理系统接口,权限系统会根据当前用户来返回权限树,而我拿到权限树之后,会将其中的按钮或是页面的权限标识作为Roles,写入AuthenticationState当中,使用上面例子的方式,控制页面元素的展示。

下面附上完整的授权服务代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using ClientSideTemplate.Client.Foundation.Authentication.Model;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.WebAssembly.Http;
using Newtonsoft.Json;

namespace ClientSideTemplate.Client.Foundation.Authentication
{
    public class AuthorizedService
    {
        private readonly IServiceClient _serviceClient;
        private readonly AuthorizedOption _authorizedOption;

        public AuthorizedService(IServiceClient serviceClient, AuthorizedOption authorizedOption)
        {
            _serviceClient = serviceClient;
            _authorizedOption = authorizedOption;
        }

        public async Task AuthorizedAsync(AuthenticationState state)
        {
#if DEBUG
            var identity = new ClaimsIdentity(_authorizedOption.ModuleIds.Select(x => new Claim(ClaimTypes.Role, x)));
            state.User.AddIdentity(identity);
#else
            foreach (var moduleId in _authorizedOption.ModuleIds)
            {
                var userInfo = await GetUserInfo(_authorizedOption.SystemCode, moduleId);
                var identity = new ClaimsIdentity(userInfo.PrivilegeTree.Select(x => new Claim(ClaimTypes.Role, x.ModuleId)));
                state.User.AddIdentity(identity);
            }
#endif
        }

        private async Task<UserInfo> GetUserInfo(string systemCode, string moduleId)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, $"/login/Auth/UserInfo?systemCode={systemCode}&moduleId={moduleId}");
            request.SetBrowserRequestCredentials(BrowserRequestCredentials.Include);

            var response = await _serviceClient.SendAsync(request);
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
#if !DEBUG
                SignIn();
#endif
            }

            var content = await response.Content.ReadAsStringAsync();
            if (string.IsNullOrWhiteSpace(content))
            {
                return new UserInfo();
            }

            return JsonConvert.DeserializeObject<ApiResult<UserInfo>>(content).Result;
        }
    }
}

另外,如果你想在代码中获取AuthenticationState,请以级联参数的形式:

 [CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Blazor是一种基于WebAssembly的新型Web开发框架,可以使用C#语言开发客户端应用程序。它提供了一种方便的方式来实现cookie认证授权。 在Blazor应用程序中,您可以使用ASP.NET Core Identity来实现cookie认证授权。首先,您需要在ASP.NET Core应用程序中启用身份验证和授权。然后,您可以使用Identity提供的API来管理用户和角色,以及实现基于角色的授权策略。 接下来,您需要在Blazor组件使用`[Authorize]`属性来标记需要授权才能访问的组件。这将要求用户登录,并检查他们是否具有访问该组件的权限。 最后,您可以使用`HttpContext`类来访问当前用户的身份信息,以及验证他们是否具有所需的角色和权限。 下面是一个示例,演示如何在Blazor应用程序中使用cookie认证授权: ``` @page "/myprotectedpage" @attribute [Authorize(Roles = "Admin")] <h1>Welcome to the protected page!</h1> @code { [Inject] private IHttpContextAccessor HttpContextAccessor { get; set; } private ClaimsPrincipal User => HttpContextAccessor.HttpContext.User; protected override async Task OnInitializedAsync() { // Check if the user has the required role if (!User.IsInRole("Admin")) { NavigationManager.NavigateTo("/accessdenied"); } } } ``` 在上面的示例中,我们使用`[Authorize(Roles = "Admin")]`属性来标记需要“Admin”角色才能访问的组件。然后,我们使用`IHttpContextAccessor`来访问当前用户的身份信息,并检查他们是否具有所需的角色。如果用户没有所需的角色,我们将重定向到一个名为“accessdenied”的页面。 希望这个示例能够帮助您实现Blazor中的cookie认证授权
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值