在我的 ASP.NET Core身份中,我注意到我添加的声明正在迷路。
首先,我具有创建索赔视图,该视图具有用于创建索赔的表单。 声明已添加到当前登录的用户。
Action方法的代码为:
[HttpPost]
[ActionName("Create")]
public IActionResult Create_Post(string claimType, string claimValue, string claimIssuer)
{
ClaimsIdentity identity = User.Identity as ClaimsIdentity;
Claim claim = new Claim(claimType, claimValue, ClaimValueTypes.String, claimIssuer);
identity.AddClaim(claim);
return RedirectToAction("Index");
}
该行添加了该行-identity.AddClaim(claim);
。
现在,最后一行将重定向到其代码为:
的Index操作方法。public ViewResult Index() => View(User?.Claims);
显示用户所有声明的索引视图是:
@model IEnumerable<System.Security.Claims.Claim>
<table class="table table-sm table-bordered">
<tr>
<th>Subject</th>
<th>Issuer</th>
<th>Type</th>
<th>Value</th>
</tr>
@foreach (var claim in Model.OrderBy(x => x.Type))
{
<tr>
<td>@claim.Subject.Name</td>
<td>@claim.Issuer</td>
<td>@claim.Type</td>
<td>@claim.Value</td>
</tr>
}
</table>
怎么了?
答案 0 :(得分:0)
答案 1 :(得分:0)
如果要将声明保存到User?.Claims
,则需要使用更新后的_signInManager.Context.SignInAsync
来致电ClaimsIdentity
。
请按照以下步骤操作:
使用新的ClaimsIdentity
登录的扩展名
public class CustomClaimsCookieSignInHelper<TIdentityUser> where TIdentityUser : IdentityUser
{
private readonly SignInManager<TIdentityUser> _signInManager;
public CustomClaimsCookieSignInHelper(SignInManager<TIdentityUser> signInManager)
{
_signInManager = signInManager;
}
public async Task SignInUserAsync(ClaimsIdentity claimsIdentity)
{
await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme, new ClaimsPrincipal(claimsIdentity));
}
}
注册CustomClaimsCookieSignInHelper<TIdentityUser>
services.AddTransient<CustomClaimsCookieSignInHelper<IdentityUser>>();
更新用户声明
public class IdentityController : Controller
{
private readonly CustomClaimsCookieSignInHelper<IdentityUser> _signInHelper;
private readonly UserManager<IdentityUser> _userManager;
public IdentityController(CustomClaimsCookieSignInHelper<IdentityUser> signInHelper
, UserManager<IdentityUser> userManager)
{
_signInHelper = signInHelper;
_userManager = userManager;
}
public ViewResult Index() => View(User?.Claims);
[HttpGet]
[ActionName("Create")]
public IActionResult Create_Post()
{
return View();
}
[HttpPost]
[ActionName("Create")]
public async Task<IActionResult> Create_Post(string claimType, string claimValue, string claimIssuer)
{
ClaimsIdentity identity = User.Identity as ClaimsIdentity;
Claim claim = new Claim(claimType, claimValue, ClaimValueTypes.String, claimIssuer);
identity.AddClaim(claim);
await _signInHelper.SignInUserAsync(identity);
return RedirectToAction("Index");
}
}