简体   繁体   中英

WebMatrix razor C# WebSecurity Logging in but Web.Security.IsAuthenticated not returning right check

I have a quick question. In my code, I have this:

if(!(username.IsEmpty() || password.IsEmpty()))
    {
        if (WebSecurity.UserExists(username) && WebSecurity.GetPasswordFailuresSinceLastSuccess(username) > 4 && WebSecurity.GetLastPasswordFailureDate(username).AddSeconds(120) > DateTime.UtcNow) 
        {
            Session["gActionMessage"] = "You're account has been locked due to too many failed login attempts. " +
                                            "Please try again in 2 minutes.";
            Session["gActionMessageDisplayed"] = "not";
            Response.Redirect("~/");
            return;
        }

        if(WebSecurity.Login(username, password, false))
        {
            errorMessage = "";
        }
    }

    if (!WebSecurity.IsAuthenticated)
    {
        errorMessage = "You are no longer logged in. Please supply your username and password credentials along with the rest of the form data.";
    }

When I attempt to use this code (the check right after the login is actually within an if(IsPost), so that I can check whether the user is still logged in before using the posted data. When it fails the check "if(!WebSecurity.IsAuthenticated)" for the first time, a small section of the page opens up, asking for login information. Once reentered and re-posted, the check reads the value of "username" and "password" and attempts to re-log them in. It does just that, however directly after they are supposed to be "logged in" it passes the "if(!WebSecurity.IsAuthenticated)" branch and executes its contents. Am I checking the "if(!WebSecurity.IsAuthenticated)" to soon? Does the page have to finish loading before a person is actually considered authenticated?

I just can't seem to pinpoint why this is happening and haven't been able to find any help in research either.

Thanks, everyone, for any help!

UPDATE:

I have posted the code that appears below the code above, below:

if((Roles.IsUserInRole((WebSecurity.CurrentUserName), "Locked")) || (Roles.IsUserInRole((WebSecurity.CurrentUserName), "AdminLocked")))
    {
        Session["gActionMessage"] = "Your account is locked. ";
        Session["gActionMessage"] += "Please contact an administrator and ask that your account be approved.";
        Session["gActionMessageDisplayed"] = "not";
        Response.Redirect("~/");
    }
}
}

@RenderPage("~/Shared/HeaderLayout.cshtml")

        <div>
            <span><button type="button" class="btn" onclick="location.href='/IntroPage.cshtml'">Main Page</button></span><span class="heading">Lookup Entry</span><span><button type="button" class="btn" onclick="javascript:document.getElementById('searchForm').submit()">Search</button></span></br></br>
            <span style="font-size: 3em; color: #808080;">________________________________________________</span></br></br></br>
        </div>

        <div id="FormHolder">
            <form id="searchForm" class="searchForm" method="post" action="">
        @{
            if (errorMessage != "")
            {
                <div class="errorMessageWrapper"><span style="font-style: italic; font-weight: 700;">ERROR:</span><br/>@errorMessage<br/><br/>
                    @if(!WebSecurity.IsAuthenticated && success==false)
                    {
                        <table class="accInterfaceTable">
                            <tr>
                                <td class="accInterfaceLabelCell">
                                    <label for="username">Email:</label>
                                </td>
                                <td class="accInterfaceInputCell">
                                    <input type="text" id="username" name="username" /><br/><br/>
                                </td>
                            </tr>
                            <tr>
                                <td class="accInterfaceLabelCell">
                                    <label for="password">Password:</label>
                                </td>
                                <td>
                                    <input type="password" id="password" name="password" /><br/><br/>
                                </td>
                            </tr>
                        </table><br/><br/>
                        <input type="hidden" id="hiddenLoginSubmit" name="hiddenLoginSubmit" value="" />
                        <input type="submit" class="btn" value="Log In" />
                    }
                </div><br/>
            }
        }
                <table class="searchTable">
                    <tr>
                        <th>Search Field<br/><br/></th>
                        <th></th>
                        <th>Search Condition<br/><br/></th>
                        <th></th>
                        <th>Search Parameter<br/><br/></th>
                    </tr>

There is more html below this, but it is just a redundant html form.

UPDATE2:

Well, I never did find a reason why the "if(!WebSecurity.IsAuthenticated)" branch is executed directly after an explicit "if(WebSecurity.Login(username, password, false))" branch is executed, however I was able to tie in a separate local boolean variable to the logic and everything is working fine now (I checked to make sure it will always check unless JUST signed in with the branch above, and checked to make sure it does in fact log in, etc.).

If anyone could tell me why this was happening for the benefit of my (and anyone else who comes across this page and has run into a similar problem) education, I will gladly accept the answer.

Thanks for the help!

I remember reading on MSDN or someplace, the WebSecurity.IsAuthenticated does not work until the page is fully loaded. Meaning if you login a user in a page and in the same flow of code you check IsAuthenticated, it will NOT return True. For IsAuthenticated to be True the page has to be reloaded or use the better practice; which is to redirect the user to another secured page as soon as the login is successful and in that page check IsAuthenticated.

Hope it helps.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM