[英]Separate DbContext for Identity, User.Identity empty after login
我有兩個DB,一個用於業務實體,一個用於身份。 我還使用外部(Azure廣告)登錄名對身份進行身份驗證。 當我將所有這些都放在一個DB和一個DbContext中時,所有這些工作正常。 但是,將其拆分后,我遇到的問題是登錄后在后續請求上User.Identity.IsAuthenticated
為false(因此User.Identity.Name
為null,以及Role / Claims數據也是如此)。 ..您明白了)。 外部注冊/登錄過程中不會在任何地方拋出錯誤; 就像我的應用程序不知道要查看User.Identity信息的上下文一樣。
這是我在Startup.cs
ConfigureServices
的主體:
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);
}
我知道中間件可能會非常棘手,與你加入到管道中的順序,所以我想盡組合( .AddIdentity
前.AddAuthentication
,加入CoreUMContext
的前EdgeContext
等)。 將Identity上下文( CoreUMContext
)注入到我的控制器中也無法解決問題。
同樣,這行有效
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
和result.Succeeded
返回true,因此在某種程度上它是可行的,但是我似乎找不到關於User.Identity的確切路徑的有效文獻。
如果有人可以照亮我,我將不勝感激,因為我真的不想回到全數據庫或全上下文的場景,因為這真的不適合我的體系結構要求。
更新
看來問題是Chrome無法存儲/發送Identity Cookie,Identity使用該Cookie來解析哪個用戶正在發出請求。 但是它可以在Microsoft Edge中工作。 昨天對我來說這已經改變了一點,我仍在嘗試推斷原因(清除cookie無效),但是看來多個上下文並不是問題的原因。
看來這是Chrome特有的問題,即Chrome與“ localhost”域上的cookie設置不同。 意識到這在Incognito中不是奇怪的問題后,我發現了這個線程: 未設置Chrome localhost cookie,這導致我更改了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,但是隨后的所有更改都將被忽略。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.