Dhanushka Weerasinghe
Dhanushka Weerasinghe

Reputation: 177

Remember me option not working using cookies in ASP .Net MVC

I have created login using asp .net MVC and I have added a cookie for users who select the "Remember me" option. Below is the code used to add a cookie

 if (model.LoginViewModel.RememberMe)
 {
    var authTicket = new FormsAuthenticationTicket(
                        1,
                        model.LoginViewModel.Email,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(20), // expiry
                        model.LoginViewModel.RememberMe, //true to remember
                        "",
                        "/");

    //encrypt the ticket and add it to a cookie
    HttpCookie cookie = new HttpCookie(
                           FormsAuthentication.FormsCookieName,
                           FormsAuthentication.Encrypt(authTicket));
    Response.Cookies.Add(cookie);
 }

and I have added this configuration to the web.config as well.

<authentication mode="Forms">
  <forms loginUrl="~/candidate" timeout="2880" />
</authentication>

I still can't see my login details when I am going to login for the second time.

Do I have missed something here or are there any other way achieve this?

Upvotes: 0

Views: 721

Answers (1)

Tieson T.
Tieson T.

Reputation: 21231

The bare minimum to replicate FormsAuthentication using OWIN would use something similar to this:

using System.Collections.Generic;
using System.Security.Claims;
using System.Web;
//
using Microsoft.Owin.Security;

namespace YourProjectNamespace
{
    public class ClaimsAuthManager
    {
        public void SignIn(string userName, string displayName = "", bool createPersistantLogin = false)
        {
            var claims = new List<Claim>();

            claims.Add(new Claim(ClaimTypes.Name, userName));
            claims.Add(new Claim(ClaimTypes.IsPersistent, createPersistantLogin.ToString()));

            claims.Add(new Claim(ClaimTypes.GivenName, string.IsNullOrWhiteSpace(displayName) ? userName : displayName));

            var identity = new ClaimsIdentity(claims, AuthenticationTypes.ApplicationCookie);

            GetAuthenticationContext().SignIn(new AuthenticationProperties { IsPersistent = createPersistantLogin }, identity);
        }

        public void SignOut()
        {
            GetAuthenticationContext().SignOut(AuthenticationTypes.ApplicationCookie);
        }

        private IAuthenticationManager GetAuthenticationContext()
        {
            return HttpContext.Current.GetOwinContext().Authentication;
        }
    }
}

Unlike FormsAuthentication, this is not a static/singleton object, so you'd need to either inject it into the controller, or create a new instance each time you wanted to sign the user in or out. Something like this:

new ClaimsAuthManager().SignIn(model.LoginViewModel.Email, null, model.LoginViewModel.RememberMe);

Upvotes: 1

Related Questions