ASP.NET web api “Remember Me” functionality using

2019-06-26 02:45发布

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 = '';
    }
});

1条回答
做个烂人
2楼-- · 2019-06-26 03:13

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

查看更多
登录 后发表回答