Blazor Wasm Google 登录

发布时间 2024-01-12 05:50:19作者: AlexChow

1. 以下11个步骤为基础步骤,之后文章不再赘述

2. 创建Blazor wasm工程

身份验证不用选择, 创建工程完成.

3. 添加包

右键点工程, 管理Nuget程序包, 搜索 Microsoft.AspNetCore.Components.WebAssembly.Authentication 安装

4. 加入鉴权脚本

编辑 wwwroot\index.html 文件, 在 <script src="_framework/blazor.webassembly.js"></script> 上一句加入这行代码

<script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>

5. 导入命名空间

_Imports.razor

@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Authorization

6. 登录页面代码

Pages\Home.razor

@page "/"
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject NavigationManager Navigation
@inject IAccessTokenProvider TokenProvider

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

<AuthorizeView>
    <Authorized>
        Hello, @context.User.Identity?.Name!
        <button class="btn btn-link" @onclick="BeginLogOut">注销</button>
    </Authorized>
    <NotAuthorized>
        <button class="btn btn-link" @onclick="Login">登录</button>
    </NotAuthorized>
</AuthorizeView>

<p>@output</p>
<button @onclick="DisplayToken">Display Access Token </button>

@code{

    private void Login()
    {
        Navigation.NavigateToLogout("authentication/login");
    }

    private void BeginLogOut()
    {
        Navigation.NavigateToLogout("authentication/logout");
    }

    private string? output;

    private async Task DisplayToken()
    {
        var tokenResult = await TokenProvider.RequestAccessToken();

        if (tokenResult.TryGetToken(out var token))
        {
            output = token.Value;

        }
        else
        {
            output = "No token";
        }
    }

}

7. 跳转登录组件

Layout 下新建 RedirectToLogin.razor

@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject NavigationManager Navigation

@code {
    protected override void OnInitialized()
    {
        Navigation.NavigateToLogin("authentication/login");
    }
}

8. 跳转登录组件

Layout 下新建 RedirectToLogin.razor

9. 登录组件

Pages 下新建 Authentication.razor

@page "/authentication/{action}"
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
<RemoteAuthenticatorView Action="@Action" />

@code{
    [Parameter] public string? Action { get; set; }
}

10. App.razor 文件

原始文件

最终文件

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    @if (context.User.Identity?.IsAuthenticated != true)
                    {
                        <RedirectToLogin />
                    }
                    else
                    {
                        <p role="alert">You are not authorized to access this resource.</p>
                    }
                </NotAuthorized>
            </AuthorizeRouteView>
            <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        </Found>
        <NotFound>
            <PageTitle>Not found</PageTitle>
            <LayoutView Layout="@typeof(MainLayout)">
                <p role="alert">Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

11. 修改调试地址

由于我们码云后台回调地址填写的是 https://localhost:5001/authentication/login-callback

所以 Properties\launchSettings.json 也修改为同样端口

https配置的applicationUrl改为

"applicationUrl": "https://localhost:5001;http://localhost:5004",

12. 创建 Google 应用

打开Google账号 API和服务页面 https://console.cloud.google.com/apis/dashboard

点击创建凭据

OAuth 2.0 客户端 ID

已获授权的重定向 URI 填写等下用到的本机测试地址 https://localhost:5001/authentication/login-callback

复制 客户端 ID 备用, 例如我的是 10599-**.apps.googleusercontent.com , 下一步需要填写.

13. 加入配置

编辑 Program.cs 文件在最后一句 await builder.Build().RunAsync(); 之前加入以下代码

builder.Services.AddOidcAuthentication(options =>
{
    options.ProviderOptions.Authority = "https://accounts.google.com/";
    options.ProviderOptions.ClientId = "10****599-******.apps.googleusercontent.com";
    options.ProviderOptions.ResponseType = "id_token token";
    options.ProviderOptions.RedirectUri = "https://localhost:5001/authentication/login-callback";
    options.UserOptions.AuthenticationType = "google";
});

14. 运行工程