I want to host multiple sites under one domain. But currently I am working on localhost, so I added these 2 lines to my etc/hosts file:
127.0.0.1 something.com
127.0.0.1 orders.something.com
There are 2 applications hosted in IIS. One can be browsed using: orders.something.com/OrdersSSO and other can be browsed using something.com/SSOSample/.
I created authentication cookie using this code in something.com/SSOSample/:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
"abc",
DateTime.Now,
DateTime.Now.AddMinutes(30), // value of time out property
true, // Value of IsPersistent property
String.Empty,
FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
encryptedTicket);
Response.Cookies.Add(authCookie);
So I am logged in this application. However when I browse orders.something.com/OrdersSSO I don't get my authentication cookie.
This is my forms section in web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" enableCrossAppRedirects="true" timeout="2880" domain=".something.com" />
</authentication>
What am I missing?
Looks like your cookie doamin has not been correctly set.
Try something like this :
authCookie.Domain = ".something.com"
Note the "." in front of the domain name, that's what makes it work for any subdomain of something.com.
Related
So, I have two sites that can be accessed from the same link, based on a condition I shall call 'Condition' from my main site:
if (Condition) {
permission = true;
window.location.href = 'http://Site1?CID=' + CtxCID;
return;
Destination = "site1";
} else {
permission = true;
window.location.href = 'http://site2?CID=' + CtxCID;
return;
Destination = "site2";
}
These sites are on seperate servers. Site 1 is on a different server than site 2 and main site, which are both on the same server.
Site 1 and site 2 are largely identical: the difference is the database connection strings.
My main site uses an authentication cookie to ensure that the user stays logged in when you transfer over to site 2:
Private Sub AddAuthCookie(ByVal username As String)
FormsAuthentication.Initialize()
Dim expires As DateTime = DateTime.Now.AddDays(365)
Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(
1,
username,
DateTime.Now,
expires,
True,
"AUTHCOOKIE",
FormsAuthentication.FormsCookiePath)
Dim encryptedTicket = FormsAuthentication.Encrypt(ticket)
Dim authCookie As HttpCookie = New HttpCookie(
FormsAuthentication.FormsCookieName,
encryptedTicket)
authCookie.Expires = expires
Response.Cookies.Add(authCookie)
Authenticated_hidden.Value = "True"
End Sub
The authentication part of the connection string for my main site:
<authentication mode="Forms">
<forms name=".AUTH" loginUrl="~/Login.aspx" domain=".domain.com" enableCrossAppRedirects="true" requireSSL="false" />
</authentication>
The same this as above, except for my two child sites:
<authentication mode="Forms">
<forms name=".AUTH" loginUrl="http://mysite.mydomain.com/Login.aspx" domain=".mydomain.com" enableCrossAppRedirects="true" />
</authentication>
This works great when it passes to site 2, which again, is on the same server as main site. However, the cookie fails to keep me logged in when I go to site 1.
So, my question:
Does anyone with more experience with cookies than me have any idea what is going on here? Keep in mind that I inherited this site from someone else: the relationship between main site and site 2 was already established. I can provide more snippets of my code if needed. Just ask!
UPDATE: The machine keys are set to be fixed, and are identical across all three sites.
Pic of cookie panel:
I know this question has been asked before but each question has a different scenario to what I have or I am missing the obvious.
So I have implemented SSO architecture, so the user click on log in and redirected to identity server and log in there and get redirected back to the application.
in one of my application I want to use the HttpContext.Current.User.Identity.Name in my membershipprovider, but it is always empty. so I found out that I need create a cookie and set it up properly to get the HttpContext.Current.User.Identity.Name form wherever I want.
My code look like this:
After the user is redirected from the Identity server to a login control:
if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
HttpContext.Current.Session["username"].ToString(),
DateTime.Now, DateTime.Now.AddMinutes(30), true, String.Empty,
FormsAuthentication.FormsCookiePath);
string encryptedCookie = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedCookie);
cookie.Expires = DateTime.Now.AddMinutes(30);
Response.Cookies.Add(cookie);
FormsAuthentication.RedirectFromLoginPage("/my-profile", true);
}
My web config file looks like this:
<authentication mode="Forms">
<forms domain="http://localhost:8081" name="yourAuthCookie" loginUrl="login.aspx"
protection="All" path="/" />
</authentication>
<authorization>
<allow users="?" />
</authorization>
after the user is redirected to the my profile page the System.Web.HttpContext.Current.User.Identity.IsAuthenticated is true and the AuthinticationType = Cookies. but the Name is empty.
I am using asp.net webforms.
UPDATE: I have tried to set the HttpContext.Current.User it is set properly but when the page load or redirected it goes back to null empty.
if (ticket != null && !ticket.Expired)
{
var roles = ticket.UserData.Split(',');
System.Web.HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(ticket), roles);
}
any help will be much appreciated.
Your domain is wrong - in your app.config; <forms domain="http://localhost:8081" ... /> in this context domain has a meaning of domain into which the cookie is set. You can read more about domain of cookies here.
Domain is something like www.google.com or .google.com etc - it doesn't contain protocol prefix, it doesn't contain port and it makes no sense to use it for local hosts - so drop that attribute from your web.config for good.
Also (and this has nothing to do with your issue, it's just a friendly suggestion) - you don't have to construct forms auth ticket when all you care about is username. You can use just FormsAuthentication.SetAuthCookie instead.
I have a login system using FormsAuthentication that for some reason is logging me out when closing and opening the browser. Here is how I have setup my login code:
FormsAuthenticationTicket ticket;
ticket = new FormsAuthenticationTicket(1, tbUsername.Text, DateTime.Now, DateTime.Now.AddYears(1), true, string.Empty, FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
//Add the cookie to the request
Context.Response.Cookies.Add(cookie);
As you can see I have set the cookie to be persistent across sessions. Here is my web.config part:
<authentication mode="Forms">
<forms slidingExpiration="false" loginUrl="~/Login.aspx" name="BOIGAUTH" defaultUrl="~/Admin/Settings.aspx"/>
</authentication>
Also, SessionState is disabled on this particular application. Anyone know what is wrong?
Btw leaving the application browser on for more than 2 hours kept me logged in even though I did not interact with the website. The cookie is only being lost when closing the browser.
If you don't set expiration on cookie it will be browser-session-only cookie and disappear after you close all instances of browser.
You need to set some expiration on your cookie for it to be persistent with Expires property.
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
cookie.Expires = DateTime.Now.AddMinutes(1000);
Side note: make sure your browser is not configured to clear all cookies on close.
I have a login problem.
First i am using SSL while logging.
When i log in, i am creating a cookie like this. when i check if it is secure the answer is yes.
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, // version
UserName.Text, // user name
DateTime.Now, // creation
DateTime.Now.AddMinutes(60),// Expiration
false, // Persistent
role); // User data
// Now encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
// Create a cookie and add the encrypted ticket to the
// cookie as data.
HttpCookie authCookie =
new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
if (authCookie.Secure)
{
new GUIUtility().LogMessageToFile("The cookie is secure with SSL.");
// Add other required code here.
}
authCookie.Secure = FormsAuthentication.RequireSSL;
// Add the cookie to the outgoing cookies collection.
HttpContext.Current.Response.Cookies.Add(authCookie);
// Redirect the user to the originally requested page
Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text,false));
then this is redirected to the global.asax page which has this code:
string cookieName = FormsAuthentication.FormsCookieName.ToString();
HttpCookie authCookie = Context.Request.Cookies[cookieName];
try
{
new GUIUtility().LogMessageToFile(cookieName + authCookie.Secure);
}
catch (Exception)
{
//
}
here i get the cookieName as ".ASPXAUTH" and authCookie.Secure value as False.
Why is this happening i want the authCookie.Secure value to be true here.
Any suggestions?? thanks
my web config has this:
<authentication mode="Forms">
<forms loginUrl="Login.aspx" defaultUrl="~/Default.aspx" slidingExpiration="true" timeout="120" path="/" requireSSL="true" protection="All">
</forms>
</authentication>
<httpCookies requireSSL="true"/>
<authorization>
<deny users="?"/>
<!--<allow users="*"/>-->
</authorization>
Restrict the Authentication Cookie-to-HTTPS Connections
Cookies support a "secure" property that determines whether or not browsers should send the cookie back to the server. With the secure property set, the cookie is sent by the browser only to a secure page that is requested using an HTTPS URL.
If you are using .NET Framework version 1.1, set the secure property by using requireSSL="true" on the element as follows:
<forms loginUrl="Secure\Login.aspx"
requireSSL="true" . . . />
If you are using .NET Framework version 1.0, set the secure property manually in the Application_EndRequest event handler in Global.asax using the following code:
protected void Application_EndRequest(Object sender, EventArgs e)
{
string authCookie = FormsAuthentication.FormsCookieName;
foreach (string sCookie in Response.Cookies)
{
if (sCookie.Equals(authCookie))
{
// Set the cookie to be secure. Browsers will send the cookie
// only to pages requested with https
Response.Cookies[sCookie].Secure = true;
}
}
}
so according to me the first option is not working in web config so im doing it manually
which is the second option in the code..
Please suggest.
Are you redirecting on log-in to a non-SSL resource? If this is the case, then the cookie you created in the first piece of code shouldn't be used, because it's a secure cookie and hence only applicable to SSL connections (i.e. you explicitly said it shouldn't be sent to non-SSL requests, that's what .Secure does), and hence a new cookie would be created. I would expect it to also not include the ticket value.
In this case, you're going to want to either:
Keep with SSL from the point of being logged in.
Live with the risk of session stealing (there are further means of mitigating this risk).
Use an authentication protocol like Digest or NTLM that allows for challenge-response and for you to more rapidly expire the log-in without the user being pestered (because the browser does the second log-in for you).
I have a testproject and the forms timeout specified in web.config overrules the timeout which I set in FormsAuthenticationTicket. According the documentation, the timeout (expire date) in FormsAuthenticationTicket must override the timeout in web.config.
Documentation found on: http://support.microsoft.com/kb/910443
If the ticket is generated manually by using the FormsAuthenticationTicket class, the time-out can be set through the Expiration attribute. This value will override the timeout attribute value specified in configuration files.
Here is my code:
Web.config:
<authentication mode="Forms">
<forms
timeout="1"
loginUrl="login.aspx"
name="sessionTest"
cookieless="UseCookies"
defaultUrl="default.aspx"
/>
</authentication>
Login.aspc.cs:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(Login1.UserName, false, 2);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(cookie);
// redirect user
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, false);
Now, when I login, i get redirected after 1 minute of inactivity. This isn't supposed to happen, right? I have to be redirected after 2 minutes.
Someone can explain this?
I think the call to RedirectFromLoginPage is overwriting your cookie. You can try using this instead.
Response.Redirect( FormsAuthentication.GetRedirectUrl( UserName.Text, chkPersistCookie.Checked );
Additional information that might be useful here: https://web.archive.org/web/20210513002246/https://www.4guysfromrolla.com/webtech/110701-1.3.shtml