Forms Authentication works locally, but not on dev server - c#

I know Forms Authentication is old, but when I run the web application locally using IIS Express, everything works well. But when I publish it to our development/test server, it just reloads the page. The dev server is running IIS 6.
One more thing to note, locally it runs as localhost:50264/Login. On the dev server, the url is more like http://dev1.server.com/op/webapp/Account/Login.
I notice that both of the cookies have the path "/". I did try to set change that by having this in my local web.config:
<add key="CookiePath" value="/" />
And then when I publish to our dev server it changest to:
<add key="CookiePath" value="http://dev1.server.com/op/webapp/" xdt:Transform="Replace" xdt:Locator="Match(key)" />
That didn't seem to work.
In another thread that I found in Stack Overflow, someone suggested to add this to the :
<system.webServer>
<modules>
<add name="FormsAuthenticationModule" type="System.Web.Security.FormsAuthenticationModule" />
</modules>
</system.webServer>
That didn't work either. Any help would be greatly appreciated!
UPDATE: 9/29/2016
I removed the CookiePath app setting and, instead made an adjustment to the authentication node. In my Web.config I now have:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" requireSSL="false" slidingExpiration="true" path="/" />
</authentication>
And in my Web.Debug.config I have:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" requireSSL="false" slidingExpiration="true" path="/op" xdt:Transform="Replace" />
</authentication>
Finally, when I create the cookie:
var authTicket = new FormsAuthenticationTicket(
1,
user.Email,
DateTime.Now,
DateTime.Now.AddDays(14),
true,
userData,
FormsAuthentication.FormsCookiePath);
When I deploy to the dev server, I check the web.config there and it did transform the forms node correctly.
When I go to login, I enter my credentials and it still refreshes the Login page. With the Chrome extension "EditThisCookie" I still see that the path of the cookie is "/". It doesn't recognize the change AT ALL. Even when I manually set the path of authTicket path to "/op" the cookie STILL has the path as "/". I have no idea what's going on. Ugh...

I use forms authentication also, here's my settings. You didn't show all your forms Authentication code, but hopefully this will point you in the right direction.
Web.Config
<authentication mode="Forms">
<forms loginUrl="members/login.aspx" name=".ASPXFORMSAUTH" requireSSL="false" slidingExpiration="true" timeout="120" />
</authentication>
Then I set the cookie in the code behind when the user logs in.
Dim authCookie As HttpCookie = FormsAuthentication.GetAuthCookie(iMembersID, False)
Dim ticket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(authCookie.Value)
Dim newTicket As FormsAuthenticationTicket = New FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, "Member")
authCookie.Value = FormsAuthentication.Encrypt(newTicket)
Response.Cookies.Add(authCookie)
Then I test to see if they are authenticated on all pages that require the user to be logged in.
If Request.IsAuthenticated Then
Dim ident As FormsIdentity = CType(User.Identity, FormsIdentity)
If ident IsNot Nothing Then
Dim ticket As FormsAuthenticationTicket = ident.Ticket
Dim userDataString As String = ticket.UserData
Select Case ticket.UserData
Case "Member"
m_MemberLoggedIn = ident.Name
Case Else
Response.Redirect("~/members/login/", True)
End Select
Else
Response.Redirect("~/members/login/", True)
End If
Update 9/29:
Check to make sure the IIS Authentication mode to set to Anonymous

I went the easy way out and asked our IT Dept to create a subdomain so the path of the cookie will always be "/". Not an answer, but it's what I did.

Related

Cookie Based Forms Authentication is Not Working when the website is in an iFrame

I have developed a Windows Forms Application in C# and It's perfectly working. Recently, my client raised a requirement that is, he wants to load this website inside an iframe of another website.
So, I created a simple HTML application with a iframe to test this scenario.
While testing, I have identified some properties were not set in the process of ticket building of Forms Authentication. Does anyone know what is the issue here?
This is the way I set cookie,
var cookie = FormsAuthentication.GetAuthCookie(userId, chkRememberMe.Checked);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration,
ticket.IsPersistent, "insured", ticket.CookiePath);
var encTicket = FormsAuthentication.Encrypt(newTicket);
cookie.Value = encTicket;
Response.Cookies.Add(cookie);
Here is the properties of the Page.User.Identity object,
AuthenticationType = ""
IsAuthenticated = false
Name = ""
Ticket object is not available
Web.config
<system.web>
<sessionState cookieSameSite="None" timeout="20"/>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="Login.aspx">
</forms>
</authentication>
.
.
</system.web>

Best way to redirect user to Login page on cache lost

What is the best way to redirect user to login when cache is lost?
At moment I'm doing this:
if (Session["Id"] == null)
{
return RedirectToAction("Login", "Home");
}
But with this method, it put this code in every function, is there any other way to do this in the entire program? I tried search by doing this from web.config, but no results.
Assuming you are using Form-based authentication and permitting access to only authorised users then this could be achieved through making changes in web.config
<authentication mode="Forms">
<forms loginUrl="login.aspx" defaultUrl="default.aspx" name=".YourApplication" timeout="60" cookieless="AutoDetect" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
the loginUrl property tells the server where to direct the user if he is not logged in, and the defaultUrl property tells the server where to direct him after the user is logged.
the deny users="?" tells the server to deny any user that is not authenticated and directs him to the loginUrl page
In the codebehind of the login page, you need something like this after you check the credentials inserted:
FormsAuthentication.RedirectFromLoginPage(userName.Text, True)
Reference
private const string GlobalAuthKey = "GlobalAuthTime";
You can insert all auth user info in authList.
HttpRuntime.Cache.Insert(GlobalAuthKey, authList);
Then Get cache :
var authList = HttpRuntime.Cache.Get(GlobalAuthKey) as List<AuthInfo> ?? new
List<AuthInfo>();
After that you check this specific user login info,and you force your user by this desire condition.Hopefully You understand.

ASP.NET 4.5 authentication cookie is not persisted on Azure Web Role

I have problems with Forms Authentication on our Azure WebRole. It does not store the authentication cookie for the login. Once the user initiates a new session, he has to login again.
First I tried:
FormsAuthentication.SetAuthCookie(userIdent, rememberMe);
Now doing it manually:
var ticket = new FormsAuthenticationTicket(1, userIdent, DateTime.Now, DateTime.Now.AddMonths(6),rememberMe,string.Empty, FormsAuthentication.FormsCookiePath);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket)
{
Path = FormsAuthentication.FormsCookiePath,
HttpOnly = true
};
if (rememberMe)
{
cookie.Expires = ticket.Expiration;
}
Response.Cookies.Add(cookie);
Here a snippet from the web.config:
<machineKey decryption="Auto" decryptionKey="<My Decryption Key>" validation="SHA1" validationKey="<MyValidationKey>" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" slidingExpiration="true" timeout="2880" cookieless="UseCookies" />
</authentication>
But the problem remains. Sometimes it does remember it ?. Because it's running in an Azure WebRole, we added the MachineKey to web.config.
The problem might not be related to Azure Web Role, because we noticed the same behavior, running locally. Eg. localhost:7778

ASP.NET MVC4 Simplemembership or autoFormsAuthentication?

I'm new to ASP.NET MVC4 and therefore read many things about how to authenticate on an Intranet Website.
I've inherited of this type of project in order to improve it and after quick reading the source code, I saw that login/password are stored in clear text in a SqlServer database...
So my first improvement is to upgrade the authentication process in order to store passwords in the right manner.
Here is what I've done so far, in my GlobalAsax.cs add :
WebSecurity.InitializeDatabaseConnection(
connectionStringName: "AppConnectionString",
userTableName: "Employe",
userIdColumn: "IDE",
userNameColumn: "E_mail",
autoCreateTables: true);
in order to add the "webpages_*" tables to my database.
I changed the IIS configuration in order to deactive "AllowAnonymous" connection and activate "Basic Authentication".
But now I'm faced to Forms vs SimpleMembership, my Web.config:
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="true" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="30" />
</authentication>
Can someone explain me clearly the use of each attribute?
I don't understand because autoFormsAuthentication is set to false but authentication use it after.
What the enableSimpleMembership?
Thanks
It's hard to find any information on the topic but in my opinion autoFormsAuthentication set to true will set:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
If you need other parameter you need to use <authentication mode="Forms">
explicity.
Also autoFormsAuthentication redirecting unauthorized users from any contollers. Not only with 'authorize' attribute.
But it is just my opinion...

Dual forms authentication in asp.net 2.0 - 4.0

BACKGROUND
I have two websites under the same domain. One website encapsulates Login/Account Management functions only and the other website is the real website.
LoginWeb - only Login Page/css/images/javascript folder allow anonymous access
AdminWebsite - completely locked down via forms auth. i.e not even javascript/images/css folders have <authorization><allow users=*>
WHAT I AM TRYING TO ACHIEVE
This is the workflow I am trying to achieve and have accomplished 99% of it :
If the user hits any page on AdminWebsite he is sent back to LoginWeb by FormsAuthentication
User supplies credentials in the loginpage and LoginWeb website issues a forms auth ticket. User is still not logged into AdminWebSite yet. (This way user can go to changepassword page etc and do account management functions)
User goes to two more steps in LoginWeb and now can be issued the FormsAuth ticket for AdminWebsite and redirected to it.
99% IS ALREADY WORKING
This is the code in LoginWeb which tries to issue the FormsAuth ticket for AdminWeb, but it is not working. i.e AdminWeb is still redirecting me back to Login. I am sure there is something very trivial I am missing but I can't figure out what exactly it is?????????
public void SetAuthenticationTicket(string username)
{
MachineKeySection sec=(MachineKeySection)WebConfigurationManager.OpenWebConfiguration("").SectionGroups["system.web"].Sections["machineKey"];
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
false, //true or false
sec.DecryptionKey, //Custom data like your webkey can go here
FormsAuthentication.FormsCookiePath);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie("ADMINWEB", encryptedTicket)
{
Path = FormsAuthentication.FormsCookiePath,
Domain = "xxx.com"
};
Response.AppendCookie(cookie);
}
These are my web.config sections for Forms Auth:
LoginWeb
<machineKey validationKey="XXXXXX" decryptionKey="XXX" validation="SHA1"/>
<authentication mode="Forms">
<forms name="LoginWeb"
domain="xxx.com"
loginUrl="~/account/Logon"
timeout="1440"
cookieless="UseCookies"
slidingExpiration="false"
protection="All"
path="/"/>
</authentication>
AdminWebSite
<machineKey validationKey="XXXXXX" decryptionKey="XXX" validation="SHA1"/>
<authentication mode="Forms">
<forms name="ADMINWEB"
domain="xxx.com"
loginUrl="http://loginweb/account/Logon"
timeout="1440"
cookieless="UseCookies"
slidingExpiration="false"
protection="All"
path="/"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
This site, Forms Authentication Across Applications, implies that the Name on the forms attribute should be the same.

Categories