MVC 5身份(v2)身份验证,无需创建应用程序用户

时间:2015-10-06 11:35:29

标签: asp.net-mvc authentication asp.net-identity

有没有办法在不创建MVC 5标识的ApplicationUser的情况下验证会话?

由于各种原因,我最终使用了双层身份验证系统。我解析了一个"用户"从我的自定义数据库到会话的对象,以及在整个站点的各个地方,该对象的存在是如何确定用户的登录状态。

我在网站的不同位置使用身份用户资料(例如索赔,登录等)。但是在这个特定的实例中,我需要登录一个匿名的Identity用户并解析为会话请求的任何用户对象。那么如何使用Identity V2创建一个匿名认证的会话?

1 个答案:

答案 0 :(得分:1)

在Identity中,您不需要拥有用户对象进行身份验证。您可以动态创建一些声明并使用它们进行身份验证。考虑这个简单的例子:

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

现在您已经像真实用户一样对匿名用户进行了身份验证:

[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;
}
相关问题