I am trying to configure authentication using a few tutorials I have found on the Membership Providers paradigm found in ASP.NET v2.0. I've followed the examples in the tutorial but can't seem to get the FormsAuthentication.RedirectFromPage method to work appropriately. When I attempt a login, the user credentials are validated via Membership.ValidateUser but the page is sent back to Login.aspx instead of Default.aspx. Here is the relevant snippet from my web.config:
...
<authentication mode="Forms">
<forms loginUrl="Login.aspx" protection="All" timeout="60" name="POTOKCookie" requireSSL="false" path="/FormsAuth"
slidingExpiration="true" cookieless="UseCookies" enableCrossAppRedirects="false" defaultUrl="~/Default.aspx"/>
</authentication>
<authorization>
<deny users="?" />
</authorization>
...
<membership defaultProvider="CustomizedProvider">
<providers>
<clear />
<add name="CustomizedProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="LoginDB2"
applicationName="POTOK"
minRequiredPasswordLength="5"
minRequiredNonalphanumericCharacters="0" />
</providers>
</membership>
I've verified that my connection string is correct (since Membership.ValidateUser seems to be working just fine) and am using the ASP.NET Login control for the UI on my Login.aspx page. Here is the authenticate event handler code:
Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
If (Membership.ValidateUser(Login1.UserName, Login1.Password)) Then
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
End If
End Sub
When I visit the url (http://localhost/Project) I am taken to: http://localhost/Project/Login.aspx and after the "login" my url is: http://localhost/Project/Login.aspx?ReturnUrl=%2fProject%2fDefault.aspx
Did I miss a configuration step?
The problem is in path="/FormsAuth" parameter.
Remove this variable and try again
Read this post about why path can be wrong
From MSDN:
path - Optional attribute. Specifies the path for cookies that are issued by the application. The default is a slash (/), because most browsers are case-sensitive and will not send cookies back, if there is a path case mismatch.
NOTE: The path attribute is case sensitive. Therefore, if the you set the value of the path attribute to /application1, and if the application name is Application1, the authentication cookie path is /application1.
So if you want to use path property, you should set it to "/project" because Project is the name of your application (as far as I understood). But I don't think you need to have different paths when you use different cookies names (i.e. name="POTOKCookie" in this application, i hope will be different from other ASP.NET applications installed on the same host)
See PRB: Forms Authentication Requests Are Not Directed to loginUrl Page
If you use the Login control with ASP.NET membership, you do not need to write code to perform authentication. However, if you want to create your own authentication logic, you can handle the Login control's Authenticate event and add custom authentication code.
So, I suggest you simply delete Login1_Authenticate event as far as it does the double work, I think, because control itself is responsible for calling ValidateUser and redirection.
Also check DestinationPageUrl property of the Login control
If you do not specify a value for the DestinationPageUrl property, the user will be redirected to the original page the user requested after successfully logging in. So in your case this property should not be set.
Related
I am working on an asp.net mvc-4 web application hosted under IIS-8 and windows server 2008 R2.
now for the asp.net mvc i am using form authentication, which is integrated with our active directory.
here is the related entities inside our web.config :-
<membership>
<providers>
<add name="TestDomain1ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="TestDomain1ConnectionString" connectionUsername="*********" connectionPassword="******" attributeMapUsername="sAMAccountName" />
</providers>
</membership>
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="40320" />
</authentication>
now my question is about the timeout parameter inside the <forms>. now i understand this setting as follow:-
When the user first login to the web application , he will enter a username & password. if his credentials are valid, a browser cookie will be generated to him, and saved inside the browser cache. now since i have specified a timeout="40320". this means that the browser cookie will expire after 40320 minute ?? is this correct ? so if the user try to access the system after 40320+ minute from his first login, then IIS will see that the passed cookie is expired and will logout the user .. is this correct ?
https://msdn.microsoft.com/en-IN/library/1d3t3c61(v=vs.85).aspx
Optional attribute.
Specifies the time, in integer minutes, after which the cookie expires. If the SlidingExpiration attribute is true, the timeout attribute is a sliding value, expiring at the specified number of minutes after the time that the last request was received. To prevent compromised performance, and to avoid multiple browser warnings for users who have cookie warnings turned on, the cookie is updated when more than half of the specified time has elapsed. This might cause a loss of precision. The default is "30" (30 minutes).
I have a site that uses the default SqlMembershipProvider and FormsAuthentication. I can use the built-in Login Controls and/or programmatically call all the methods to authenticate a user and get the same result - the user is authenticated and a cookie is created, but the cookie does not appear to be valid since I can't get into any page that requires authentication.
There is no real code to show for the default Login Control since it should just "work", but here is the custom code I tried:
protected void ctrlLogin_Authenticate(object sender, AuthenticateEventArgs e)
{
if (Membership.ValidateUser(ctrlLogin.UserName, ctrlLogin.Password))
{
FormsAuthentication.RedirectFromLoginPage(ctrlLogin.UserName, ctrlLogin.RememberMeSet);
/*
* I also tried this:
FormsAuthentication.SetAuthCookie(ctrlLogin.UserName, ctrlLogin.RememberMeSet);
if (!String.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
Response.Redirect(Request.QueryString["ReturnUrl"]);
Response.Redirect("/index.aspx");
*/
}
else
{
ctrlLogin.FailureText = "Invalid Username/Password Combination";
}
}
With this code, Membership.ValidateUser() succeeds, and both FormsAuthentication.RedirectFromLoginPage() and FormsAuthentication.RedirectFromLoginPage() successfully set a cookie - that cookie just doesn't work to verify my authentication. I have confirmed this by deleting all my cookies and watching them get created again with FireCookie. The cookie name matches what I have in my web.config, the domain is "/", and the expiration date is as expected (see below).
Here are the relevant sections of my web.config:
<authentication mode="Forms">
<forms loginUrl="~/login/index.aspx" name=".SoeAuth" protection="All"
slidingExpiration="true" timeout="525599" domain=""></forms>
</authentication>
<membership defaultProvider="SqlMembershipProvider">
<providers>
<add connectionStringName="[MY_CS]" applicationName="[MY_APPNAME]"
minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0"
enablePasswordReset="true" passwordFormat="Hashed" requiresUniqueEmail="true"
name="SqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider"
requiresQuestionAndAnswer="false"/>
</providers>
</membership>
It should be noted that I also added a machineKey entry in my web.config file based on a suggestion from a very similar question here (which didn't solve my problem). Also, for reference, the timeout=525599 above is 1 minute less than a year for my persistent cookies.
I found the problem:
Since I was able to create a simple working test project with the exact same source code, I determined that the problem was in the web.config file.
Going through each section, I discovered in the 'system.web / httpModules' section I had a <clear/> element. This removed the <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/> module defined in machine-level web.config file. Adding it back in instantly fixed the problem.
It sure would have been nice to get an error message when I tried to use the FormsAuthentication methods and that module wasn't even loaded...
I use FormsAuthentication.RedirectFromLoginPage(userName.Trim(), false); to set the User.Identity.Name field that I reference later. When I execute this line, the User.Identity object does not update at all; it contains whatever it was previously set to. All the documentation I see online says this should update my User.Identity object with the correct name, but I don't see that happening.
I have the web config set up properly with the following lines:
<authentication mode="Forms">
<forms name="formsauth" loginUrl="Login.aspx" protection="All" timeout="60">
</forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
I am relatively new to this stuff, so any help is appreciated. Thanks!
It will be updated on the next request but not on the next line following it. RedirectFromLoginPage sets an authentication cookie in the client browser that will be read upon the next client request and you will see the User.Identity.Name property updated. Updating this property in the same HTTP request is meaningless as you already know that the user passed authentication as you called the method.
I am using a Response.Redirect in global.asax.cs.
When the page loads the RawUrl property contains an encoded directory of some kind.
"/(F(D7zFAWNl_SpT-cuyRXksIZnvwBB_bYfBl3ens83McZjPg9zLBvcjvik6FkwBNhnjeK-faeUt6PUYOZSsYXKdg4hi4IDPTDO5diQf693NLpw1))/Integration/Workflow.aspx"
Where does this horrible directory come from?
It's breaking a bunch of user controls on the target page which use the RawUrl to get path information.
Why would Response.Redirect invent this horrible path and add it?
Is there any way around this?
Thanks
Craig
"(F(D7zFAWNl_SpT-cuyRXksIZnvwBB_bYfBl3ens83McZjPg9zLBvcjvik6FkwBNhnjeK-faeUt6PUYOZSsYXKdg4hi4IDPTDO5diQf693NLpw1))" is your session id or auth. id stored in your URL and not in a cookie. You can change this in your web.config file
It is the setting that is taken from the web.config as in the following location;
<authentication mode="Forms">
<forms loginUrl="~/en/Access/Login" defaultUrl="~" cookieless="UseUri" timeout="2880" />
</authentication>
If you set cookieless="UseUri", your session details will be appended to your URL instead of storing in a cookie.
Set cookieless="UseCookies" or remove the cookieless attribute to use cookie instead of URL for session details
I want to set my FormsAuthentication cookie to timeout BUT VIA CODE. I know I can do this in the web.config but I want to configure at the database. Is this possible via code?
<system.web>
<authentication mode="Forms">
<forms timeout="50000000"/>
</authentication>
</system.web>
To do this you'll need to create your own FormsAuthenticationTicket and cookie and add it to the response manually. See the example on the linked page.