BlazorWASM中使用现有JWT授权添加Google认证存在问题。
创始人
2024-12-21 22:30:05
0
  1. 首先需要在Google Cloud Console中创建OAuth 2.0客户端ID,并添加回调URI。
  2. 在Blazor WASM项目中安装以下NuGet包:
    • Microsoft.AspNetCore.Authentication.Google
    • Microsoft.AspNetCore.Components.Authorization
  3. 创建AuthService类,从AuthenticationStateProvider接口继承并实现GetAuthenticationStateAsync方法。在此方法中,可以使用JWT令牌从服务器检索用户的身份验证状态。
    public class AuthService : AuthenticationStateProvider
    {
        private readonly HttpClient httpClient;
        private readonly ILocalStorageService localStorage;
    
        public AuthService(HttpClient httpClient, ILocalStorageService localStorage)
        {
            this.httpClient = httpClient;
            this.localStorage = localStorage;
        }
    
        public override async Task GetAuthenticationStateAsync()
        {
            var accessToken = await localStorage.GetItemAsync("access_token");
    
            // 如果访问令牌未过期,从服务器检索用户信息
            if (!string.IsNullOrEmpty(accessToken))
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
    
                var userData = await httpClient.GetFromJsonAsync("api/UserData");
    
                if (userData != null && !string.IsNullOrEmpty(userData.Email))
                {
                    var claims = new[] { new Claim(ClaimTypes.Name, userData.Email) };
                    var identity = new ClaimsIdentity(claims, "GoogleAuth");
                    return new AuthenticationState(new ClaimsPrincipal(identity));
                }
            }
    
            // 如果没有登录,返回未认证的AuthenticationState
            return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
        }
    }
    
  4. 在startup.cs文件中,配置Google认证模式和服JWT令牌。
    private const string GoogleClientId = "";
    private const string GoogleClientSecret = "";
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(o =>
        {
            o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddGoogle(options =>
        {
            options.ClientId = GoogleClientId;
            options.ClientSecret = GoogleClientSecret;
        });
    
        // 添加Jwt验证
        services.AddAuthorizationCore(options =>
        {
            options.AddPolicy("JwtAuth", policy =>
            {
                policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
                policy.RequireAuthenticatedUser();
            });
        });
    
        services.AddControllers();
        services.AddHttpClient();
        services.AddHttpContextAccessor();
        services.Add BlazoredLocalStorage();
        services.AddScoped();
        services.AddScoped();
    
    }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseHttpsRedirection();
        app.UseBlazorFrameworkFiles();
        app.UseStaticFiles();
    
        app.UseRouting();
    
        app.UseAuthentication();
        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapFallbackToFile("index.html");
        });
    }
    
  5. 在组件中使用AuthService和AuthorizeView组件。
    @inject AuthService authService
    ...
    
        
            

    Hello, @context.User.Identity.Name!

    Please log in.

    Login
    ... @code { private AuthenticationState authState; protected override async Task OnInitializedAsync() { authState = await authService.GetAuthenticationStateAsync(); authService.AuthStateChanged

相关内容

热门资讯

黑科技攻略(德州之星)外挂辅助... 黑科技攻略(德州之星)外挂辅助神器(透视)透明挂教程(竟然有挂)1、起透看视 德州之星透明视辅助2、...
黑科技代打(wepOkE)黑科... 黑科技代打(wepOkE)黑科技透明挂辅助挂(透视)透牌教程(竟然真的是有挂)1、用户打开应用后不用...
黑科技系统!(aapokEr)... 黑科技系统!(aapokEr)透明挂辅助器,(AAPOkER)从来真的有挂,2025版教程(有挂技巧...
黑科技工具(we poker)... 黑科技工具(we poker)黑科技透明挂辅助软件(透视)黑科技教程(一直是真的有挂)1、不需要AI...
黑科技讲解!(德扑)外挂辅助a... 黑科技讲解!(德扑)外挂辅助app,(德扑)原来存在有挂,解密教程(有挂方法);致您一封信;亲爱德扑...
黑科技攻略(红龙扑克)外挂辅助... 黑科技攻略(红龙扑克)外挂辅助方法(透视)揭秘教程(其实有挂)1、红龙扑克透视辅助简单,红龙扑克软件...
黑科技有挂!(wEpoKe)软... 黑科技有挂!(wEpoKe)软件透明挂,(WePoKer)素来是有挂,解说技巧(有挂技巧),支持语音...
黑科技好牌(微扑克私人局)外挂... 黑科技好牌(微扑克私人局)外挂透视辅助神器(透视)新2025教程(总是是真的有挂);1、该软件可以轻...
黑科技插件!(wPK)透视辅助... 黑科技插件!(wPK)透视辅助器,(wpK)原生存在有挂,攻略教程(有挂教程);《WPK辅助透视》‌...
黑科技线上(WepOke)黑科... 黑科技线上(WepOke)黑科技透明挂辅助挂(透视)可靠技巧(一直真的是有挂)1、用户打开应用后不用...