使用cookie的ASP.NET web api“记住我”function

我正在尝试在我的Web Api项目中实现“记住我”function。

我想要 :

  • 用户登录时拥有“ 记住我”function。
  • 保存cookie以保持用户始终登录,以便用户在访问网站时无需每次都输入用户名密码
  • 通过阅读上次登录时保存的cookie来签署用户。

我正在考虑的另一个问题是……我正在尝试使用JavaScript在用户选中“ 记住我”复选框时生成cookie 。 是否有可能做到这一点?

要么

我应该在AccountController实现RememberMe() ??

另外:这是我在ApplicationOAuthProvider的代码。

  public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManager(); ApplicationUser user = await userManager.FindByNameAsync(context.UserName); if (user == null) {...} if (userManager.IsLockedOut(user.Id)) {...} if (!(await userManager.CheckPasswordAsync(user, context.Password))) { ... } if (!user.EmailConfirmed) {...} ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); 

在我的JavaScript中。

 $('#checkbox').click(function () { if ($('#checkbox').is(':checked')) { // save username and password username = $('#txtLoginEmail').val(); password = $('#pass').val(); checkbox = $('#chkRememberMe').val(); } else { username = ''; password = ''; checkbox = ''; } }); 

您需要在应用程序中实现刷新令牌才能提供此function。

基本上,您需要创建一个生成刷新令牌的RefreshTokenOAuthProvider 。 您可以使用两种类型的client_id来区分需要记住的客户端。

在这篇优秀的博客文章系列中对此进行了解释(虽然它可能会开始变得有点过时,但有关owin设置的信息是黄金)。