简体   繁体   中英

ASP.NET web api “Remember Me” functionality using cookies

I am trying to implement a "Remember Me" functionality in my Web Api project.

I would like to :

  • 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.

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

I should implement the RememberMe() in the AccountController ??

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

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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