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

ε祈祈猫儿з 提交于 2019-12-01 13:02:30

问题


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 system. I parse a "user" object from my custom db into session, and in various places all over the site, the existence of this object is how the logged-in status of a user is determined.

I use Identity user stuff (e.g. claims, logins, etc.) at various places of the site. But at this one specific instance, I need to log in an anonymous Identity user and parse whatever user object is requested to the session. So how can I create an anonymously authenticated session with Identity V2?


回答1:


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


来源:https://stackoverflow.com/questions/32968910/mvc-5-identity-v2-authentication-without-creating-an-application-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!