使用aspnetcore 2.2联合Azure AD登录后,User.Identity.Name为空 [英] User.Identity.Name is null after federated Azure AD login with aspnetcore 2.2

查看:81
本文介绍了使用aspnetcore 2.2联合Azure AD登录后,User.Identity.Name为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尽可能密切地关注AzureAD aspnetcore示例,以尝试在我们的aspnetcore 2.2 Web应用程序中实现Azure AD身份验证.我可以使用Azure AD成功登录.但是,登录后不会显示用户名.

进一步检查后,我发现主要索赔已正确返回给应用程序.但是,由于某些原因,HttpContext.User对象未正确填充.我不知道为什么会这样.当我从上面的示例中查看相同的值时,HttpContext已正确设置.为了澄清起见,我实现了OnSecurityTokenValidated处理程序,并使用以下上下文:

可以看出,userPrincipal拥有预期的声明.

但是,httpContext没有声明.因此User.Identity.Name也为null:

我尝试执行手动登录,但这也不起作用:

 私有异步任务SignInUser(TokenValidatedContext tokenValidatedContext){var httpContext = tokenValidatedContext.HttpContext;var userPrincipal = tokenValidatedContext.Principal;等待httpContext.SignOutAsync(AppSettings.CookieName);等待httpContext.SignInAsync(AppSettings.CookieName,userPrincipal,新的AuthenticationProperties{ExpiresUtc = DateTime.UtcNow.AddDays(1),IsPersistent = false,AllowRefresh =否});} 

更新

我正在设置NameClaimType,如上所示.在配置中设置NameClaimType

有人知道我在做什么错吗?

我正在使用Visual Studio 2017&aspnetcore 2.2库.我已经将Microsoft.Identity.Client升级到2.7

解决方案

我认为我已经有了答案,尽管这会引发新的问题.

基本上,我们的代码使用Identity以及AzureADB2C.身份与AzureADB2C登录过程冲突.登录成功,并且令牌已返回,但返回时,身份会以某种方式将其删除.

这是我在Startup.cs中拥有的代码:

  services.AddAuthentication(sharedOptions =>{sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;}).AddAzureAdB2C(options => Configuration.Bind("Authentication:AzureAdB2C",options)).AddCookie();services.Configure< CookiePolicyOptions>(options =>{//此lambda决定对于给定的请求是否需要用户同意非必要的cookie.options.CheckConsentNeeded =上下文=>真的;options.MinimumSameSitePolicy = SameSiteMode.None;});services.Configure< ApiBehaviorOptions>(options =>{options.InvalidModelStateResponseFactory = ctx =>新的ValidationProblemDetailsResult();});services.AddOptions();ConfigureMvc(服务);//将身份服务添加到服务容器.services.SetupIdentity(); 

SetupIdentity是包含以下内容的扩展方法:

  services.AddIdentity< ApplicationUser,ApplicationRole>(o => {o.Password.RequiredLength = 8;o.Password.RequireDigit = true;o.Password.RequireLowercase = true;o.Password.RequireUppercase = true;o.Password.RequireNonAlphanumeric = true;}).AddEntityFrameworkStores< ApplicationContext>().AddDefaultTokenProviders().AddUserStore< UserStore< ApplicationUser,ApplicationRole,ApplicationContext,Guid>().AddRoleStore< RoleStore< ApplicationRole,ApplicationContext,Guid>();. 

该想法是AAD将用于身份验证,而本地身份角色将用于为用户提供对该应用程序的各种权限.基于此问题,看来我们将不得不重新考虑我们的安全性.

问题是,AAD和身份真的不能一起使用吗?我想要一种方案,其中返回AAD的用户ID,并将其存储在本地sql中,然后在本地数据库中使用此用户ID将用户连接到变量实体.如果不能同时使用AAD和身份,那有什么选择?IE.将AAD用户连接到本地数据库的最佳方法是什么?谁能指出我一些讨论此话题的MS文章?

I've followed AzureAD aspnetcore sample as closely as possible to try and implement Azure AD authentication in our aspnetcore 2.2 webapp. I am able to login successfully using Azure AD. However, the user's name is not being displayed AFTER login.

https://github.com/Azure-Samples/active-directory-b2c-dotnetcore-webapp

This value should be read in the view from the User.Identity.Name property.

On further inspection, I can see that the principal claims are being correctly returned to the application. However, for some reason the HttpContext.User object is not correctly populated. I don't know why this is happening. When I look at the same value from the sample above, HttpContext is correctly set. For clarification, I have implemented OnSecurityTokenValidated handler and I use this context:

As can be seen, userPrincipal has the claims as expected.

However, the httpContext has no claims. Also User.Identity.Name therefore is null:

I've tried to carry out a manual signin, but that doesn't work either:

private async Task SignInUser(TokenValidatedContext tokenValidatedContext)
{
    var httpContext = tokenValidatedContext.HttpContext;
    var userPrincipal = tokenValidatedContext.Principal;

    await httpContext.SignOutAsync(AppSettings.CookieName);
    await httpContext.SignInAsync(AppSettings.CookieName, userPrincipal,
      new AuthenticationProperties
      {
          ExpiresUtc = DateTime.UtcNow.AddDays(1),
          IsPersistent = false,
          AllowRefresh = false
      });
}

Update

I am setting the NameClaimType as shown above. The NameClaimType is set in Configure

Anyone have any idea what I am doing wrong?

I am using Visual Studio 2017 & aspnetcore 2.2 libraries. I've upgraded Microsoft.Identity.Client to 2.7

解决方案

I think I've got the answer to this, although it leads to new questions.

Basically, our code uses Identity as well as AzureADB2C. The Identity is conflicting with the AzureADB2C login process. Login is successful and the token is being returned, but on return it is somehow being erased by Identity.

This is the code that I have in Startup.cs:

            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddAzureAdB2C(options => Configuration.Bind("Authentication:AzureAdB2C", options))
            .AddCookie();

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.Configure<ApiBehaviorOptions>(options =>
        {
            options.InvalidModelStateResponseFactory = ctx => new ValidationProblemDetailsResult();
        });

        services.AddOptions();

        ConfigureMvc(services);

        // Add Identity services to the services container.
        services.SetupIdentity();

SetupIdentity is an extension method that contains the following:

            services.AddIdentity<ApplicationUser, ApplicationRole>(o => {
            o.Password.RequiredLength = 8;
            o.Password.RequireDigit = true;
            o.Password.RequireLowercase = true;
            o.Password.RequireUppercase = true;
            o.Password.RequireNonAlphanumeric = true;
        })
            .AddEntityFrameworkStores<ApplicationContext>()
            .AddDefaultTokenProviders()
            .AddUserStore<UserStore<ApplicationUser, ApplicationRole, ApplicationContext, Guid>>()
            .AddRoleStore<RoleStore<ApplicationRole, ApplicationContext, Guid>>();

The idea is that AAD will be used for authentication, and local Identity roles will be used for giving the user various permissions on the app. Based on this issue, looks like we will have to rethink our security.

The question is, can AAD and Identity really not be used together? I'd want a scenario where a user id from AAD is returned, stored in local sql, and then this user id used in the local database to connect the user to variable entities. If AAD and Identity can't be used together, what is the alternative? I.e. what's the best way to connect an AAD user to a local database? Can anyone point me to some MS articles that discuss this?

这篇关于使用aspnetcore 2.2联合Azure AD登录后,User.Identity.Name为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆