I created a Sample Blazor Server App with Azure Ad B2C by following this Documentation.
I successfully logged in and logged out without any issues.
Below is My Complete code.
Program.cs:
using System.Reflection;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using BlazorApp1.Components;
using System.Security.Claims;
namespace BlazorApp1;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var env = builder.Environment;
builder.Configuration
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.AddUserSecrets(Assembly.GetExecutingAssembly(), optional: true);
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAdB2C"));
builder.Services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Events = new OpenIdConnectEvents
{
OnSignedOutCallbackRedirect = ctxt =>
{
ctxt.Response.Redirect(ctxt.Options.SignedOutRedirectUri);
ctxt.HandleResponse();
return Task.CompletedTask;
},
OnTicketReceived = ctxt =>
{
var claims = ctxt.Principal?.Claims.ToList();
return Task.CompletedTask;
}
};
});
builder.Services.AddControllersWithViews().AddMicrosoftIdentityUI();
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddMicrosoftIdentityConsentHandler();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddHttpContextAccessor();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.UseAntiforgery();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.Run();
}
}
MainLayout.razor:
@inherits LayoutComponentBase
<div class="page">
<div class="sidebar">
<NavMenu />
</div>
<main>
<div class="top-row px-4">
<AuthorizeView>
<Authorized>
Hello @context.User.Identity?.Name!
<a href="MicrosoftIdentity/Account/SignOut">Log out</a>
</Authorized>
<NotAuthorized>
<a href="/MicrosoftIdentity/Account/SignIn">Sign in with your social account</a>
</NotAuthorized>
</AuthorizeView>
</div>
<article class="content px-4">
@Body
</article>
</main>
</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="" class="reload">Reload</a>
<a class="dismiss"></a>
</div>
appsettings.json:
"AzureAdB2C": {
"Instance": "https://<DomainName>.b2clogin.com/tfp/",
"ClientId": "<clientid>",
"CallbackPath": "/signin-oidc",
"Domain": "<DomainName>.onmicrosoft.com",
"SignUpSignInPolicyId": "<PolicyName>",
"ResetPasswordPolicyId": "",
"EditProfilePolicyId": ""
}
Make Sure to Add Redirect URL in the App registration as shown below:
Output: