Forms Authentication Cookie is not setting? - c#

I am trying to use FormsAuthentication.RedirectFromLoginPage(username,true,cookiepath);
On using FormsAuthentication.RedirectFromLoginPage it's redirecting to the DefaultUrl provided in the web.config.
Authentication section in web.config:
<authentication mode="Forms">
<forms name=".ASPXADMINAUTH"
loginUrl="/Default.aspx"
defaultUrl="homepage.aspx"
protection="All"
timeout="30" path="/admin" slidingExpiration="true" enableCrossAppRedirects="false" cookieless="UseCookies" domain="localhost" ticketCompatibilityMode="Framework20" ></forms>
</authentication>
In httpModules Section:
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
The page is redirecting from the Loginpage to the "homepage.aspx" but it didn't set the Authentication cookie.
In my Response header, Set-Cookie contains the Authentication cookie, but it is not set in the homepage.aspx page.
So the LoginStaus and LoginName control is not working.

The problems in your code are path="/admin" domain="localhost"
According to your code
After user logins, a cookie is set under /admin. As the result, every pages under /admin folder knows that the user is authenticated such as ~/admin/default.aspx.
However ~/homepage.aspx does not know about user, because ~/homepage.aspx cannot read cookie written under /admin.
var path = FormsAuthentication.FormsCookiePath;
FormsAuthentication.RedirectFromLoginPage("win", false, path);
How to fix it?
You want to start slowly using simple one. Then tweak depending on what you need.
<forms loginUrl="~/Default.aspx" timeout="2880" defaultUrl="~/homepage.aspx" />
FYI: Please do not add properties which are default such as slidingExpiration="true",
enableCrossAppRedirects="false" and so on.

Related

ASPXAUTH cookie duplicated

Well I'm working on a WebApplication using FormsAuthentication.FormsCookieName. I have this in the WebConfig:
<httpCookies requireSSL="true" />
<authentication mode="Forms">
<forms cookieless="UseCookies"
name=".ASPXAUTH1" />
</authentication>
in code:
var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket))
{
HttpOnly = true,
Domain = "." +host, // Ex- host = google.com (without www because we use subdomains)
Secure = false
};
httpCookie.Expires = remember ? DateTime.Now.Add(FormsAuthentication.Timeout) : DateTime.Now.AddMinutes(1);
When I log in to the web app everything looks good:
the domain with the red arrow = .google.com
after a few seconds the second cookie appears with a different domain = www.google.com and Expires Date
I'm not using the RedirectToLoging Page Method.
this was solved adding slidingExpiration property in webconfig
<authentication mode="Forms" >
<forms cookieless="UseCookies" name=".ASPXAUTH" slidingExpiration="false" />

How to configure IIS Express properly so that it would allow anonymous login

I'm converting my current MVC application which uses windows based authentication to forms based. I have made changes in web.config and global.asax file. Now when I run the application, it goes to login page and with the user's credentials validated, its gets navigated to other page. My issue is when I do a signout, my applicationhost.config file gets rewrited from
<windowsAuthentication enabled="false" />
to
<windowsAuthentication enabled="true" />
and then if I hit the home page of my application, it takes my windows credentials.
In my web config I do have
<authentication mode="Forms">
<forms loginUrl="~/Logon/Index"></forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
In global.asax I have
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
string roles = string.Empty;
//Let us set the Pricipal with our user specific details
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
ISecurityUserIdentity objUser = null;
objUser = SecurityLibrary.Security.GetUser(username, Mgr.GetSecurityAttribute());
Context.User = objUser;
My issue is why my applicationhost.config file rewrites automatically when I do a signout and change my authentication mode.

SetAuthCookie does not set cookie on our test server

I am trying to setup my website on a new environment, and I have a problem with the membership provider.
I can call Membership.ValidateUser, which returns true and false, as it should. That is perfect.
However, on my new environment, the cookie is never set. I can see on localhost and our production server, that it sets a cookie called CommunityServer, but not on our new environment.
Web.config code:
<authentication mode="Forms">
<!-- development -->
<forms name=".CommunityServer" protection="All" timeout="60000" loginUrl="~/user/login" slidingExpiration="true"/>
<!-- deployment -->
<!--<forms name=".CommunityServer" domain="domain.com" protection="All" timeout="60000" loginUrl="~/user1.aspx" slidingExpiration="true" />-->
</authentication>
<authorization>
<allow users="?"/>
</authorization>
Log in code:
if (String.IsNullOrEmpty(UsernameLogin)) {
ModelState.AddModelError("UsernameLogin", Strings.Error_NoLoginUsernameEntered);
}
if (String.IsNullOrEmpty(PasswordLogin)) {
ModelState.AddModelError("PasswordLogin", Strings.Error_NoLoginPasswordEntered);
}
if (!Membership.ValidateUser(UsernameLogin, PasswordLogin)) {
ModelState.AddModelError("UsernameLogin", Strings.Error_LoginFailed);
}
if (!ModelState.IsValid) {
return View(new UserLoginModel() { Title = String.Format(Strings.Site_Title, Strings.UserLogin_Title) });
}
FormsAuthentication.SetAuthCookie(UsernameLogin, true);
// we know this code is run and I am being redirected to the return url
if (!String.IsNullOrEmpty(ReturnUrl)) {
return Redirect(ReturnUrl);
}
Any ideas of hints about why our cookie is never set? It is an IIS 8 server.
Add the domain="domain.com" on the parametre of authentication, to say to the cookie to be valid to the full domain, and to the correct domain, or else there is the possibility to not been able to be set.
<authentication mode="Forms">
<!-- development -->
<forms name=".CommunityServer" domain="domain.com" protection="All" timeout="60000" loginUrl="~/user/login" slidingExpiration="true"/>

How To Have Multiple Login Page Styles In ASP.Net

My site will have a few tools/sub-sites available for people to do different things. I have one common Login UserControl that will be used so I am not really duplicating much. But each of these sub-sites have their own MasterPage and thus styling. There is only one User table in the database and there are Roles for which sub-site you can get to. The Login UserControl will handle that.
Here is a simplized folder structure:
\Root
--> Images
--> Scripts
--> Styles
--> POHR
------> Login.aspx
------> PORHMasterPage
--> Beer
------> Login.aspx
------> BeerMasterPage
--> StatusUpdates
------> Login.aspx
------> StatusUpdatesMasterPage
Each of those Login Pages use the same Login UserControl which validates people and sets up a Cookie as see here:
public void LogUserIn(string EMailOrName, string Password) {
DS.User u = DS.Common.ValidateUser(EMailOrName, Password);
if (u != null) {
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
u.FirstName + " " + u.LastName,
DateTime.UtcNow,
DateTime.UtcNow.AddMinutes(30),
true,
string.Format("UserID={0}|SiteID={1}", u.ID, SiteID)
);
string eTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, eTicket);
Response.Cookies.Add(cookie);
string redirectUrl = FormsAuthentication.GetRedirectUrl(EMailOrName, true);
Response.Redirect(redirectUrl);
} // if they got authenticated
} // LogUserIn - Method
My issue is the FormsAuthentication.GetRedirectUrl. It is returning /default.aspx. I tried adding the following to the Web.config
<location path="~/StatusUpdates">
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/StatusUpdates/Login.aspx" defaultUrl="~/StatusUpdates/Dashboard.aspx" timeout="30" slidingExpiration="false" name="MGG_StatusUpdates" />
</authentication>
</system.web>
</location>
<location path="~/Beer">
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Beer/Login.aspx" defaultUrl="~/Beer/Dashboard.aspx" timeout="30" slidingExpiration="false" name="MGG_Beer" />
</authentication>
</system.web>
</location>
I would expect a page the above defaultUrl values to be passed back based on where I am in the application.
My questions are... How can I get this to do what I want? Do I need Web.config files in each of those folders, if so, what should they hold as well as what should the root's web.config file have.

Issues with custom ASP.NET RoleProvider

I am having difficulties implementing a custom ASP.NET RoleProvider.
First off, let me show you the relevant settings in my web.config file:
<?xml version="1.0"?>
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
name="FormsAuthentication"
path="Default.aspx"
timeout="20"/>
</authentication>
<membership defaultProvider="MembershipProvider">
<providers>
<clear />
<add name="MembershipProvider"
type="CompanyName.Security.MembershipProvider" />
</providers>
</membership>
<roleManager defaultProvider="RoleProvider"
enabled="true">
<providers>
<clear />
<add name="RoleProvider"
type="CompanyName.Security.RoleProvider" />
</providers>
</roleManager>
</system.web>
<location path="Employees.aspx">
<system.web>
<authorization>
<deny users="?"/>
<allow roles="Employees"/>
</authorization>
</system.web>
</location>
</configuration>
Here's the code for the login button's event handler:
if (Membership.ValidateUser(tbxUsername.Text, tbxPassword.Text))
Response.Redirect("./Employees.aspx");
else
{
tbxUsername.Text = string.Empty;
tbxPassword.Text = string.Empty;
tbxUsername.Focus();
lblLogin.Visible = true;
}
Side Note based on FormsAuthentication.RedirectFromLoginPage() suggestion:
[It has been suggested that I use FormsAuthentication.RedirectFromLoginPage() instead of Response.Redirect(). Eventually, I'd like to redirect the user to a different page based on his/her role. I don't know how FormsAuthentication.RedirectFromLoginPage() would allow me to do this as it does not accept a redirection url as a parameter. In addition, it is my understanding that I could call FormsAuthentication.SetAuthCookie() prior to Response.Redirect() in order to create the authentication cookie that FormsAuthentication.RedirectFromLoginPage() creates. Please let me know if my thought process here is wrong.]
After stepping through the source, I can see that Membership.ValidateUser() is executing the ValidateUser() function of my custom MembershipProvider class. However, when a valid user logs in, and is redirected to Employees.aspx, the user is returned to Login.aspx**?ReturnUrl=%2fEmployees.aspx**. I assume that this is because although the user authenticates, s/he is failing authorization to the Employees.aspx resource.
With that assumption, I created breakpoints on every function in my custom RoleProvider class to see where things run amuck. Not one of them breaks execution when I debug. Most of the code in my RoleProvider throws NotYetImplementetExceptions, but I would still expect to hit the breakpoints (and would then implement those required functions). Here are two dumbed-down functions I have implemented:
public override string[] GetRolesForUser(string username)
{
return new string[1] {"Employees"};
}
public override bool IsUserInRole(string username, string roleName)
{
return true;
}
I assume that since the RoleProvider code never executes, that something must be wrong with my web.config.
I've searched for an answer to this for the past two days and have tried various changes without success. Does anyone see where I'm going wrong?
Thanks in advance!
After authenticating the user using Membership.ValidateUser, you should call FormsAuthentication.RedirectFromLoginPage rather than Response.Redirect to create the forms authentication ticket.
See the MSDN documentation for Membership.ValidateUser for an example.
EDIT
Or if you want to redirect to a specific page, call FormsAuthentication.SetAuthCookie to create the forms authentication ticket before calling Response.Redirect.
It redirects authenticated users to default.aspx
Actually it redirects back to the page that was originally requested, which is not necessarily default.aspx
EDIT 2
Also there is a problem with your configuration:
The path attribute should not point to a specific page (Default.aspx in your case), but the root directory of the site. The default is "/" because most browsers are case-sensitive and so won't send the cookie if there is a case mismatch.
<forms loginUrl="Login.aspx"
name="FormsAuthentication"
path="/"
timeout="20"/>
Check if user is in role:
If (Roles.IsUserInRole("Employees"))
{
}
or try if it works without role checking:
<allow users="*"/>
maybe helps configuration change:
<location path="Employees.aspx">
<system.web>
<authorization>
<allow roles="Employees"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
I changed the path value (see below) from "Default.aspx" to "/" and now the breakpoints in the custom RoleProvider are being hit!
Does not work:
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
name="FormsAuthentication"
path="Default.aspx"
timeout="20"/>
</authentication>
Works:
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
name="FormsAuthentication"
path="/"
timeout="20"/>
</authentication>

Categories

Resources