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:
- Create Blazor application
Create a Blazor Server app and install a NuGet package named “Microsoft.AspNetCore.Authentication.OpenIdConnect” using the NuGet package manager.
- 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();
}
}
} - 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> - 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> - 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]
[Logout.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 });
}
}
}using Microsoft.AspNetCore.Authentication;
namespace BlazorServerApp.Pages
{
public class LogoutModel : PageModel
{
public async Task<IActionResult> OnGetAsync()
{
await HttpContext.SignOutAsync();
return Redirect("/");
}
}
} - 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> - 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