Azure AD B2C令牌返回名称,但User.Identity.Name为null

时间:2018-03-24 18:36:05

标签: oauth-2.0 jwt azure-ad-b2c

我有一个Azure AD B2C令牌,似乎正确返回当前登录用户的名称。这是jwt.ms的截图,我用它来解码我登录后应用程序返回的令牌:

enter image description here

然而,我尝试在@User.Identity.Name中使用_Layout.cshtml。为什么它为空?它不应该等于屏幕截图中的“名称”值吗?

2 个答案:

答案 0 :(得分:2)

原来我错过了评论标记的行:

        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}"
            }
        );

整个文件位于:https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/blob/master/TaskWebApp/App_Start/Startup.Auth.cs

答案 1 :(得分:1)

请参阅使用Owin的this working example(听起来你正在使用它)。

<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

相关问题