How to implement Google Authetication in Blazor Web app without Core Identity

Iftekhar Ahammed 0 Reputation points
2024-05-14T10:25:28.9566667+00:00

I would like to use custom authentication without using out-of-the-box Core Identity in my Blazor Web App with Oauth authentication.

I started the app using the template without using individual user account because we have our own registration and login page.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,679 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 68,311 Reputation points
    2024-05-14T22:59:10.54+00:00

    you don't give any info, the authentication flows are all pretty similar.

    • when your Blazor app need Authentication it redirects to the login server passing reply information, such as the reply url, and app id. this step unloads the Blazor app.
    • the login server authenticates the user and redirect back to the reply url
    • the reply url (typically a razor page or mvc controller) reads the ticket info and builds the user principal. if cookie authentication, the principal is serialized to a cookie. if token, it is passed on the url (if access tokens are required, typically they are cached key by user). the reply url page redirects to the Blazor host page.
    • the Blazor host page reads the cookie or passed token and build a user principal that is added as a scoped service. the host page the loads a pre-render Blazor app.
    • the Blazor pre-render reads the user from scoped services, and adds to the authentication state provider. The pre-render state needs to be persisted to response html. the pre-render response html is sent to the browser
    • the browser load the pre-render response, and either open signal/r connection to new Blazor server instance or loads a Blazor WASM app instance.
    • the new Blazor instance loads pre-render state info and creates a new authentication state provider with the saved state.
    0 comments No comments

  2. Zhi Lv - MSFT 32,646 Reputation points Microsoft Vendor
    2024-05-27T08:51:50.16+00:00

    Hi @Iftekhar Ahammed,

    Here is a simple sample about implement Google Authentication in Blazor Web App (None Authentication type and Auto interactive render mode) without using Asp.net core Identity, you can check it:

    1. Create a new Asp.net core Blazor Web App, without select the "Individual Accounts" type.
    2. Install the Microsoft.AspNetCore.Authentication.Google package via Nuget.
    3. Refer to the Google Authentication document and Create the Google OAuth 2.0 Client ID and secret.
    4. Configure the Authentication Pipeline. Open the appsettings.json file and add the Google configuration. Like this:
      "Google": {
        "Instance": "https://accounts.google.com/o/oauth2/v2/auth",
        "ClientId": "{client id}",
        "ClientSecret": "{client secret}",
        "CallbackPath": "/signin-google"
      },
    

    Open the Program.cs file (this is a .Net 8 application), register the google authentication and enable razor page middleware and service:

    var builder = WebApplication.CreateBuilder(args);
    // Add services to the container.
    builder.Services.AddRazorComponents()
        .AddInteractiveServerComponents()
        .AddInteractiveWebAssemblyComponents();
    //configure google auth
    builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
    builder.Services.AddAuthentication().AddGoogle(options =>
    {
        var clientid = builder.Configuration["Google:ClientId"];
        options.ClientId = builder.Configuration["Google:ClientId"];
        options.ClientSecret =builder.Configuration["Google:ClientSecret"]; 
    });
    builder.Services.AddHttpContextAccessor();
    builder.Services.AddScoped<HttpContextAccessor>();
    builder.Services.AddHttpClient();
    builder.Services.AddScoped<HttpClient>(); 
    builder.Services.AddRazorPages();
    var app = builder.Build();
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseWebAssemblyDebugging();
    }
    else
    {
        app.UseExceptionHandler("/Error", createScopeForErrors: true);
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseAntiforgery();
    app.UseCookiePolicy();
    app.UseAuthentication(); 
    app.MapRazorComponents<App>()
        .AddInteractiveServerRenderMode()
        .AddInteractiveWebAssemblyRenderMode()
        .AddAdditionalAssemblies(typeof(BlazorWebGoogleLogin.Client._Imports).Assembly);
    app.MapRazorPages();  //since we will use razor page to login and logout, so we need to add the MapRazorPage and AddRazorPages.
    app.Run();
    
    1. Create Login page, Logout page and LoginControl component:

    User's image

    You can view the page source from here: 197626-loginpage.txt 197627-logoutpage.txt 197692-logincontrol.txt

    Then, add the LoginControl component in the MainLayout.razor component:

    User's image

    Finally, running the application, after clicking the Login button, it will show the following page. Then we can login using google account.

    User's image

    Refer to my reply in this thread: How to implement Google Authetication in Blazor server app without Core Identity.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.