Dhanuka777
Dhanuka777

Reputation: 8636

MVC 5 Forms authentication retuns null for User.Identity.Name

Authentication fails to authenticate for forms authentication in my MVC 5 application. Page gets redirected correctly, but User.Identity.IsAuthenticated and User.Identity.Name values are empty.

My webconfig,

  <system.web>        
    <authentication mode="Forms">
          <forms cookieless="UseCookies" defaultUrl="~/" loginUrl="~/user/signin"  name="MYAPPWeb" timeout="21600" slidingExpiration="true"/>
        </authentication>

UserController,

 [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult SignIn(SignInViewModel user)
        {

                        UserDTO userObj;
                        using (var services = new ServiceFactory())
                        {                            
                            userObj = services.UserManagement.ValidateLoginDetails(ConfigHelper.EnvironmentString, user.TenantName, user.Username, user.Password);
                        }
                                string userID = userObj.UserID.ToString();
                                //FormsAuthentication.RedirectFromLoginPage(userID, user.RememberMe);
                                FormsAuthentication.SetAuthCookie(userID.ToString(),true);

                                FormsAuthentication.RedirectFromLoginPage(userID, false); //DO NOT REMEMBER ME

}

HomeController (Default page)

 public ActionResult Index()
        {

            bool x = User.Identity.IsAuthenticated; //false?
            string y = User.Identity.Name; //null?

return View();
}

It looks pretty straight forward, am I missing something? Please help!

Note:
When I create the project I selected windows authentication. It created some Owin authenticaiton related configuration cs files (startup.auth.cs). I have removed them and added the above appsetting entry as it is required to stop loading Owin assemblies.

<add key="owin:AutomaticAppStartup" value="false"/>

Upvotes: 4

Views: 1460

Answers (1)

cp100
cp100

Reputation: 1503

If your project has Owin authentication by default, it will remove form authentication from the project. If you see your web config you may see

<remove name="FormsAuthentication" />

configuration.

Simply remove it.

I had the same problem and it solved the issue.

Upvotes: 5

Related Questions