How do I implement Blazor authentication with OpenID Connect?

Platform: Blazor| Category: General

Blazor authentication is implemented to determine who a particular user is. Blazor follows the existing ASP.NET Core authentication mechanisms to show a user’s identity.
Follow these steps to implement authentication with OpenID Connect in Blazor:

  1. Create Blazor application

    Create a Blazor Server app and install a NuGet package named “Microsoft.AspNetCore.Authentication.OpenIdConnect” using the NuGet package manager.

  2. Add OIDC and authentication configuration

    Add OpenID Connect and cookie authentication service configuration to the Blazor Server app in the Startup.cs file.
    [Startup.cs]

    using Microsoft.AspNetCore.Authentication.Cookies;
    using Microsoft.AspNetCore.Authentication.OpenIdConnect;
    using Microsoft.IdentityModel.Tokens;
     
    namespace BlazorServerApp
    {
        public class Startup
        {
          . . .
          . . .
          public void ConfigureServices(IServiceCollection services)
          {
                      . . .
                      . . .
                      services.AddAuthentication(opt =>
                {
                    opt.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    opt.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    opt.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                }).AddCookie().AddOpenIdConnect("oidc", options =>
                    {
                    options.Authority = "https://demo.identityserver.io/";
                    options.ClientId = "interactive.confidential.short";
                    options.ClientSecret = "secret";
                    options.ResponseType = "code";
                    options.SaveTokens = true;
                    options.GetClaimsFromUserInfoEndpoint = true;
                    options.UseTokenLifetime = false;
                    options.Scope.Add("openid");
                    options.Scope.Add("profile");
                    options.TokenValidationParameters = new TokenValidationParameters{ NameClaimType = "name" };
     
                    options.Events = new OpenIdConnectEvents
                    {
                        OnAccessDenied = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/");
                            return Task.CompletedTask;
                        }
                    };
                });
             }
     
             public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
             {
                 . . .
                 . . .
                                app.UseAuthentication();
                 app.UseAuthorization();
                         }
               }
     }

  3. Add AuthorizeRouteView to the App.razor file

    Add AuthorizeRouteView to display the page matching the specified route only if the user is authorized.
    [App.razor]

    @inject NavigationManager UriHelper
     
    <CascadingAuthenticationState>
        <Router AppAssembly="@typeof(Program).Assembly">
            <Found Context="routeData">
                <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                    <NotAuthorized>
                        @{
                            var returnUrl = UriHelper.ToBaseRelativePath(UriHelper.Uri);
                            UriHelper.NavigateTo($"login?redirectUri={returnUrl}", forceLoad: true);
                        }
                    </NotAuthorized>
                    <Authorizing>
                        Loading...
                    </Authorizing>
                </AuthorizeRouteView>
            </Found>
            <NotFound>
                <LayoutView Layout="@typeof(MainLayout)">
                    <p>Sorry, there's nothing at this address.</p>
                </LayoutView>
            </NotFound>
        </Router>
    </CascadingAuthenticationState>

  4. Add buttons

    Add Log out and Log in buttons to authorize the user in the header section.
    [MainLayout.razor]

    <div class="top-row px-4">
                <AuthorizeView>
                    <Authorized>
                        <form method="get" action="logout">
                            <button type="submit" class="nav-link btn btn-link">Log out</button>
                        </form>
                    </Authorized>
                    <NotAuthorized>
                        <a href="login?redirectUri=/">Log in</a>
                    </NotAuthorized>
                </AuthorizeView>
                <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
            </div>

  5. Redirect requests to log in or log out users

    Create Razor pages for login (Login.cshtml.cs) and logout (Logout.cshtml.cs) redirection requests to IdentityServer for authorization under the Pages folder.
    [Login.cshtml.cs]

    using Microsoft.AspNetCore.Authentication;
     
    namespace BlazorServerApp.Pages
    {
        public class LoginModel : PageModel
        {
            public async Task OnGet(string redirectUri)
            {
                await HttpContext.ChallengeAsync("oidc", new AuthenticationProperties { RedirectUri = redirectUri });
            }
        }
    }
    [Logout.cshtml.cs]
    using Microsoft.AspNetCore.Authentication;
     
    namespace BlazorServerApp.Pages
    {
        public class LogoutModel : PageModel
        {
            public async Task<IActionResult> OnGetAsync()
            {
                await HttpContext.SignOutAsync();
                return Redirect("/");
            }
        }
    }

  6. Show authorized content in Razor component

    Following is the code to display the authorized content when the app is authorized. If the app is not authorized, it displays the “Not Authorized” message to the user.
    [Index.razor]

    @page "/"
     
    <AuthorizeView>
        <Authorized>
            <h1>Hello, @context.User.Identity.Name !</h1>
     
            <p>Welcome to your new app.</p>
        </Authorized>
        <NotAuthorized>
            <p>Not Authorized</p>
        </NotAuthorized>
    </AuthorizeView>

  7. Run the application

    Press Ctrl + F5 to run the application and click Log in in the header to authenticate the user.

    You can download the reference sample on GitHub.

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.