我有一個簡單的 MVC .Core 6 Web 應用程式,它將在企業外聯網上使用(通過 azure 應用程式服務)。
我已經為登錄/身份驗證設定了 Microsoft Identity。這真的很好用。用戶請求一個頁面,然后他們被發送到公司 azure 活動目錄登錄頁面(包括 2fa)并回傳到通過用戶宣告進行身份驗證的應用程式。
但是......我的身份資料庫表仍然是空的(AspNetUsers 等)。我有點期待創建一個代表剛剛登錄的用戶的記錄。
我搭建了 ExternalLogin.cshtml 頁面,希望它在用戶登錄后顯示(如果 userManager.GetUserAsync(User) == null,我可以在那里手動創建用戶)。但該頁面從未顯示
我想我想要 AspNetUsers 表條目,因為我的簡單應用程式做了一些審計跟蹤(CreatedByUserId、LastUpdatedByUserId),我希望這些是 AspNetUsers 表的外鍵。
想法?我的期望不正常嗎?
uj5u.com熱心網友回復:
我在這方面偏離了基礎。
Microsoft.Identity.Web 和 Microsoft.Identity.Web.UI 不需要/創建 AspNetUsers 表(等)。
如果您想在用戶登錄應用程式時構建自己的用戶表,您可以執行以下操作:
builder.Services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, opts =>
{
opts.Events = new OpenIdConnectEvents()
{
OnTicketReceived = async (context) =>
{
//
// Pull out the user details
//
var objectidentifier = context.Principal.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier");
var nameidentifier = context.Principal.FindFirstValue(ClaimTypes.NameIdentifier);
var name = context.Principal.FindFirstValue("name");
var email = context.Principal.FindFirstValue("preferred_username");
//
// Demo code to create a record in a users db table
//
using var scope = context.HttpContext.RequestServices.CreateScope();
var ctx = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var isUserExists = await ctx.MyApplicationUser.AnyAsync(u => u.ObjectIdentifier == objectidentifier);
if (!isUserExists)
{
var applicationUser = new MyApplicationUser()
{
ObjectIdentifier = objectidentifier,
NameIdentifier = nameidentifier,
Email = email,
Name = name,
};
ctx.MyApplicationUser.Add(applicationUser);
await ctx.SaveChangesAsync();
};
}
};
});
請注意,需要注意提取正確的宣告。
請注意,如果現有用戶的詳細資訊發生變化(名稱確實發生變化),這可能應該更新現有用戶。
這與我在以下位置找到的內容略有不同:https : //dotnetthoughts.net/azure-active-directory-b2c-in-aspnet-core-mvc-part1/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/388537.html
