28

Can you tell me why FormsAuthentication.SetAuthCookie(user.Name, false); is not causing Request.IsAuthenticated to be true?

Here is my code:

[HttpPost]
    public ActionResult LogIn(karcioszki.Models.UserLoginModel  user)
    {
        if (ModelState.IsValid)
        {
            if (IsValid(user.Name, user.Password))
            {
                FormsAuthentication.SetAuthCookie(user.Name, false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "Login or password is incorrect");
            }
        }

        return View(user);
    }

and if statement:

@if (Request.IsAuthenticated)
{
    <a href="@Href("~/")" class="active">Home</a>
    <a href="@Href("~/Cards")">Cards</a>
    @Html.ActionLink("Log out", "Logout", "User")
    @Html.Encode(User.Identity.Name)
}

Also, please tell me, how to make it work?

EDIT: I added authentication in web.config(both) but it still isn't working.

<system.web>
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5" />
<authentication mode="Windows"/>
<pages>
  <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages" />
    <add namespace="System.Web.Optimization" /> 
  </namespaces>
</pages>

Should I use Windows or other mode?

Kmaczek
  • 638
  • 2
  • 8
  • 23
  • Where (in what view) is this `if` statement located? – Andrei Oct 23 '13 at 08:49
  • Have you checked whether ModelSate.IsValid is true? There might be an issue with the model you are sending to the action. – James Oct 23 '13 at 08:50
  • 1
    checked that everything is ok with the `authentication` element of your web.config ? Could you post it ? – jbl Oct 23 '13 at 08:52
  • if is located in Layout file. Model is valid, i debuged this and it goes through, also user.Name is correct. Hmm... I dont hav authentication element in web.config(in both). – Kmaczek Oct 23 '13 at 09:01
  • 2
    Form authentication section is missing i.e – Spock Oct 23 '13 at 09:37
  • YES, it works. Thx for both answers Raj and jbl. Could you post this as an answer Raj? – Kmaczek Oct 23 '13 at 09:44

10 Answers10

49

I had the same problem in an MVC5 project. The solution was to add the following lines to the modules section in the system.webServer

<remove name="FormsAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
Ger Groot
  • 1,071
  • 11
  • 7
16

you must set FormsAuthentication.SetAuthCookie(acct.UserName, true); after validating user and please check you must set authentication mode="Forms" in web.config.

slfan
  • 8,950
  • 115
  • 65
  • 78
Sanjay Sharma
  • 635
  • 8
  • 10
10

Add the following code in your Web.config

<authentication mode="Forms">
  <forms loginUrl="~/_Login/Login" timeout="30" />
</authentication>

and

  <modules>
  <remove name="FormsAuthentication" />
  <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
</modules>
Long Luong
  • 764
  • 2
  • 14
  • 28
  • Link to the doc that explains in which section authentication must be (system.web) https://msdn.microsoft.com/fr-fr/library/532aee0e(v=vs.71).aspx – sandwood Mar 20 '18 at 15:25
2

You are checking if the user is authenticated. So use:

if (User.Identity.IsAuthenticated) 

This will fix the issue and as mentioned set the authentication element in your web.config to Forms and not Windows.

AliK
  • 962
  • 2
  • 10
  • 31
  • 1
    It works for both `User.Identity.IsAuthenticated` and `Request.IsAuthenticated`, is there any difference between this two? They seem work identically. Changing authentication to Forms was the key. – Kmaczek Oct 23 '13 at 09:46
  • 7
    @Kmaczek There's no practical difference between the two. In fact, the implementation of `Request.IsAuthenticated` just checks `User.Identity.IsAuthenticated` in addition to checking whether `User` or `User.Identity` are null. So you can just stick with `Request.IsAuthenticated`. – Martin Wedvich Oct 23 '13 at 10:19
2

I was looking for about 2 hours now to solve the problem. And in case you already got setups like you are told to in several guides (as MSDN and so) and you still got the problem, the one and only thing that will solve it is to add:

<system.webServer>
  <modules>
     <remove name="FormsAuthentication" />
     <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
  </modules>
<system.webServer>

within the webconfig.

blu3drag0n
  • 61
  • 4
1

I had exactly same problem in my MVC4 Web Application. One more possible reason for this problem is below method in IdentityModels.cs file

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
                            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
                            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
                            // Add custom user claims here
                   return userIdentity;
    }

Make sure DefaultAuthenticationTypes is ApplicationCookie

Cheers,

user2243747
  • 2,767
  • 6
  • 41
  • 61
1

In my case, it was a problem in Chrome browser. I just removed all cookies stored and works.

1

In my case I had this issue which ended up in a redirect-loop where the user would be redirected to the login, successfully logged in and then back to our site but since Request.IsAuthenticated was false the user was redirected to the login again.

In our case this was solved by using another CookieManager,

var cookieOptions = new CookieAuthenticationOptions();
cookieOptions.CookieManager = new SystemWebCookieManager(); 
app.UseCookieAuthentication(cookieOptions);

Turns out that there was some kind of bug in Katana that this other CookieManager worked around, in out case this solved the issue.

https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues

  • 1
    I've spent three days trying to figure out the exact problem you just described, and your solution worked like magic You are an angel – codeMonkey Sep 13 '22 at 21:35
0

I solve it by deleting the caches and cookies in browser.

0

Just do it

     <system.web>
    <authentication mode="Forms">
      <forms cookieless="UseCookies" loginUrl="~/User/Login" slidingExpiration="true"> 
   </forms>
    </authentication>
..........
.......
  </system.web>
tayfun Kılıç
  • 2,042
  • 1
  • 14
  • 11