2016-04-04 67 views
2

我試圖在我的Web Api項目中實現「記住我」功能。ASP.NET web api使用Cookie的「記住我」功能

我想:

  • 記住功能,當用戶登錄
  • 節省餅乾爲保持始終登錄的用戶,使用戶無需鍵入用戶名密碼一個時間,當他們訪問的網站。
  • 通過閱讀上次登錄時保存的cookies對用戶進行簽名。 ,我想的是

一個問題......我想產生餅乾使用JavaScript當用戶選中的記住複選框。是否有可能做到這一點?

OR

我應該落實在AccountControllerRememberMe()

增加: 這裏是我的代碼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中。

$('#checkbox').click(function() { 

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

回答

2

你需要在你應用能夠提供這個功能來實現刷新令牌

基本上,您需要創建一個將生成刷新令牌的RefreshTokenOAuthProvider。您可以使用兩種類型的client_id來區分需要記住或不記住的客戶。

這是在this excellent series of blog posts(雖然它可能會開始有點過時,有關owin設置的信息是黃金)解釋。

+0

我認爲你的鏈接不正確。 [This](http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/)是正確的 – Pikoh