【问题标题】:How to implement user profile with token auth如何使用令牌身份验证实现用户配置文件
【发布时间】:2016-06-20 10:13:36
【问题描述】:
我正在对 Web Api 的 Visual Studio 模板附带的个人用户帐户使用开箱即用的身份验证。我在 Angular.js 前端使用 api。
向前端提供用户配置文件的“规范”方式是什么?
获取令牌和获取用户个人资料(电子邮件、名字和姓氏、角色)是分开的活动,还是 /Token 是否应该提供令牌和至少角色以及可能的名字和姓氏,以便 UI 可以显示它?
我正在寻找有关使用身份验证令牌以及 ASP.Net Web Api + Angular.js 特定信息的应用程序架构/流程的一般指南。
【问题讨论】:
标签:
angularjs
asp.net-web-api2
asp.net-identity
asp.net-membership
【解决方案1】:
为了记录,这就是我实现它的方式。
TL;DR
我决定使用声明,因为“GivenName”、“Surname”已经存在,这表明它是存储此信息的好地方。
我发现编辑声明非常尴尬。
详情
这是我的 Add/UpdateUser 方法。我讨厌处理索赔的方式,但我找不到更好的方法。
[HttpPost]
[Authorize(Roles = "admin")]
public async Task<IHttpActionResult> Post(AccountModelDTO model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
using (var transaction = Request.GetOwinContext().Get<ApplicationDbContext>().Database.BeginTransaction())
{
ApplicationUser user;
if( string.IsNullOrEmpty(model.Id) )
{//Add user
user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult resultAdd = await UserManager.CreateAsync(user); //Note, that CreateAsync this sets user.Id
if (!resultAdd.Succeeded)
{
return GetErrorResult(resultAdd);
}
} else
{//Update user
user = await UserManager.FindByIdAsync(model.Id);
if( user == null )
{
throw new HttpResponseException(Request.CreateResponse(System.Net.HttpStatusCode.BadRequest, "Unknown id"));
}
user.UserName = model.Email;
user.Email = model.Email;
//Remove existing claims
var claims = user.Claims.Where(c=>c.ClaimType == ClaimTypes.GivenName).ToList();
foreach( var claim in claims)
{
await UserManager.RemoveClaimAsync(user.Id, new Claim(ClaimTypes.GivenName, claim.ClaimValue));
}
claims = user.Claims.Where(c => c.ClaimType == ClaimTypes.Surname).ToList();
foreach (var claim in claims)
{
await UserManager.RemoveClaimAsync(user.Id, new Claim(ClaimTypes.Surname, claim.ClaimValue));
}
claims = user.Claims.Where(c => c.ClaimType == ClaimTypes.Role).ToList();
foreach (var claim in claims)
{
await UserManager.RemoveClaimAsync(user.Id, new Claim(ClaimTypes.Role, claim.ClaimValue));
}
}
var result = await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));
if (!result.Succeeded)
{
return GetErrorResult(result);
}
await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Surname, model.LastName));
if (!result.Succeeded)
{
return GetErrorResult(result);
}
foreach (var role in model.Roles)
{
result = await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, role));
}
if (!result.Succeeded)
{
return GetErrorResult(result);
}
transaction.Commit();
return Ok();
}
}