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

纵然是瞬间 提交于 2019-12-01 13:55:59

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