2

Below is the code used to login

WebSecurity.Login("abc", "123", true);//return true
return RedirectToAction("afterLogin", @"afterLogin");

After loggin in, I checked the user's id to see if it's -1 by running the below line:

WebSecurity.CurrentUserId

But why whenever I called this, the return value always -1 and CurrentUserName is empty?

edited:

An additional question:

Does the WebSecurity have something like timeout so that the user idle for a specific period and will logged out automatically?

tereško
  • 58,060
  • 25
  • 98
  • 150
User2012384
  • 4,769
  • 16
  • 70
  • 106
  • possible duplicate of [MVC 4 SimpleMembership - Why WebSecurity.CurrentUserId -1 after login](http://stackoverflow.com/questions/13850861/mvc-4-simplemembership-why-websecurity-currentuserid-1-after-login) – Yogesh Oct 27 '13 at 17:07
  • I've tried the solution before on that link, I've redirected to another page, but the result was still the same. – User2012384 Oct 28 '13 at 01:49
  • You should split this into 2 different questions. – Mike Brind Oct 28 '13 at 05:46

2 Answers2

3

Check your webconfig, you have to enable forms authentication:

Add following snippet inside

   <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="3600" />
    </authentication>

Comment out if it is in your webconfig:

<!--<modules>
      <remove name="FormsAuthentication" />
</modules>-->

Now you can check

WebSecurity.CurrentUserName, WebSecurity.CurrentUserId and , WebSecurity.IsAuthenticated flags;

Also add this class in app_start

public static class AuthConfig
    {
        public static void RegisterAuth()
        {
 }
}

and call this in AppStart in Global.asax.cs

AuthConfig.RegisterAuth();
Nalan Madheswaran
  • 10,136
  • 1
  • 57
  • 42
2

I think the default expiration is when the browser session ends. It might be that cookies are not enabled and that's why it is returning -1 cookies need to be enabled.

  • I've checked the developer tools and found there's a cookie called "AUTH" and has value in it.. – User2012384 Oct 29 '13 at 01:02
  • Quite strange I have no idea what's going on then. You might want to debug your website in Visual Studio. –  Nov 02 '13 at 10:20
  • Do I need to "Redirect" to another page for the cookie to take effect? or can I have an example about how to use the WebSecurity.CurrentUserName function.? – User2012384 Nov 02 '13 at 16:06
  • Hi, there is a ref for the WebSecurity class available here: http://www.thecodingguys.net/reference/asp/websecurity-class –  Nov 02 '13 at 16:39
  • Thanks, let me take a look at it. – User2012384 Nov 03 '13 at 10:23