简体   繁体   English

双重注册(作为用户/作为公司)

[英]Double registration(As User/As Company)

I write a new ASP.NET MVC 5 application and I have some problems with the authentication. 我编写了一个新的ASP.NET MVC 5应用程序,但在身份验证方面遇到了一些问题。 I want to have two registration and login forms (for users and for companies). 我想有两个注册和登录表单(针对用户和公司)。 I use the basic table ApplicationUser for Users and make my own table CompaniesAccountModel for companies. 我使用基本表ApplicationUser for Users并为公司创建自己的表CompaniesAccountModel。 But the problem comes when I use the UserManager and SignInManager. 但是问题出在我使用UserManager和SignInManager时。 I can't modify them to work with CompaniesAccountModel. 我无法修改它们以使用CompaniesAccountModel。 Here you are some code. 这是一些代码。

[AllowAnonymous]
public ActionResult CompanyRegister()
{
    return View();
}

//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult CompanyRegister([Bind(Include = "CompanyName, Password, Email, ConfirmPassword")] CompanyAccountModel model)
{
     if (ModelState.IsValid)
     {
         db.CompanyAccountModels.Add(model);
         db.SaveChanges();

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

     // If we got this far, something failed, redisplay form
     return View(model);
}

and

[AllowAnonymous]
public ActionResult CompanyLogin(string returnUrl)
{
    ViewBag.ReturnUrl = returnUrl;
    return View();
}

//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> CompanyLogin(CompanyLoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // This doesn't count login failures towards account lockout
    // To enable password failures to trigger account lockout, change to shouldLockout: true
    var result = await SignInManager.PasswordSignInAsync(model.CompanyName, model.Password, model.RememberMe, shouldLockout: false);
    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);
        case SignInStatus.LockedOut:
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
        return View(model);
    }
}

I want to use the UserManager and SignInManager for the companies registration and login. 我想使用UserManager和SignInManager进行公司注册和登录。 If someone have an idea how to do this, it would be well. 如果有人知道如何执行此操作,那将是很好的。

You could easily customize authentication process for your company users. 您可以轻松地为公司用户自定义身份验证过程。 And use it side by side with existing method for ordinary users. 并与普通用户的现有方法一起使用。 Consider this example as a clue: 考虑以下示例作为线索:

public ActionResoult CompanyLogin(CompanyLoginViewModel model, string returnUrl)
{
    // imaging you have own company manager, completely independent from identity
    // you could check validity of company by own preferred logic  
    if(_companyManager.IsValid(model))         
    {
        // company is valid, going to authenticate
        var ident = new ClaimsIdentity(
        new[] 
        {
            // adding following 2 claim just for supporting default antiforgery provider
            new Claim(ClaimTypes.NameIdentifier, model.CompanyName),
            new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

            // an optional claim you could omit this 
            new Claim(ClaimTypes.Name, model.CompanyName),
            // add this role to differentiate from ordinary users
            new Claim(ClaimTypes.Role, "Company"),                 
            // you could even add some role
            new Claim(ClaimTypes.Role, "AnotherRole"),
            // and so on
        },
        DefaultAuthenticationTypes.ApplicationCookie);

        // Identity is sign in user based on claim don't matter 
        // how you generated it Identity 
        HttpContext.GetOwinContext().Authentication.SignIn(
            new AuthenticationProperties { IsPersistent = false }, ident);

        // auth is succeed, 
        return RedirectToAction("MyAction"); 
     }
     ModelState.AddModelError("", "We could not authorize you :(");
     return View();
} 

Since we injected our logic to Identity, we don't need to do extra thing at all. 由于我们将逻辑注入到Identity中,因此我们根本不需要做任何额外的事情。

[Authorize]
public ActionResult MySecretAction()
{
    // all authorized users could use this method don't matter how has been authenticated
    // we have access current user principal by calling also
    // HttpContext.User
 }

 [Authorize(Roles="Company")]
 public ActionResult MySecretAction()
 {
     // just companies have accesses to this method
 }

Also if both ApplicationUser and Company classes share lots in common you could just extend Company from ApplicationUser . 同样,如果ApplicationUserCompany类共享许多共同点,则可以从ApplicationUser扩展Company By doing so you don't need to write extra login method. 这样,您无需编写额外的登录方法。 Same login works for both. 相同的登录名对两者均适用。 But if for any reason you don't want inherit Company from ApplicationUser my above solution more desirable. 但是,如果您出于任何原因不希望从ApplicationUser继承Company ,则上述解决方案将更为可取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM