不创建应用程序用户的MVC 5身份(v2)身份验证 [英] MVC 5 Identity (v2) Authentication Without Creating an Application User

查看:75
本文介绍了不创建应用程序用户的MVC 5身份(v2)身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不使用MVC 5身份创建ApplicationUser的情况下对会话进行身份验证?

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.

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

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?

推荐答案

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

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

这篇关于不创建应用程序用户的MVC 5身份(v2)身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆