我有一個簡單的沙箱項目,我用它來更好地理解.net Core Identity的工作方式,我遇到了一些不一致的地方,我希望有人能解釋。該項目正在使用實體框架。身份角色沒有被填充
我用這個真棒文章幫我設置了項目,https://medium.com/@goodealsnow/asp-net-core-identity-3-0-6018fc151b4#.2env44446和我的User類如下。
public class User : IdentityUser<int>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string TempPassword { get; set; }
}
我播種的分貝有三個用戶和三個角色,一個用戶對於每個角色,「所有者」,「管理」和「用戶」。我加了一些政策,爲我的行爲,
auth.AddPolicy("Owner", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireRole("Owner");
});
auth.AddPolicy("Admin", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireRole("Admin", "Owner");
});
auth.AddPolicy("User", policy =>
{
policy.RequireAuthenticatedUser();
});
那麼喜歡[Authorize("Admin")]
工作我的屬性很棒。我甚至增加了一些主要的擴展爲使
public static class PrincipalExtensions
{
public static bool IsOwner(this ClaimsPrincipal principal)
{
return principal.IsInRole("Owner");
}
public static bool IsAdmin(this ClaimsPrincipal principal)
{
return principal.IsInRole("Admin") || principal.IsInRole("Owner");
}
public static bool IsUser(this ClaimsPrincipal principal)
{
return principal.Identity.IsAuthenticated;
}
}
所以我可以做if(User.IsAdmin())
這完美的作品也是如此。
這裏是會很奇怪......
如果我通過下面的代碼,我得到混淆的結果步驟。
var user = await _userManager.GetUserAsync(User);
var userRoles = await _userManager.GetRolesAsync(user);
await _userManager.AddToRoleAsync(user, "Owner");
第一行爲我提供了一個User
對象。在該對象上有一個他的角色集合user.Roles
,但即使用戶確實有有角色,它也會顯示爲空(Count = 0)。
第二行獲取用戶的Roles
,並且它填充正確。
第三行爲用戶添加了「所有者」角色,並且它可以正常工作(數據庫已更新),而且本地變量user
突然在user.Roles
中擁有該角色!請注意,用戶的其他角色都不會出現,只有那一個。
所以我基本上有兩個問題:1。爲什麼不user
對象已在user.Roles
填充到開始? 2.爲什麼添加角色後突然同步?
任何幫助表示讚賞。
感謝您的鏈接。起初,我只是想說「如果他們不打算填充它,他們爲什麼要把它放在對象上」,但是在該頁面的積壓部分中,它表示它即將到來。 – nurdyguy
嘿,最重要的是,'用戶。Roles'是隻讀的,所以我甚至不能自己填充它! – nurdyguy