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

相关内容

热门资讯

7分钟了解(aa扑克伙牌)外挂... 7分钟了解(aa扑克伙牌)外挂辅助插件安装神器(透视)新2025教程(2023已更新)(哔哩哔哩),...
2分钟了解(wpK)外挂智能a... 2分钟了解(wpK)外挂智能ai辅助软件(透视)必胜教程(2025已更新)(哔哩哔哩);1.wpK ...
第九分钟了解(wEpoke)黑... 第九分钟了解(wEpoke)黑科技透明挂辅助软件(透视)必赢教程(2026已更新)(哔哩哔哩);第九...
第十分钟了解(推扑克)外挂辅助... 第十分钟了解(推扑克)外挂辅助插件安装ai(透视)软件教程(2020已更新)(哔哩哔哩)是一款可以让...
第六分钟了解(wepokerp... 第六分钟了解(wepokerplus)软件透明挂辅助软件(透视)安装教程(2022已更新)(哔哩哔哩...
第十分钟了解(werplan)... 第十分钟了解(werplan)外挂智能ai辅助科技(透视)wepoke教程(2020已更新)(哔哩哔...
一分钟了解(aapoker透明... 一分钟了解(aapoker透明挂)外挂辅助插件安装神器(透视)2025版教程(2025已更新)(哔哩...
第七分钟了解(WPK)外挂智能... 您好:wepoke这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别...
十分钟了解(we辅助poker... 十分钟了解(we辅助poker)外挂智能ai辅助神器(透视)揭秘教程(2026已更新)(哔哩哔哩);...
四分钟了解(菠萝德州)外挂透明... 四分钟了解(菠萝德州)外挂透明挂辅助黑科技(透视)新2025版(2021已更新)(哔哩哔哩);超受欢...