我正在使用asp.net身份2&天蓝网站上的MVC 5。我创建了一些角色,并且没有问题将用户(作为本地帐户注册到站点)分配给新创建的角色。
奇怪的部分只有在我使用社交登录创建帐户时(在这种情况下为Facebook)。
我检查了表格[aspnetusers]& [aspnetuserlogins],一切看起来都不错......
直到我尝试为角色分配社交帐户。没有例外,在我的记录器中一切都很好。我做错了什么?
var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = um.FindByEmail(email);
um.AddToRole(user.Id, "admin");
只是有点唠叨:角色存在,我毫不费力地将其分配给本地帐户
答案 0 :(得分:0)
在搜索了stackoverflow之后,我终于偶然发现了这条评论AddToRole() method doesn't result in db entry in ASP.NET Identity
之后,我改变了行
um.AddToRole(user.Id, "admin");
到
var result = um.AddToRole(user.Id, "admin");
//log result.Errors
.AddToRole()
用户名Lee Gary无效,只能包含字母或数字。
在查看本地创建的帐户后,我意识到所有这些帐户的电子邮件都是用户ID
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser()
{
// this line assigned email as username
UserName = model.Email,
Email = model.Email
};
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
但是,上帝知道原因,MVC开发人员决定让社交登录用户输入他们自己的用户名而无需验证
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser()
{
UserName = model.Name, //<--- model.Name = user input
Email = model.Email ,
BirthDate = model.BirthDate
};
IdentityResult result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
最后为了确保用户名是A-OK,我在Register()
自:
var user = new ApplicationUser()
{
UserName = model.Name,
Email = model.Email ,
BirthDate = model.BirthDate
};
要:
var user = new ApplicationUser()
{
Name = model.Name,
UserName = model.Email,
Email = model.Email ,
BirthDate = model.BirthDate
};