簡體   English   中英

雙重注冊(作為用戶/作為公司)

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

我編寫了一個新的ASP.NET MVC 5應用程序,但在身份驗證方面遇到了一些問題。 我想有兩個注冊和登錄表單(針對用戶和公司)。 我使用基本表ApplicationUser for Users並為公司創建自己的表CompaniesAccountModel。 但是問題出在我使用UserManager和SignInManager時。 我無法修改它們以使用CompaniesAccountModel。 這是一些代碼。

[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);
}

[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);
    }
}

我想使用UserManager和SignInManager進行公司注冊和登錄。 如果有人知道如何執行此操作,那將是很好的。

您可以輕松地為公司用戶自定義身份驗證過程。 並與普通用戶的現有方法一起使用。 考慮以下示例作為線索:

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();
} 

由於我們將邏輯注入到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
 }

同樣,如果ApplicationUserCompany類共享許多共同點,則可以從ApplicationUser擴展Company 這樣,您無需編寫額外的登錄方法。 相同的登錄名對兩者均適用。 但是,如果您出於任何原因不希望從ApplicationUser繼承Company ,則上述解決方案將更為可取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM