I have an Azure AD B2C token that seems to be correctly returning the currently logged-in user's name. Here is a screenshot from jwt.ms which I am using to decode the token returned by the application after I have logged in:
However, then I attempt to use @User.Identity.Name
in my _Layout.cshtml
. Why is it null? Shouldn't it be equal to the "name" value in the screenshot?
It turned out I was missing the line marked by the comments:
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
// Generate the metadata address using the tenant and policy information
MetadataAddress = String.Format(AadInstance, Tenant, DefaultPolicy),
// These are standard OpenID Connect parameters, with values pulled from web.config
ClientId = ClientId,
Authority = Authority,
PostLogoutRedirectUri = RedirectUri,
RedirectUri = RedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
RedirectToIdentityProvider = OnRedirectToIdentityProvider,
AuthenticationFailed = OnAuthenticationFailed,
AuthorizationCodeReceived = OnAuthorizationCodeReceived,
},
//////// WAS MISSING THIS BELOW /////////
// Specify the claims to validate
TokenValidationParameters = new TokenValidationParameters
{
// This claim is in the Azure AD B2C token; this code tells the web app to "absorb" the token "name" and place it in the user object
NameClaimType = "name"
},
// Specify the scope by appending all of the scopes requested into one string (separated by a blank space)
Scope = $"{OpenIdConnectScopes.OpenId} {ReadTasksScope} {WriteTasksScope}"
}
);
The entire file is located here: https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/blob/master/TaskWebApp/App_Start/Startup.Auth.cs
See this working example that is using Owin (which it sounds like you're using).
<ul class="nav navbar-nav navbar-right">
<li>
<a id="profile-link">@User.Identity.Name</a>
...
</li>
</ul>
Source
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
...
);
}
Source