Blazor授权动态添加策略声明
创始人
2024-12-21 18:00:12
0

Blazor是一个流行的Web框架,允许我们使用声明式授权来保护应用程序的资源。在实践中,我们可能需要动态添加策略声明,以根据运行时条件实现细粒度的控制。

首先,我们需要在服务器端或客户端中注册自定义策略。例如,以下代码演示了如何在客户端启动时动态添加策略声明:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
using Microsoft.Extensions.DependencyInjection;
using System.Security.Claims;

public class CustomClaimsPrincipalFactory : ServerAuthenticationStateProvider
{
  public CustomClaimsPrincipalFactory(IServiceProvider serviceProvider)
  : base(serviceProvider)
  {
  }

  public async override Task GetAuthenticationStateAsync()
  {
      var identity = new ClaimsIdentity(new[]
      {
          new Claim(ClaimTypes.Name, "John Doe"),
      }, "some-authentication-type");

      var user = new ClaimsPrincipal(identity);

      return new AuthenticationState(user);
  }
}

public class Startup
{
  public void ConfigureServices(IServiceCollection services)
  {
      services.AddAuthorization(options =>
      {
          options.AddPolicy("Permission", policy =>
          {
              policy.RequireClaim("Permission");
          });
      });

      services.AddScoped();

      services.AddMvc().AddRazorPagesOptions(options =>
      {
          options.Conventions.AuthorizeFolder("/secure");
      });

      services.AddServerSideBlazor()
          .AddCircuitOptions(options =>
          {
              options.DetailedErrors = true;
          });
  }

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
      app.UseRouting();

      app.UseEndpoints(endpoints =>
      {
          endpoints.MapBlazorHub();
          endpoints.MapFallbackToPage("/_Host");
      });
  }
}

在以上示例中,我们添加了一个名为“Permission”的策略声明,该声明要求用户具有一个名为“Permission”的声明。然后,我们将自定义ClaimsPrincipalFactory注入到Blazor服务中。

在组件中使用此策略声明

相关内容

热门资讯

详细说明!wepoker破解游... 详细说明!wepoker破解游戏盒子,hardrock作弊,科技教程(有挂攻略);最新版2024是一...
今日头条!德普辅助器辅助器怎么... 今日头条!德普辅助器辅助器怎么用,we poker游戏下,科技教程(有挂方法);人气非常高,ai更新...
玩家必看攻略!wepoker脚... 玩家必看攻略!wepoker脚本下载,hhpoker俱乐部是干嘛的,扑克教程(有挂教程)1、玩家可以...
推荐一款!hhpoker有作弊... 推荐一款!hhpoker有作弊的吗,wepoker透视版下载,揭秘攻略(有挂技巧);原来确实真的有挂...
最新通报!wepoker有透视... 最新通报!wepoker有透视吗,wejoker透视方法,揭秘教程(有挂神器);玩家必备必赢加哟《1...
新手必备!fishpoker透... 新手必备!fishpoker透视底牌,wepoker开辅助能查到吗,普及教程(有挂神器)这是由厦门游...
交流学习经验!德扑圈有透视吗,... 1、交流学习经验!德扑圈有透视吗,hhpoker万能辅助器,德州教程(有挂技巧);详细教程。2、hh...
程序员教你!pokermast... 1、程序员教你!pokermaster脚本,大菠萝辅助器,教你攻略(有挂技巧)。2、大菠萝辅助器透视...
必备攻略!wepoker有辅助... 必备攻略!wepoker有辅助吗,德普之星app安卓版破解版,详细教程(有挂教程)1、许多玩家不知道...
实测交流!黑侠破解wepoke... 实测交流!黑侠破解wepoker,wepoker俱乐部辅助器,力荐教程(有挂软件)1、玩家可以在we...