登录后,单独的DbContext用于身份,User.Identity为空

时间:2018-06-28 20:58:24

标签: c# asp.net-core asp.net-core-identity

我有两个DB,一个用于业务实体,一个用于身份。我还使用外部(Azure广告)登录名对身份进行身份验证。当我将所有这些都放在一个DB和一个DbContext中时,所有这些工作正常。但是,一经拆分,我遇到的问题是登录后,后续请求上的User.Identity.IsAuthenticated为假(因此User.Identity.Name为空,以及角色/声明数据)。 ..您明白了)。外部注册/登录过程中不会在任何地方抛出错误;就像我的应用程序不知道要查看User.Identity信息的上下文一样。

这是ConfigureServices中我的Startup.cs的正文:

services.AddAuthentication(sharedOpts =>
{
    sharedOpts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOpts.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddAzureAd(opts => Configuration.Bind("AzureAd", opts))
.AddCookie();

services.AddIdentity<AspNetUsers, AspNetRoles>()
   .AddEntityFrameworkStores<CoreUMContext>()
   .AddDefaultTokenProviders();

services.AddMvc();

string dataConnection = Configuration["ConnectionStrings:TrackerDatabase"];
string userConnection = Configuration["ConnectionStrings:UserDatabase"];
Trace.TraceWarning("Connecting to connection at: " + dataConnection);
try {
    services.AddDbContext<EdgeContext>(options => options.UseSqlServer(dataConnection));
    services.AddDbContext<CoreUMContext>(options => options.UseSqlServer(userConnection));
}
catch (Exception ex) {
    Trace.TraceError("Error connecting to DB: " + ex);
}

我知道中间件可能很难处理您添加到管道中的顺序,因此我尝试了每个组合({{1}之前的.AddIdentity,在{{1}之前添加了.AddAuthentication }等)。将Identity上下文(CoreUMContext)注入我的控制器也无法解决问题。

同样,此行有效

EdgeContext

CoreUMContext返回true,因此在某种程度上可以正常工作,但是我似乎找不到关于User.Identity可以自行解决的确切路径的好的文献。

如果有人能照亮我,我将不胜感激,因为我真的不想不必回到全数据库或全上下文的情况,因为这并不是真的符合我的建筑要求。

  

更新

问题似乎出在Chrome不存储/发送Identity身份信息用来解析哪个用户发出请求的属性Cookie。但是它可以在Microsoft Edge中工作。昨天对我来说这已经改变了一点,我仍在尝试推断原因(清除cookie无效),但是看来多个上下文并不是问题的原因。

1 个答案:

答案 0 :(得分:0)

这似乎是一个特定于Chrome的问题,即Chrome与“ localhost”域上的cookie设置不同。意识到这在Incognito中不是奇怪的问题之后,我发现了这个线程:Chrome localhost cookie not being set 这导致我更改了Startup.cs文件:

services.AddAuthentication(sharedOpts =>
        {
            sharedOpts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            sharedOpts.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddAzureAd(opts => Configuration.Bind("AzureAd", opts))
        .AddCookie(opts => {
            opts.Cookie.Domain = ""; <-- This made the difference
        });

我现在允许浏览器解析cookie域,而不是采用身份代码生成的默认值。 希望当我发布到产品中时,这并不是一个问题。

我不明白的是为什么它最初起作用,然后中断,然后在我将所有代码重新打包到一个上下文和数据库中后仍然保持中断;为什么?也许Chrome允许对Cookie进行一次设置,但随后的所有更改都将被忽略。