Blazor WebAssembly阻止WebApi的AllowAnonymous
创始人
2024-12-20 20:31:15
0

在Blazor WebAssembly中,如果想要阻止WebApi方法的AllowAnonymous特性生效,可以通过自定义一个AuthorizationMessageHandler来实现。

首先,创建一个名为CustomAuthorizationMessageHandler的类,继承自AuthorizationMessageHandler。

using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.Extensions.Logging;

public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
{
    public CustomAuthorizationMessageHandler(IAccessTokenProvider provider, 
        ILoggerFactory loggerFactory, 
        NavigationManager navigationManager, 
        IAuthorizationService authorizationService)
        : base(provider, loggerFactory, navigationManager, authorizationService)
    {
        ConfigureHandler();
    }

    private void ConfigureHandler()
    {
        // 在这里可以自定义处理逻辑来阻止AllowAnonymous特性生效
        // 例如,可以检查当前请求的URL是否为WebApi的URL,然后判断是否需要进行授权

        // 这里是一个示例,假设WebApi的URL路径为/api
        // 如果请求的URL路径包含/api,则不允许AllowAnonymous特性生效
        var apiPath = "/api";
        if (NavigationManager.Uri.Contains(apiPath))
        {
            ConfigureHandler(new[] { apiPath });
        }
    }
}

接下来,在Program.cs文件中,注册CustomAuthorizationMessageHandler。

using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace BlazorApp
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add("#app");

            builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

            // 注册自定义的AuthorizationMessageHandler
            builder.Services.AddHttpClient("ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
                .AddHttpMessageHandler();

            await builder.Build().RunAsync();
        }
    }
}

现在,CustomAuthorizationMessageHandler将会在每个请求之前进行检查,并阻止AllowAnonymous特性生效。你可以根据自己的需求,在ConfigureHandler方法中添加自定义的逻辑进行授权判断。

相关内容

热门资讯

黑科技科技(wepoke智能a... 黑科技科技(wepoke智能ai)wepower使用说明书(wepOkE)素来是真的有挂(确实有挂)...
黑科技模拟器(wepoke智能... WePoker透视辅助工具核心要点解析‌,黑科技模拟器(wepoke智能ai)wepoke是机器发牌...
黑科技脚本(wepokeai代... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款游戏中打牌都...
黑科技辅助挂(wepoke真的... 黑科技辅助挂(wepoke真的有挂)wepoke 软件(wEPOKE)固有真的有挂(有挂猫腻)-哔哩...
黑科技辅助挂(wepoke黑科... 黑科技辅助挂(wepoke黑科技)wepoke软件透明挂演示(wEpOke)一直真的有挂(真的有挂)...
黑科技app(wepoke真的... 此外,数据分析德州()辅助神器app还具备辅助透视行为开挂功能,通过对客户透明挂的深入研究,你可以了...
黑科技智能ai(wepoke辅... 黑科技智能ai(wepoke辅助插件)wepoke软件透明(WEPOke)先前是有挂(果真有挂)-哔...
黑科技模拟器(wepoke透明... 黑科技模拟器(wepoke透明黑科技)wepoke德州扑克用ai代打(WEPOKE)最初存在有挂(有...
黑科技插件(wepoke辅助插... 黑科技插件(wepoke辅助插件)wepoke软件透明(WEPOke)从来是真的有挂(有挂解惑)-哔...
黑科技美元局(wepoke智能... 黑科技美元局(wepoke智能ai)wepoke辅助真的假的(wepoKE)原先真的有挂(竟然有挂)...