ASP.NET Web API“记住我"使用cookie的功能 [英] ASP.NET web api "Remember Me" functionality using cookies
问题描述
我正在尝试在我的 Web Api 项目中实现记住我" 功能.
I am trying to implement a "Remember Me" functionality in my Web Api project.
我想:
- 当用户登录时,
- 具有记住我功能.
- 保存 cookies 以使用户始终保持登录状态,从而使用户无需每次都键入 username 和 password 当他们访问网站时.
- 通过阅读上次登录时保存的 cookies 来登录用户.
- have the Remember Me functionality when the user Sign In.
- save a cookies for to keep the user always logged in, so that the user no need type the username and password every single time when they visit the websites.
- Sign the user in by reading the cookies that saved on the last login.
我正在考虑的另一个问题是...当用户选中记住我<时,我正在尝试使用 JavaScript
生成 cookies ./em>复选框.是否有可能做到这一点?
One more question that I am thinking about is... I am trying to generate the cookies by using JavaScript
when the user checked the Remember Me Checkbox. Is it possible to do this?
OR
我应该在 AccountController
??
添加:这是我在 ApplicationOAuthProvider
中的代码.
Addition:
Here's my code in ApplicationOAuthProvider
.
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
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中.
In my 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 = '';
}
});
推荐答案
您需要在应用中实现刷新令牌才能提供此功能.
You need to implement refresh tokens in you app to be able to offer this functionality.
基本上,您需要创建一个将生成刷新令牌的 RefreshTokenOAuthProvider
.您可以使用两种类型的 client_id
区分需要记住或不记住的客户.
Basically, you need to create a RefreshTokenOAuthProvider
that will generate refresh tokens. You can use 2 types of client_id
to make a difference between clients who need to be remembered or not.
It is explained in this excellent series of blog posts (though it might start to become a little bit outdated, the information regarding owin setup is gold).
这篇关于ASP.NET Web API“记住我"使用cookie的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!