我创建了一个基于Microsoft authorization example的项目,该项目生成了一个名为ApplicationUser的类。我正在尝试在创建帐户时向用户添加声明。
基于this SO post我会将声明添加到创建用户的构造函数中。但是,构造函数似乎没有显式存在于ApplicationUser类中(但登录工作正常)。如何向刚刚创建的用户添加声明?
此外,类ApplicationUser
没有在Register方法中分配给它的属性UserName
和Email
,这让我觉得有很多事情要发生在背景我很想念。
ApplicationUser.cs
namespace xxx.Models
{
public class ApplicationUser : IdentityUser
{
}
}
AccountController.cs
private readonly UserManager<ApplicationUser> _userManager;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ILogger<AccountController> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_logger = logger;
}
.........
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation("User created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
答案 0 :(得分:0)
ApplicationUser没有在Register方法中分配给它的UserName和Email属性......
ApplicationUser
继承了UserName
类的Email
和IdentityUser
属性。这些属性和其他属性在其文档中列出here。
public class ApplicationUser : IdentityUser
{
}
如何向刚刚创建的用户添加声明?
向用户添加声明的一种方法是使用UserManager.AddClaimAsync
方法。有一个example of doing that here。
在以下与您的Register
方法类似的代码段中,我们在检查result.Succeeded
之后将claim添加到新用户。
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await _userManager.AddClaimAsync(user, new Claim("MyClaimType", "MyClaimValue"));