MVC 5 Identity (v2) Authentication Without Creating an Application User

后端 未结 1 655
一个人的身影
一个人的身影 2021-01-16 20:53

Is there a way to authenticate a session without creating an ApplicationUser in MVC 5 identity?

For various reasons, I ended up using a two layered authentication sy

相关标签:
1条回答
  • 2021-01-16 21:11

    In Identity you don't need to have user object to authenticate. You could create some claims on the fly and use them to authenticate. Consider this simple example:

    [HttpPost]
    public ActionResult AnonymousLogin()
    {
        var ident = new ClaimsIdentity(
            new[] 
            {
                // adding following 2 claim just for supporting default antiforgery provider
                new Claim(ClaimTypes.NameIdentifier, "AnonymousUserID"),
                new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
    
                new Claim(ClaimTypes.Name, "AnonymousUserID"),
             },
             DefaultAuthenticationTypes.ApplicationCookie);
    
        HttpContext.GetOwinContext().Authentication.SignIn(
           new AuthenticationProperties { IsPersistent = false }, ident);
        return RedirectToAction("MyAction"); // auth succeed 
    }
    

    Now you have authenticated an anonymous user just like a real user:

    [Authorize]
    public ActionResult MyAction()
    {
        // all authorized users could use this method don't matter how have been authenticated
        // you have access current user principal
        var username=HttpContext.User.Identity.Name;
    }
    
    0 讨论(0)
提交回复
热议问题