Search code examples
google-oauthblazoropenid-connect

Using Blazor OIDC authentication with Google OAuth only for Google Drive


In my Blazor WASM app I am using OIDC authentication to log in to Google Drive as described here:

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

But I don't want to use

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

because I don't want to restrict user access to my Blazor page.

Most importantly: I don't want the user to see the "Authorizing..." message for several seconds when they aren't logged in - logging in is optional.

I only need the Google OAuth login if the user decides to use Google Drive, so I can get the access token.

How can I use OIDC authentication only to get the access token for Google Drive?

If that isn't possible, can I use C# to login to Google as seen here in JavaScript?

OAuth 2.0 for Client-side Web Applications


Solution

  • The following suggestion may work. If not, report further issues, and I'll try to improve on it...

    Make the following changes in your App.razor file:

    Replace:

    <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>
    

    with

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

    You also have to remove all added Authorize attributes.

    You'll no longer make use of the RedirectToLogin component... Leave the LoginDisplay component in its place to enable authentication when requested.