Page.User.Identity.Name is blank on pages of subdomains - c#

I have multiple subdomains trying to use a single subdomain for authentiction using forms authentication all running on windows server 2008 r2.
All of the forms authentication pages are setup to use the same name, and on the authentication page the cookie is added with the following snippet:
FormsAuthentication.SetAuthCookie(txtUserName.Text, false);
System.Web.HttpCookie MyCookie = System.Web.Security.FormsAuthentication.GetAuthCookie(User.Identity.Name.ToString(), false);
MyCookie.Domain = ConfigurationManager.AppSettings["domainName"];
Response.AppendCookie(MyCookie);
When I am logged in to signon.mysite.com the page.user.identity.isauthenticated and page.user.identity.name properties both work fine. When I navigate to subdomain.mysite.com the page.user.identity.isauthenticated returns true, bue the name is empty.
I tried to retrieve it from the cookie using the following, but it also was blank.
HttpCookie cookie = Request.Cookies[".ASPXAUTH"];
FormsAuthenticationTicket fat = FormsAuthentication.Decrypt(cookie.Value);
user2_lbl.Text = fat.Name;
When googling the issue I found some people saying something must be added to global.asax and other saying it wasn't necessary.
The goal is to be able to login on the authentication subdomain and have the user identity accessible from the root site and other subdomains. Machine keys match in all web.config, and the AppSettings["domainName"] is set to "mysite.com" currently.
Does anyone know what is preventing me from accessing the user information?

Change "mysite.com" to be ".mysite.com" (note the leading ".").
That'll tell the browser that the cookie is valid for subdomains as well.

Related

ASP.Net MVC - OWIN - Allowing Windows/Individual Authentication

I have an ASP.Net MVC 5 application which is currently using individual authentication (account/login.cshtml page with no authentication/anonymous access) and OWIN. Works fine.
As this is an intranet app I want to allow the users to log in under their windows account, another users windows account or an application account(admin, special user etc. - these accounts have no associated domain account).
For the first option I wanted to display their windows username on the login screen and they can simply click the "ok" button to login. To get the username I modified the Visual Studio Project properties to disable anonymous authentication and enable windows authentication. Also modified the web.config and set the authentication mode to Forms. This causes "HTTP Error 404.15 - Not Found". This appears to be due to an authentication loop caused by OWIN with the following suggestions to fix:
Ensure Login controller methods allow anonymous access (seems to be this way by default).
or Modify Startup.auth, comment out the LoginPath property.
or Modify the web.config, add the appSetting "owin:AutomaticAppStartup" with value "false".
I opted for the LoginPath fix and this appears to work (as does web.config change) in that there are no errors and the login page displays with the windows username (retrieved using System.Threading.Thread.Currentprinciple.Identity.Name).
The problem is now that once the user has logged in the OwinContext has no user ( HttpContext.GetOwinContext().GetUserManager()).
Ideally I don't need IIS or OWIN doing any authentication as it's done by the app - but I need the initial request (for the account/login page) to include the Authenticate headers so I can get the windows user.
Firstly I would like to understand what causes the "HTTP Error 404.15" and fix.
Secondly, how do I get OWIN to work with the authentication change - I just need it to persist the user for controller authentication.
This is just a guess but I believe the error is caused by the misconfiguration you've described: you have set the authentication mode to "Forms" but set the project to use Windows Authentication. It can be confusing but Windows Authentication is not Forms Authentication. When you are using Forms Authentication the user provides the credentials in the form that is submitted, validated (including all anti-forgery goodness) against the user store (I believe you are using ASP.NET Identity which would be a default for "Individual Authentication" setting) and if the validation is successful a cookie to set is included in the response. This cookie is then used to authenticate further requests.
As confirmed by Katana documentation, there is no built-in middleware for Windows Authentication - Microsoft simply assumes that IIS should be used for that. Which effectively prevents us from easily combining Katana OWIN middleware providers with Windows authentication. Now, easily is the key word: we still can "hack" our way around it.
Unfortunately, it still will be a hack: I have not found a way to make the authentication "transparent" (as in "a user opens the login form and can enter both the AD account credentials or the individual account credentials and everything just works"). You will need to maintain the individual account record for every Windows user (as you would do with any external OWIN middleware, such as Google or Facebook). You can automate the account creation and association though and make it look transparent. You can add an "external provider" button for your Windows authentication.
Authenticating the user would look like (in a separate "AD Authentication" controller):
bool userWindowsAuthentication = Request.LogonUserIdentity.IsAuthenticated;
if (userWindowsAuthentication) {
var userStoreDatabaseContext = new ApplicationDbContext();
var userStore = new UserStore<UserModel>(userStoreDatabaseContext);
var userStoreManager = new UserManager<UserModel>(userStore);
var userWindowsLoginCredentials = GetWindowsLoginInfo();
var existingInternalUser = userStoreManager.FindAsync(userWindowsLoginCredentials.UserName)
if (existingInternalUser) {
// It means that the user already exists in the internal provider and here you simply authenticate and redirect to destination
} else {
// It means that the user does not exist. You can automatically create the internal user record here and associate the Windows user with the internal record.
}
} else {
// It means that user is not signed in using Windows authentication, so you either want to redirect back to the login page or restrict access or do something else
}
As you can see, it's "dirty". Another hack: you can have additional layer (separate application or a virtual application) that accepts only Windows authentication. This app can be your log-in resource. If the user is authenticated with Windows AD you can redirect them to the correct login page. You can go even further and add their login info in the redirect request header but if you do so - the header must be encrypted to ensure that Windows authentication cannot be faked and the only thing that should be able to decrypt and validate it should be your main application. Again, dirty, but works.

How to Get sharepoint Application Sign In Page URL Programmatically

In SharePoint Application When Claims Based Authentication types are enabled, a URL for redirecting the user to the Sign In page is required.
I want to get that Which Login Page is set Either default or Custom and if it is custom i want to get the 'Custom Sign in Page' URL programmatically.
Read this, explains how it works:
"http://blog.octavie.nl/index.php/2012/06/11/custom-sign-in-and-sign-out-page/"
You do not have to provide a URL if using Windows Authentication in claims mode. The default login page is _login/default.aspx If a custom login page is used, it will be listed in central admin.
A URL for redirecting the user to the Sign In page is required only when using a trusted identity provider. In that case you can get the login page by setting the identity provider to a variable ex. $TIP = Get-SPTrustedIdentityTokenIssuer "YourTrustedIdentityProviderName" then running $TIP.ProviderUri
That will show the host that is being redirected to for login.
I know it's been a long time this post was answered but I was looking up how to get the custom sign in page Url programatically. This is not very documented so here's what I've found:
Get a SPWebApplication object (in my case I used an SPSite.WebApplication property.)
Find the WebApplication IisSetting that has FormsClaimsAuthentication
Get the Claims Authentication Login Redirection Url
Here:
using (SPSite site = new SPSite("http://mysiteurl")
{
foreach(KeyValuePair<SPUrlZone, SPIisSettings> zone in site.WebApplication.IisSettings)
{
if(zone.Value.FormsClaimsAuthenticationProvider != null)
{
string customSignInPageUrl = zone.Value.ClaimsAuthenticationRedirectionUrl;
}
}
}
This gave my the relative path to the custom Sign In page I've set in my central admin.
In my case I was coding my own FBA management solution and I wanted the admin to be able to go see the login page even when already logged in.

ASP.NET Site Authentication Cookie sharing

I've got 2 MVC3 Internet websites. One (Site1) uses Windows authentication and is in the Local Intranet Zone. The second (Site2) is publicly available and uses Forms Authentication. Both sites are in the same Domain, but have a different sub-domain. I want to share authentication cookies between the two. In order to do this, they need identical settings in the web config. Sometimes this works, most of the time it doesn't. If anyone hits Site1 from outside our network, they get a 403 error, which is good. If a network user hits Site1, they're allowed in based on their network credentials. I then check their user's roles with the code below.
var userName = string.Empty;
var winId = (WindowsIdentity)HttpContext.User.Identity;
var winPrincipal = new WindowsPrincipal(winId);
if(winPrincipal.IsInRole("SiteAdmin")) {
FormsAuthentication.SetAuthCookie("siteadmin", false);
userName = "siteadmin"; //This is a Forms Auth user
}
else if(///I check for other roles here and assign like above)
Once I've checked the roles, I forward them onto Site2, creating a cookie for them if the user is in one of the roles determined in the if...statement above.
if(!string.IsNullOrEmpty(userName)) {
//Add a cookie that Site2 will use for Authentication
var cookie = FormsAuthentication.GetAuthCookie(userName, false);
cookie.Domain = FormsAuthentication.CookieDomain; //This may need to be changed to actually set the Domain to the Domain of the TVAP site.
HttpContext.Response.Cookies.Add(cookie);
}
//Network users not found in roles will simply be forwarded without a cookie and have to login
HttpContext.Response.RedirectPermanent(tvapUrl);
I've set up in the web.config a matching MachineKey (validationkey, decryptionkey and validation) for each site.
They also both have the same authentiation settings, with the exception of the mode. So my config for this looks like this.
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" name=".ASPXFORMSAUTH" protection="All" path="/" domain="mydomain.com" enableCrossAppRedirects="true" timeout="2880" />
</authentication>
I think my problem is that the 'authentication' mode is different for each one, so Site2 won't use the authentication cookie from site1. This is just a guess though. Is there anyway I can figure out the issue?
According to this article, what I have going here should work. And there have been times where I think it's worked, but it's hard to tell, as I may have cookies cached and their getting reused. I'm hoping someone can see something I'm missing here, or has an alternative solution.
UPDATE
I checked my authentication cookie on Site2 after logging in normally and found the Domain wasn't set, so I've removed that line of code.
Also, I read about cookies expiring when the date isn't set, so I set an Expire Date on my cookie before sending with the request.
So, with those two changes, here's where I'm at.
It works on Chrome and Firefox, but not with IE. Not sure. I'm going to do some additional testing from another machine and another user so I know I haven't got any residual cookies sitting around.
I determined my problem was not setting the Expires property of my cookie. According this Microsoft article, cookies won't be written to the client unless the Expires property is set.
"If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded. A non-persistent cookie like this is useful for information that needs to be stored for only a short time or that for security reasons should not be written to disk on the client computer. For example, non-persistent cookies are useful if the user is working on a public computer, where you do not want to write the cookie to disk."
In this case, I needed the cookie to be written to disk since I was doing a server transfer to another site, thereby ending the session for that user. I'm not 100% sure that this was the fix, but it is working now, so I'm assuming that.

Browser occasionally losing HttpCookie for authentication after postback and redirect

This has been a nagging issue for some time, but very sporadic and difficult to isolate.
From time to time, browsers that have authenticated on a web application, have been open for a while, have logged in and out of the same web application multiple times, have multiple tabs, are pretty much any browser (Chrome, IE, Firefox, Safari), and seemingly at random, lose their ability to retain an AuthCookie after being set and followed by a redirect. Closing the browser and starting a new session resolves the issue, as does opening up a different browser and attempting to authenticate.
Our team uses forms authentication for all of our websites and web application. This is a pretty typical setup where a login form is displayed, the user enters credentials and a cookie is set on the click event of the postback, then a redirect occurs to the same page where the cookie is then referenced and used to complete authentication.
In this situation
FormsAuthentication.FormsCookieName = ".WebAuth"
Within Event:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, Username, DateTime.Now, DateTime.Now.AddMinutes(SessionTimeout), false, Username);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(faCookie);
Response.Redirect(Request.RawUrl, true);
After the redirect, on PreInit:
HttpCookie authCookie = Request.Cookies[cookieName];
At this point, the authCookie variable is typically not null, but in these isolated circumstances that I've outlined above, the cookie comes back null after the redirect.
This happens very randomly, sometimes weeks before affecting one of our developers. As I said, restarting the browser resolves the issue.
Today I had it happen on our dev server while using Chrome. I had logged into the application, allowed the application to session timeout, and then attempted to login again. The attempted login then failed to set the cookie. I remotely attached Visual Studio to the process on the server to begin debugging. The entire time I could step through my code, even deploy new code versions to the server with updates, restart the app, restart IIS on the server, attach and reattach to the project, and the issue persisted in Chrome. In Firefox, I was able to authenticate without issue.
From Chrome, the login would validate, attempt to set a Response Cookie as outlined above. Prior to redirect, I could see the properly set Response Cookie, as well as its counterpart in the Request Cookies. However, on each redirect after a seemingly successful login, the Response and Request Cookie are gone.
I enabled Trace on the application to view the cookie collection:
There is a .WebAuth in the Request Cookies Collection, as well as ASP.NET_SessionId and several ASPSESSIONIDxxxxxxxx, but when the page loads, only the ASP.NET_SessionId and ASPSESSIONIDxxxxxxxx cookies are available in the Request.Cookies scope, no sign of the .WebAuth. However, in the page's Trace information after render, there multiple .WebAuth cookies listed, it is just that the page seems to have no access to them.
Primarily, on a working version after authentication there is both a .WebAuth Response and Request Cookie in the page's Trace info. But on a non functioning browser window, the Response Cookie is absent.
Has anyone else had any experience with this? It is such a nagging issue, and so sporadic, but I would love to be able to resolve it. My concern is that it may be affecting users and we would have no knowledge since the description of the issue is so convoluted.
Based on your scenario you may be running into browser's restrictions on number of cookies per domain/total. The limits are relatively high, but exist (spec: http://www.ietf.org/rfc/rfc2109.txt, section 6.3 , some recent information - http://www.nczonline.net/blog/2008/05/17/browser-cookie-restrictions/)
If you get it happening again try to look at actual server responses (i.e. using Fiddler) to see if cookies are send to the browser. Check what cookies are set for the domain and current page (depending on browser there are different ways of doing it, in all browsers you can see some cookies by running following in address bar javascript:alert(document.cookie) )
This is a non-persistent cookie issue. Session simply times out.
Try changing false to true in this line:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, Username, DateTime.Now, DateTime.Now.AddMinutes(SessionTimeout), true, Username);
Also add
faCookie.Expires = DateTime.Now.AddMinutes(SessionTimeout);
I have fall in similar situation, things was certain as you described. But, later the reason have been found.
ASP.NET and IIS understood MyApplication and myapplication as one equal, but browsers undertood them as different. So, when we set auth cookies for /MyApplication, they were not sent to the server, when we go to /myapplication.
The fix is next:
protected void Application_BeginRequest(object sender, EventArgs e)
{
string url = HttpContext.Current.Request.Url.PathAndQuery;
string application = HttpContext.Current.Request.ApplicationPath;
if (!url.StartsWith(application))
{
HttpContext.Current.Response.Redirect(application + url.Substring(application.Length));
Response.End();
return;
}
}

FormsAuthentication Membership.GetUser() Null

I am using Forms Authentication and have the basic logon page and default page.
When I am on the logon page, and call the SignOn this works just great. However, when I am still on the Logon page the Membership.GetUser() returns null. When I redirect to my default page, the Membership.GetUser() returns my user information.
Is there any way I get get this method to return my user while still on the logon page. I have read all over google that other have similar issues where it will only work once you redirect.
Let me know if you need further information.
Here is a simple code snippet of what I am using to verify that the information is being set:
bool authenticated = User.Identity.IsAuthenticated;
string username = User.Identity.Name;
MembershipUser user = Membership.GetUser();
I put this code on both the logon page and the default page in the code behind and only the default page has values and shows that it is authenticated after the authentication process executes.
Something else to try is the following code:
MembershipUser user = Membership.GetUser(username);
GenericIdentity identity = new GenericIdentity(user.UserName);
RolePrincipal principal = new RolePrincipal(identity);
System.Threading.Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
This might be because you allow anonymous users on your login page. Therefore the browser doesn't bother sending any more information to this page than is necessary.
I was in this same situation, here is what worked for me on MVC 4 .NET 4.5.
Membership.GetUser(HttpContext.Current.User.Identity.Name)
I had a similar issue and the problem turned out to be that I was missing authentication method = form in the web config .
<system.web>
<authentication mode="Forms"/>
....
Don't forget that one (I was migrating an old legacy site to aspnet)
I had this issue and found it was due to having multiple membership providers, so instead of
Membership.GetUser()
you can try
Membership.Providers["MyMembershipProvider"].GetUser()
or more specifically
Membership.Providers["MyMembershipProvider"].GetUser(LoginCtrl.UserName, false)
I had a similar problem (it was all pages on the site) and it was caused by an error in the AspNetSqlMembershipProvider connection string, which SHOULD have been different in different environments but wasn't, so it worked locally but not when deployed to the server.

Categories