【问题标题】:Transforming / Modifying claims in asp.net identity 2在 asp.net 身份 2 中转换/修改声明
【发布时间】:2015-06-27 06:32:51
【问题描述】:
在 Windows 身份框架 (WIF) 中,您可以实现 ClaimsAuthenticationManager 以修改主体上的声明或向其添加新声明。
声明身份验证管理器在应用程序的声明处理管道中提供了一个扩展点,您可以使用它来验证、过滤、修改、传入声明或在执行 RP 应用程序代码之前将新声明注入到 ClaimsPrincipal 提供的声明集中.
ASP.net Identity 2 有类似这样的管道挂钩吗?如果我想添加一些声明而不将它们保留在 AspNetUserClaims 表中,我该怎么做?
【问题讨论】:
标签:
c#
asp.net-mvc
claims-based-identity
asp.net-identity-2
【解决方案1】:
执行此操作的逻辑位置是在用户成功登录之后。这将发生在AccountController 登录操作中:
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid) { return View(model); }
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
// Transform here
var freshClaims = new List<Claim>
{
new Claim(ClaimTypes.Email, model.Email),
new Claim(ClaimTypes.Locality, "Earth (Milky Way)"),
new Claim(ClaimTypes.Role, "Trooper"),
new Claim(ClaimTypes.SerialNumber, "555666777")
};
AuthenticationManager.AuthenticationResponseGrant.Identity.AddClaims(freshClaims);
return RedirectToLocal(returnUrl);
我使用 DI 将AuthenticationManager 注入AccountControllers 构造函数并将其设置为AccountController 的属性。如果您不这样做,那么您可以将其从 OWIN 上下文中删除:
var authManager = HttpContext.Current.GetOwinContext().Authentication;
authManager.AuthenticationResponseGrant.Identity.AddClaims(freshClaims);