简体   繁体   English

ASP.NET Identity 2是否支持匿名用户?

[英]Does ASP.NET Identity 2 support anonymous users?

I want to allow anonymous/not yet registered and registered users to post on my website. 我想允许匿名/尚未注册和注册的用户在我的网站上发布。

Posts (table)
- Id (int)
- Subject (nvarchar)
- Body (nvarchar)
- UserId (uniqueidentifier)

The project uses the latest MS technologies (ASP.NET MVC 5+, C#...) How should I go about doing that? 该项目使用最新的MS技术(ASP.NET MVC 5 +,C#...)我应该怎么做呢?

Is ASP.NET Identity even the right solution? ASP.NET Identity甚至是正确的解决方案吗?

What's the difference between these: 这些之间有什么区别:

  • ASP.NET Identity ASP.NET身份
  • SimpleMembership SimpleMembership
  • Membership Provider 会员提供者

Update I need to be able to differentiate not yet registered users and record their postings in the database. 更新我需要能够区分尚未注册的用户并在数据库中记录他们的帖子。

Update 2 Then have the option to migrate to a registered account. 更新2然后可以选择迁移到已注册的帐户。 Just like how stackoverflow used to allow anonymous users. 就像stackoverflow用于允许匿名用户一样。 Something like this but compatible with ASP.NET Identitfy http://msdn.microsoft.com/en-us/library/ewfkf772(v=vs.100).aspx 这样的东西,但与ASP.NET Identitfy兼容http://msdn.microsoft.com/en-us/library/ewfkf772(v=vs.100).aspx

ASP.NET Identity is the newest revision of authentication in ASP.NET. ASP.NET Identity是ASP.NET中最新的身份验证修订版。 It's predecessor was SimpleMembership, which itself was an attempt to improve on the old ASP.NET Auth. 它的前身是SimpleMembership,它本身就是为了改进旧的ASP.NET Auth。 Membership providers are not a separate kind of authentication system, but instead, a way to bootstrap ASP.NET Auth or SimpleMembership with additional functionality. 成员资格提供程序不是一种单独的身份验证系统,而是一种通过其他功能引导ASP.NET Auth或SimpleMembership的方法。 If you had a particular login scenario not covered by the defaults, you could create a membership provider that would allow ASP.NET to interface with that system. 如果您有默认值未涵盖的特定登录方案,则可以创建一个允许ASP.NET与该系统连接的成员资格提供程序。

ASP.NET Identity supercedes everything else, and does not use membership providers. ASP.NET Identity取代了其他所有内容,并且不使用成员资格提供程序。 Instead, it's provides a very extensible foundation for authentication that through the use of standard APIs allows you to customize authentication in pretty much any way you like. 相反,它为身份验证提供了一个非常可扩展的基础,通过使用标准API,您可以以任何您喜欢的方式自定义身份验证。 It also has much more robust support for OAuth and external signin providers, and interfaces better with things like Active Directory, especially the Azure version in the cloud. 它还为OAuth和外部登录提供程序提供了更强大的支持,并且可以更好地与Active Directory之类的接口进行交互,尤其是云中的Azure版本。

If you're starting on a new project go with Identity. 如果您正在开始一个新项目,请使用Identity。 Saying that it will remain for the forseeable future is a bit dangerous with Microsoft's seeming flavor-of-the-week approach to authentication in the past, but from my personal experience working with it, they seem to have finally gotten it right. 对于可预见的未来而言,它将继续存在,这与微软过去认为的每周一次的身份验证方法有点危险,但根据我个人使用它的经验,他们似乎终于做对了。 I think you'll only see refinements and improvements going forward, rather than complete replacements. 我认为你只会看到未来的改进和改进,而不是完全替换。

I want to answer one of the original questions: "I need to be able to differentiate not yet registered users and record their postings in the database.". 我想回答一个原始问题:“我需要能够区分尚未注册的用户并在数据库中记录他们的帖子。”

I have used Simple Membership before and I am using Asp.Net Identity Framework 2.2.1. 我以前使用过Simple Membership,我使用的是Asp.Net Identity Framework 2.2.1。 In both cases I use anonymous identification to differentiate not yet registered users and authenticated users. 在这两种情况下,我都使用匿名标识来区分尚未注册的用户和经过身份验证的用户。

  1. Enable anonymous identification in your Web.config by adding <anonymousIdentification enabled="true" cookieName="YOUR_COOKIE_FOR_ANONYMOUS_IDENTIFICATION" /> . 通过添加<anonymousIdentification enabled="true" cookieName="YOUR_COOKIE_FOR_ANONYMOUS_IDENTIFICATION" />在Web.config中启用匿名标识。
  2. You can get the anonymous id by Request.AnonymousID . 您可以通过Request.AnonymousID获取匿名ID。 That id is a GUID in string format. 该id是字符串格式的GUID。
  3. As other users mention, you can use whatever identity system you want, just remember to clear the anonymous id during the log out process. 正如其他用户所提到的,您可以使用您想要的任何身份系统,只需记住在注销过程中清除匿名ID。 Typically after a user is successfully authenticated, you save either the username / userId with the anonymousId into persistence storage. 通常在用户成功通过身份验证后,将带有anonymousId的username / userId保存到持久性存储中。 By clearing the anonymousId when the user logs out, you can make sure the other authenticated users won't be able to associate with the same anonymousId. 通过在用户注销时清除anonymousId,您可以确保其他经过身份验证的用户无法与同一个anonymousId关联。
  4. You can clear the anonymousId by AnonymousIdentificationModule.ClearAnonymousIdentifier() . 您可以通过AnonymousIdentificationModule.ClearAnonymousIdentifier()清除anonymousId。 Note: the AnonymousIdentificationModule is in System.Web.Security assembly. 注意: AnonymousIdentificationModule位于System.Web.Security程序集中。 You can add a reference of System.Web or use CTRL + "." 您可以添加System.Web的引用或使用CTRL +“。” on the AnonymousIdentificationModule in your code to bring in System.Web.Security. 在您的代码中的AnonymousIdentificationModule中引入System.Web.Security。

ASP.NET Identity is a flexible framework for handling user authentication in your Web App. ASP.NET Identity是一个灵活的框架,用于处理Web App中的用户身份验证。 It's pretty awesome, and I would highly recommend you continue using it in your project. 它非常棒,我强烈建议你继续在你的项目中使用它。

Identity doesn't support anonymous users, per se...rather, it's a framework for letting you manage users that are authenticated. Identity本身不支持匿名用户......相反,它是一个允许您管理经过身份验证的用户的框架。 Identity will let you maintain local users, or if you want, users that authenticate with your web app via an external service (say, Facebook or Google). 身份将允许您维护本地用户,或者如果您需要,通过外部服务(例如,Facebook或Google)对您的Web应用程序进行身份验证的用户。

It sounds like you want part of your web app to be accessible to users who are not authenticated. 听起来您希望未经过身份验证的用户可以访问您的部分Web应用程序。 The way you'd achieve that is through attributes on your ASP.NET Controllers. 您实现这一目标的方式是通过ASP.NET控制器上的属性。

Adding the [Authorize] attribute to a Controller or Controller method will tell MVC to ensure the user is both authenticated and authorized. [Authorize]属性添加到Controller或Controller方法将告诉MVC确保用户经过身份验证和授权。 However, to allow anonymous users, simply put the [AllowAnonymous] attribute on the method you want to give public access to. 但是,要允许匿名用户,只需将[AllowAnonymous]属性放在要为其提供公共访问权限的方法上即可。

However, you'll still be able to tell if the user is authenticated or not. 但是,您仍然可以判断用户是否已通过身份验证。 Consider this sample controller and method: 考虑这个示例控制器和方法:

[Authorize]
public class PostController : Controller
{
    [AllowAnonymous]
    public ActionResult Index()
    {
        var isAuthenticated = User.Identity.IsAuthenticated;

        return View();
    }
}

That isAuthenticated will let you know if the current user is logged in or not, and if they are, you can get more information from the User.Identity object. 即使是当前用户是否已登录, isAuthenticated将告诉您,如果是,则可以从User.Identity对象获取更多信息。


In regards to your general question about the differences between the membership frameworks, I'll defer to the official documentation which gives a great overview of the differences: http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity . 关于成员框架之间差异的一般性问题,我将遵循官方文档,对差异进行全面概述: http//www.asp.net/identity/overview/getting-started/introduction到aspnet身份 You definitely want to use ASP.NET Identity in your web app. 您肯定希望在Web应用程序中使用ASP.NET标识。


Update Check out this sample code, which will help you differentiate between not yet registered users when recording posts to the database. 更新查看此示例代码,这将帮助您在将帖子记录到数据库时区分尚未注册的用户。

[Authorize]
public class PostController : Controller
{
    [AllowAnonymous]
    public HttpStatusCodeResult CreatePost(string postText)
    {
        // Use ASP.NET Identity to see if the user is logged in.  
        // If they are, we can get their User Id (blank otherwise)
        var isAuthenticated = User.Identity.IsAuthenticated;
        var userId = "";
        if (isAuthenticated)
            userId = User.Identity.GetUserId();

        // Create a new post object
        var post = new
        {
            PostText = postText,
            Anonymous = !isAuthenticated,
            UserId = userId
        };

        // Save the post to the database here

        return new HttpStatusCodeResult(HttpStatusCode.OK);
    }
}

One way you could handle this is by using a cookie based authentication method. 您可以通过使用基于cookie的身份验证方法来解决此问题。 Browsers will send up any cookies associated with your domain with each web request, so they're an easy way to handle authentication. 浏览器会根据每个Web请求发送与您的域相关联的任何Cookie,因此它们是处理身份验证的简便方法。 The idea here is that we'll have a cookie called ident that will store a user id we generate. 这里的想法是我们将有一个名为ident的cookie,它将存储我们生成的用户ID。 I'm using Guids, but you could easily create an entry in your DB instead. 我正在使用Guids,但您可以轻松地在数据库中创建一个条目。 When we get a web request, see if the cookie exists. 当我们收到Web请求时,查看cookie是否存在。 If it does, we have their user id in the cookie. 如果是,我们在cookie中有他们的用户ID。 Otherwise, generate a new user id for them and set the cookie. 否则,为它们生成新的用户ID并设置cookie。

It's not perfect...if your user clears cookies you'll lose your ability to identity them, but it's probably the best you can do. 它并不完美......如果你的用户清除了你的身份,你就会失去识别身份的能力,但这可能是你能做到的最好的。

Here's some working code you can drop into your project and play with: 这里有一些可以放入项目并使用的代码:

public class PostController : Controller
{
    [HttpGet]
    public ActionResult Index(string text)
    {
        if (string.IsNullOrWhiteSpace(text))
            return Content("Please specifiy a value for text.  i.e. /Post/Index?text=Message");

        var message = "";

        var isAuthenticated = Request.Cookies["ident"] != null;
        if (isAuthenticated)
        {
            var userId = Request.Cookies["ident"].Value;
            var post = new
            {
                Text = text,
                User = userId
            };
            // Save to database here
            message = "You are a previously recognized user, with UserId=" + userId;
        }
        else
        {
            var userId = Guid.NewGuid().ToString();
            var identCookie = new HttpCookie("ident", userId);
            Response.Cookies.Add(identCookie);

            var post = new
            {
                Text = text,
                User = userId
            };
            // Save to database
            message = "You are a new anonymous user. Your new UserId=" + userId;
        }

        return Content(message);
    }
}

If you do end up going this route and you want to reuse this logic among multiple requests, I'd highly recommend abstracting it out into a utility class or, better yet, override the IPrincipal User property in the controller. 如果你最终走了这条路线而你想在多个请求中重用这个逻辑,我强烈建议将它抽象到实用程序类中,或者更好的是,覆盖控制器中的IPrincipal User属性。 Take a look [here]( ASP.NET MVC - Set custom IIdentity or IPrincipal for more information about setting a custom IPrincipal . 看看[这里]( ASP.NET MVC - 设置自定义IIdentity或IPrincipal ,了解有关设置自定义IPrincipal更多信息。

The ASP.NET Identity system is designed to replace the previous ASP.NET Membership and Simple Membership systems. ASP.NET Identity系统旨在取代以前的ASP.NET成员资格和简单成员资格系统。 It includes profile support , OAuth integration, works with OWIN, and is included with the ASP.NET templates shipped with Visual Studio 2013 它包括配置文件支持 ,OAuth集成,与OWIN一起使用,并包含在Visual Studio 2013附带的ASP.NET模板中

The ASP.NET user profile feature is designed to provide information that is unique to the current user. ASP.NET用户配置文件功能旨在提供当前用户特有的信息。 Profiles can work with either authenticated users or with anonymous (non-authenticated) users. 配置文件可以与经过身份验证的用户或匿名(未经身份验证的)用户一起使用。

In some cases, your application might initially be maintaining personalization information for an anonymous user, but eventually the user logs in to your application. 在某些情况下,您的应用程序最初可能会为匿名用户维护个性化信息,但最终用户会登录到您的应用程序。 In that case, the user's identity changes from the assigned anonymous user identity to the identity provided by the authentication process. 在这种情况下,用户的身份从分配的匿名用户身份变为身份验证过程提供的身份。

When users log in (that is, when they stop being anonymous users), the MigrateAnonymous event is raised. 当用户登录时(即,当他们不再是匿名用户时),将引发MigrateAnonymous事件。 You can handle this event to migrate information from the user's anonymous identity to the new authenticated identity, if necessary. 如有必要,您可以处理此事件以将信息从用户的匿名身份迁移到新的身份验证身份。

http://msdn.microsoft.com/en-us/library/vstudio/ewfkf772(v=vs.100).aspx http://msdn.microsoft.com/en-us/library/vstudio/ewfkf772(v=vs.100).aspx

Best way to Migrate Anonymous Profile 迁移匿名配置文件的最佳方式

http://odetocode.com/articles/440.aspx http://odetocode.com/articles/440.aspx

public void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs args)
{
  ProfileCommon anonymousProfile = Profile.GetProfile(args.AnonymousID);

  Profile.ZipCode = anonymousProfile.ZipCode;
  Profile.CityAndState = anonymousProfile.CityAndState;
  Profile.StockSymbols = anonymousProfile.StockSymbols;

  ////////
  // Delete the anonymous profile. If the anonymous ID is not 
  // needed in the rest of the site, remove the anonymous cookie.

  ProfileManager.DeleteProfile(args.AnonymousID);
  AnonymousIdentificationModule.ClearAnonymousIdentifier(); 

  // Delete the user row that was created for the anonymous user.
  Membership.DeleteUser(args.AnonymousID, true);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM