0

我正在使用内置认证/授权系统,其中ApplicationUser需要登录,一旦通过身份验证,他就使用SignInManager登录。Asp.Net MVC授权扩展ApplicationUser的自定义用户

我也有不同的用户,CustomUser,它延伸ApplicationUserCustomUser通过外部服务进行身份验证。一旦他被认证,我检查他是否存在,如果没有,我创建他并给他CustomRole

我该如何保持CustomUser授权?我希望能够将[Authorize(Roles="CustomRole")] 属性放在应该允许他的操作之上。那可能吗?我需要做些什么来完成这项工作?或者,还有更好的方法?

编辑

这里的CustomUser的实施。它位于Application.Models

public class CustomUser : ApplicationUser 
{ 
    public int Gender 
    { 
     get; 
     set; 
    } 

    public string FCode 
    { 
     get; 
     set; 
    } 

    public bool Subscribed 
    { 
     get; 
     set; 
    } 
} 

这是CustomUser的简化版本。

回答

0

如果您想通过角色来授权,则需要使用创建Roles

userManager.AddToRole(user.Id, "NameOfRole"); 

您可以创建一个类似下面的注册操作,任何注册表ered用户将来自一个角色。您可以为Manager创建其他角色,并稍后更新特定用户。

using (var context = new ApplicationDbContext()) 
{ 
    if (ModelState.IsValid) 
    { 
     var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; 
     var result = await UserManager.CreateAsync(user, model.Password); 

     if (result.Succeeded) 
     { 
      await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); 
         //adding a role after register 
      var roleStore = new RoleStore<IdentityRole>(context); 
      var roleManager = new RoleManager<IdentityRole>(roleStore); 

      var userStore = new UserStore<ApplicationUser>(context); 
      var userManager = new UserManager<ApplicationUser>(userStore); 
      userManager.AddToRole(user.Id, "SimpleUser"); 
      // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 
      // Send an email with this link 
      // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); 
      // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); 
      // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); 

      return RedirectToAction("Index", "Home"); 
     } 
     AddErrors(result); 
    } 
} 

然后在您的授权属性上,您可以使用Roles来授权。

[Authorize(Roles="Manager, SimpleUser, so on..")] 
+0

问题是SignInManager只接受ApplicationUser,而不接受扩展的CustomUser。我设法创建了CustomUser并添加了正确的角色,但是现在我需要能够“签名”或以某种方式告诉系统哪个用户正在使用该系统,如果这有意义的话?那么是否有可能获得SignInManager 的实例可以签名? – joks

+0

@joks是你的CustomUser是由'IdentityUser'实现的吗? – Valkyrie

+0

@joks看这篇文章队友,你不需要为自定义用户创建一个模型,你可以使用ApplicationUser,如果你想给它额外的属性,你可以将它添加到它的类,像这篇文章:http:// stackoverflow .com/questions/28335353/how-to-extend-available-properties-of-user-identity – Valkyrie

0

你应该能够为角色做类似如下:

[Authorize(Roles = "CustomRole")] 
public ActionResult CustomRoleOnly() 
{ 
    return View(); 
} 

,或者如果它是为用户

[Authorize(Users = "JoeBloggs, JaneDoe")] 
public ActionResult SpecificUserOnly() 
{ 
    return View(); 
}