仅对 Google Drive 将 Blazor OIDC 身份验证与 Google OAuth 结合使用

时间:2021-03-26 08:04:00

标签: google-oauth blazor openid-connect

在我的 Blazor WASM 应用中,我使用 OIDC 身份验证登录 Google Drive,如下所述:

Secure an ASP.NET Core Blazor WebAssembly standalone app with the Authentication library

Google Auth error getting access token in Blazor

Cannot log in or get access token with Google Authorization on Blazor WASM Standalone app

但是我不想用

<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
    <NotAuthorized>
        @if (!context.User.Identity.IsAuthenticated)
        {
            <RedirectToLogin />
        }
    </NotAuthorized>
</AuthorizeRouteView>

因为我不想限制用户访问我的 Blazor 页面。

最重要的是:我不希望用户在未登录时看到“授权...”消息几秒钟 - 登录是可选的。

如果用户决定使用 Google Drive,我只需要 Google OAuth 登录,这样我就可以获得访问令牌。

如何仅使用 OIDC 身份验证来获取 Google Drive 的访问令牌?

如果这不可能,我可以使用 C# 登录 Google 吗,就像这里在 JavaScript 中看到的那样?

OAuth 2.0 for Client-side Web Applications

1 个答案:

答案 0 :(得分:1)

以下建议可能有效。如果没有,请报告更多问题,我会努力改进...

在您的 App.razor 文件中进行以下更改:

替换:

<AuthorizeRouteView RouteData="@routeData" 
                               DefaultLayout="@typeof(MainLayout)">
            <NotAuthorized>
                @if (!context.User.Identity.IsAuthenticated)
                {
                    <RedirectToLogin />
                }
                else
                {
                    <p>You are not authorized to access this resource.</p>
                }
            </NotAuthorized>
 </AuthorizeRouteView>

<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />

您还必须删除所有添加的授权属性。

您将不再使用 RedirectToLogin 组件... 保留 LoginDisplay 组件以在请求时启用身份验证。