Forms authentication for www and without www - asp.net

This is part of my config file
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" enableCrossAppRedirects="true"
name="authtoken" domain="localsite.com" />
</authentication>
This is my method for authentication
public void Authenticate(string token, int userId)
{
var userData = new FormTicketUserData() {UserId = userId};
var ticket = new FormsAuthenticationTicket(1, token, DateTime.Now, DateTime.MaxValue,
false, userData.ToString());
var encryptString = FormsAuthentication.Encrypt(ticket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptString);
authCookie.Path = FormsAuthentication.FormsCookiePath;
HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
HttpContext.Current.Response.Cookies.Add(authCookie);
HttpContext.Current.User = new MyFormsPrincipal(new FormsIdentity(ticket), userId);
UserContext.Refresh();
}
When I Authenticate on www.localsite.com,I don't Authenticate on localsite.com and vice versa.
When I Authenticate on www.localsite.com,I need be Authenticate on localsite.com too.
How can I do this.

This solved problem
authCookie.Domain = "localsite.com";

Related

How to set expiration date for ASP.NET_SessionId cookie?

Here's how I have authentication configured in web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/Sigin"
name="MYCAUTH"
timeout="3000" />
</authentication>
How can I make both MYCAUTH and ASP.NET_SessionId cookies use expiration?
Try this:
DateTime expireDate = DateTime.Now.AddDays(30);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, expireDate, true, string.Empty);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authenticationCookie.Expires = ticket.Expiration;
Response.Cookies.Add(authenticationCookie);
FormsAuthentication.SetAuthCookie(userName, true);
var myCookie = Request.Cookies["myCookie"];
if (myCookie != null)
{
HttpCookie respCookie = new HttpCookie("myCookie", "MyValue");
respCookie.Expires = DateTime.Now.AddMinutes(5);
Response.Cookies.Set(myCookie);
}

HttpContext.Current.User.Identity.Name is lost

I'm using ASP.NET forms authentication in my web application.recently i found a strange behavior. everything was working fine in production environment.with .net 4.0 and IIS 7.in the login user enter username and password and logged in then suddenly HttpContext.Current.User.Identity.Name is lost.this does not happen every time only in some occasions.i have unable to reproduce the issue in my development environment.i have checked if(HttpContext.Current.User.Identity.IsAuthenticated) it's also true authentication ticket user data is not empty also.only HttpContext.Current.User.Identity.Name is empty.plz help
code in Login button
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
dtUserDetails = new DataTable();
if (UserRepositoryBL.ValidateUser(txtUserName.Text.Trim(), Password.Text.Trim(), out dtUserDetails))
{
AuthUser au = new AuthUser();
if (dtUserDetails.Rows.Count > 0)
{
DataRow DR = dtUserDetails.Rows[0];
au.UserID = Convert.ToInt32(DR["UserID"].ToString());
au.UserNo = DR["UserNo"].ToString();
au.UserName = DR["UserName"].ToString();
au.Password = DR["Password"].ToString();
}
string userData = au.ToString();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
2, // Version number
txtUserName.Text.Trim(), // Username
DateTime.Now, // Issue date
DateTime.Now.AddMinutes(60), // Expiration date
false, // Persistent?
userData // User data
);
string eticket = FormsAuthentication.Encrypt(ticket);
if (Request.Cookies[txtUserName.Text] != null)
{
//HttpCookie myCookie = new HttpCookie(txtUserName.Text);
//myCookie.Expires = DateTime.Now.AddDays(-1d);
Request.Cookies[txtUserName.Text].Expires = DateTime.Now.AddDays(-1d);
Request.Cookies.Remove(txtUserName.Text);
}
HttpCookie cookie = new HttpCookie("SiteCookie", eticket);
// HttpCookie cookie = new HttpCookie("SiteCookie", eticket);
cookie.Expires = DateTime.Now.AddMinutes(60);
FormsAuthentication.SetAuthCookie(txtUserName.Text, false);
// cookie.Path = FormsAuthentication.FormsCookiePath;
FormsAuthentication.RenewTicketIfOld(ticket);
Response.Cookies.Add(cookie);
BasePage.ActivityLog("User Login", txtUserName.Text.Trim(), true, Request.RawUrl);
string url = FormsAuthentication.GetRedirectUrl(txtUserName.Text, false);
Response.Redirect(url);
// FormsAuthentication.RedirectFromLoginPage(LoginUser.UserName, false);
}
else
{
FailureText.Text = "Your login attempt was not successful. Please try again.";
}
}
catch (Exception ex)
{
throw ex;
}
}
web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="60" cookieless="UseCookies" defaultUrl="~/Landing.aspx" protection="All"/>
</authentication>
<authorization>
<deny users="?" />
</authorization>
Your session time is limited to 60 minutes. Does the problem only occur for people with an expired session? Might explain why you can't reproduce this on your development machine because you simply don't wait that long?

Forms authentication "Remember me" does not remembering me

I'm doing this:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.UserName,
DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
model.RememberMe, verification.UserId.ToString());
string hashedTicket = FormsAuthentication.Encrypt(ticket);
web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" defaultUrl="/" name="FunkyAuth" timeout="10000" />
</authentication>
and I check it like that:
protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
{
HttpCookie formsCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (formsCookie != null)
{
FormsAuthenticationTicket auth = FormsAuthentication.Decrypt(formsCookie.Value);
if (string.IsNullOrWhiteSpace(auth.UserData)) return;
int userId = int.Parse(auth.UserData);
var principal = new FunkyPrincipal(new GenericIdentity(auth.Name), userId);
Context.User = principal;
Thread.CurrentPrincipal = principal;
//Response.Cookies[FormsAuthentication.FormsCookieName] = formsCookie;
}
}
What am I doing wrong? Why it didn't persist it for long time?

User.Identity.IsAuthenticated returns false sometimes

Im using asp.net 4.0 and Form auth.
To check if a user is authenticated or not, i use User.Identity.IsAuthenticated.
Most of time it works perfect but i dont know how, sometimes it returns false even if user has auth.
My web.config:
<authentication mode="Forms">
<forms name=".xyz" loginUrl="~/" timeout="120" protection="All" path="/" slidingexpiration=true/>
</authentication>
In global.asax:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (authCookie == null)
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch
{
return;
}
if (authTicket == null)
{
return;
}
string[] roles = authTicket.UserData.Split(new char[] { '|' });
FormsIdentity id = new FormsIdentity(authTicket);
GenericPrincipal principal = new GenericPrincipal(id, roles);
Context.User = principal;
}
and in login page:
FormsAuthenticationTicket authTick = new FormsAuthenticationTicket(1, email.Text, DateTime.Now, DateTime.Now.AddDays(360), true, password.Text, FormsAuthentication.FormsCookiePath);
string encriptTicket = FormsAuthentication.Encrypt(authTick);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encriptTicket);
authCookie.Expires = DateTime.Now.AddDays(360);
Response.Cookies.Add(authCookie);
I also use ajax request in every 5 min. to keep session alive and this also reset auth timeout because slidingexpiration value.
I don't know what is wrong with it. sometimes same session and in same minute, it returns false for one page even if it returns true for all the other page. I never got this error but my visitors claim about that problem.
i found the problem. The problem was about difference between www.address.com and address.com.
www version pretend like a sub domain and creates new session and auth. If server redirects to www address when user came without www prefix, error happens. I will try url rewriting to solve it.

asp.net login control - set user auth ticket expiration date

I wanna to overide expiration date of user auth ticket on login.aspx.
This code doen't work properly, because after 1 minute user is still authenticated.
private int loginExpire = 1;
protected void Login_LoggedIn(object sender, EventArgs e)
{
HttpCookie authCookie = Response.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket oldAuthTicket = FormsAuthentication.Decrypt(authCookie.Value);
var newAuthTicket = new FormsAuthenticationTicket(
oldAuthTicket.Version,
oldAuthTicket.Name,
DateTime.Now,
DateTime.Now.Add
(TimeSpan.FromMinutes(loginExpire)),
oldAuthTicket.IsPersistent,
oldAuthTicket.UserData,
FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(newAuthTicket);
authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Current.Response.Cookies.Set(authCookie);
FormsAuthentication.RedirectFromLoginPage(GetDestinationPage(lgUserLogin.UserName), false);
}
web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" requireSSL="false" timeout="1" slidingExpiration="true" protection="All"/>
</authentication>
Edit the forms element for authentication section in web.config: set timeout="1" and slidingExpiration="false"
Or instead of RedirectFromLoginPage method use code below:
String returnUrl;
if (Request.QueryString["ReturnURL"] == null)
{
returnUrl = "/Default.aspx"; //your default page url
}
else
{
returnUrl = Request.QueryString["ReturnURL"];
}
Response.Redirect(returnUrl);

Resources