ASP.NET MVC - cross sub domain authentication/membership - c#

Hit a roadblock while implementing a sub domain based language switcher (en.domain.com loads English, jp.domain.com loads Japanese).
How do I get a single membership system to work across multiple sub domains (ASP.NET MVC C#)?
Saw something about adding domain="domain.com" to <forms > entry in web.config. Did that, but does that work when testing on local visual studio development web server?

Try creating the cookie yourself.
In AccountController you'll find this:
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
that "creates and adds to the cookie collection". It doesn't allow modification of the domain (but does allow modification of the path, oddly). Instead create a cookie without adding to the collection, modify the necessary properties, then add to the collection:
var a = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie);
//if you're debugging right here, a.Domain should be en.example.com; change it
a.Domain = "example.com";
HttpContext.Current.Response.Cookies.Add(a);
James

You have to use dot prefix, like this.
<authentication mode="Forms">
<forms domain=".tv.loc" loginUrl="~/signin" timeout="2880" name="auth" />
</authentication>

Your problem is how browsers sends cookie during request.
Cookie is generally tied to a single domain, this is for security reasons and performance. For example, user don't want to send cookie for your domain to any other domain, because your cookie may contain sensitive information.
Browser do differentiate between cookies set with en.domain.com and jp.domain.com. They do not allow cookies from one domain goes to the other because they are not on a parent domain.
The solution to your problem would be to take over the control of generating cookies. I haven't played much with ASP.NET MVC, but I'm sure it can be done not through the HTML but through a property or something. This is a very common scenario. You should set the cookies domain to "domain.com" for your production boxes, that is correct. If you're working on a local box, you should set the cookies domain to "".

Related

Azure Cloud Service Losing Session if URL doesn't contain WWW

My Azure cloud service app has users logged in with session data. If they click on a link internally that doesn't have a preceding www, then the session data is not applied. If they go back and click on a link that does have a preceding www, the session data works as expected. Does anyone know how to resolve this?
TIA
Sounds like your session cookies are not tuned to the wildcard of the domain. Can this be a problem? Check the forms section of your web.config if it contains domain attribute and if it doesn't, set it.
<authentication mode="Forms">
<forms loginUrl="/Account/LogOn" timeout="43200" domain="yourdomain.com"/>
</authentication>

I want to mod how IE generates cookies

There are two different websites that people use, let's call them A and B. Now, as far as login page goes, A and B are nearly identical in design, but the user account logins for A and B are stored in separate datatables and information is different. When someone logs into A, IE will store their info in a cookie and will call it when going on B, even though they are not the same. Nowhere in the login web forms can I find code for generating the cookie, so I am assuming that everything is done within IE. I found the file 'index.dat' that supposedly stores all of IE's cookies in each user's AppData folder, but I do not know how to access it, let alone change the way IE stores the cookies.
My goal is for IE to have distinct cookies for A and B.
Place the sites on different domains. If the sites share a domain, they will see each other's cookies. You can't change this. It's how cookies work.
So I suppose you want to change default asp.net forms authentication cookie names to something else.
Something like this in web.config:
<authentication mode="Forms">
<forms name="myCustomCookieForApp1" ... />
</authentication>
You can read up here:
http://msdn.microsoft.com/en-us/library/ff647070.aspx
The only way IE will send the cookie for A to B is if they are on the same domain and you haven't configured the login mechanism to limit the cookie to your subdomain.
See sub-domain cookies, sent in a parent domain request?

After logout the user should not be able to re enter into the site by typing the url of the internal pages in the address bar

i m relatively new to C# and ASP.NET and I am having trouble designing an authentication system.
I have created a website where the user has to login, after which he can access various pages in this site. When the user clicks a logout link, he returns to the login page and is given the message "you have successfully logout." Now how do I prevent the user from typing the URL of one of the internal pages, bypassing my authentication? While working with PHP, I used session_start() and ob_end_flush() at the beginning and the end of each page to control authentication. What is a similar model in ASP.NET?
Also how do I include a .cs file from app_code folder to a aspx.cs?
If you are using FormsAuthentication, this is simple to do using configuration in web.config.
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="default.aspx" protection="All" path="/" slidingExpiration="true" timeout="60" />
</authentication>
This configuration forces aspx to ensure that all pages in the site can only be accessed by authorized users.
However, there is a logic problem with this configuration: no one would ever be able to login since they must be authorized to access any page in the site.
You can fix this, however, by opening "holes" in this protected by adding specific pages and indicating they can be authorized by anyone:
<location path="default.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
Now how do i prevent re entry into the site by typing the url of the internal pages in the address bar.
How are you actually tracking the authentication? Forms authentication? Windows authentication? Something custom? Essentially, what you need to do is have those pages check for a valid authentication token. If no such token exists, redirect to the login page or an error or something to that effect.
You can do this by checking for authentication manually in the Page_Init method (which can access Session data, Cookies data, etc. where you'd store such a token), you can use various methods built-in, etc.
The concept is the same as it was in PHP, the tooling is just a little different.
While working with PHP i used session_start() and ob_end_flush() at the beginning and the end of each page.....What is it im supposed to use in c#?
You don't need to explicitly start/end session state in ASP.NET. Any code in the scope of the web application can access session state/values via System.Web.HttpContext.Current.Session. Any request coming from the same session will have this data associated with it.
Also how do i include .cs file from app_code folder to a aspx.cs
While in PHP you had to include files, in ASP.NET it's compiled code so the file isn't so important. What you need to reference is the namespace/class to use the code. For example...
If you have the following in a file in App_Code:
namespace MyApplicationCode
{
public class SomeCode
{
// stuff in the class
}
}
Then from any code within the application you should be able to use it by it's fully-qualified name (MyApplicationCode.SomeCode):
var someVariable = new MyApplicationCode.SomeCode();
Additionally, you can add a using statement in the header of the code file:
using MyApplicationCode;
And then access it directly:
var someVariable = new SomeCode();
When a user is successfully authenticated with his credentials, a cookie is set with a session id that corresponds to a file that stores value on the server. This cookie confirms to the server that the user is authenticated.
Check how your system handles sessions, it can be done without a session cookie, too:
(pseudo-code)
if (User.Login(formUsername, formPassword)) {
SetCookie ("LoggedIn", 1, Time() + 3600);
}
Now, whicever page needs a logged in user to be viewed, you just check if the user has the cookie set:
(pseudo-code)
if (CookieIsSet("LoggedIn")) {
// this page can be viewed
}
else {
Redirect ("/notAuthorized");
}
When you log the user out, you can delete the cookie by setting the expiration date in the past:
(pseudo-code)
SetCookie ("LoggedIn", 1, Time() - 3600);
Now, the user cannot view the internal page as the check (CookieIsSet(...)) will fail. Now, functions, methods and all the details depend on the system, but it always works like this:
if credentials are ok, set a cookie
whenever an internal page is visited, check if cookie is set
when logging out, delete the cookie
Hope this helps.
To check if the user typed in the address bar I would simply check the UrlReferer in page load of protected pages, other aspects should be controlled by web security and state management
if (Request.UrlReferrer == null)
Response.Redirect("errorpage.aspx");

Share session between domain and sub-domain

We're doing a whitelabelled version of our site, which will be hosted at foo.ourdomain.com.
However we need to ensure session is maintained between www.ourdomain.com and foo.ourdomain.com, as our SSL certificate only covers the main domain.
In practice this means we'll swap to the main domain on our payment pages, which run HTTPS, and then redirect back to the subdomain, after payment.
So the question is: How do we maintain the session when doing so ?
I've tried with <httpCookies domain=".ourdomain.com" /> in web.config to no avail :-(
Edit: Figured it out now, I lacked domain on my <forms /> tag to handle login properly.
Like I mentioned in my edit, I just lacked the domain attribute on my tag in web.config.

Forms Authentication across Sub-Domains

Is it possible to authenticate users across sub-domains when the authentication takes place at a sub-domain instead of the parent domain?
For example:
User logs into site1.parent.com, and then we need to send them to reporting.parent.com.
Can I authenticate them to the reporting site even though the log-in occured at a sub-domain?
So far all of the research I have done has users logging into the parent domain first and then each sub-domain has access to the authentication cookie.
When you authenticate the user, set the authentication cookie's domain to the second-level domain, i.e. parent.com. Each sub-domain will receive the parent domain's cookies on request, so authentication over each is possible since you will have a shared authentication cookie to work with.
Authentication code:
System.Web.HttpCookie authcookie = System.Web.Security.FormsAuthentication.GetAuthCookie(UserName, False);
authcookie.Domain = "parent.com";
HttpResponse.AppendCookie(authcookie);
HttpResponse.Redirect(System.Web.Security.FormsAuthentication.GetRedirectUrl(UserName,
False));
You can set the cookie to be the parent domain at authentication time but you have to explicitly set it, it will default to the full domain that you are on.
Once the auth cookie is correctly set to the parent domain, then all sub-domains should be able to read it.
As a side note, I found that after using jro's method which worked well +1, the FormsAuthenication.SignOut() method didn't work when called from a subdomain other than www/. (I'm guessing because the .Domain property doesn't match) - To get around this I used:
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
myCookie.Domain = "parent.com";
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
In addition to setting a cookie to parent domain also need to make sure that all sites (apps) have same validationKey and decryptionKey () so they all recognise each other's authentication ticket and cookie. Pretty good article here http://www.codeproject.com/KB/aspnet/SingleSignon.aspx
Jro's answer works fine. But make sure to update the webconfig forms authentication setting "domain"
, otherwise forms authentication signout will not work properly. Here is the signout issue I came across. Trick here is to have a '.' as the prefix as the domain is set for the cookie as ".parent.com" (use a cookie inspector).
<authentication mode="Forms">
<forms cookieless="UseCookies" defaultUrl="~/Default" loginUrl="~/user/signin" domain=".parent.com" name="FormAuthentication" path="/"/>
</authentication>
Yes, sure. You may need to roll your own at some stages, but it should be doable.
One idea: as you redirect them across the boundary, give them a one-time pass token and then tell the receiving sub-domain to expect them (this user, from this IP, with this token).
2 things to be done:
MachineKey should be same in all web.config (main domain and sub domain(s))
AuthenticationCookie domain name should be same.
Follow the following article for more depth.

Categories

Resources