Azure AD B2C Token returns name but User.Identity.Name is null

二次信任 提交于 2019-12-11 16:20:01

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/49468422/azure-ad-b2c-token-returns-name-but-user-identity-name-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!