Where does User in MVC controller come from? - asp.net

I am working on a website that has multiple applications, one of them uses asp.net membership.
In another application I want to get the name of the current user, so I added the following to the web.config so I can get 'User.Identity.Name', note that both apps using same applicationName.
<membership defaultProvider="CustomProvider">
<providers>
<add name="CustomProvider" type="myNamespace.CustomProvider" applicationName="/appname" />
</providers>
</membership>
<machineKey validationKey="vv" decryptionKey="dd" validation="SHA1" decryption="Auto" />
What should I do to be able to get the current user identity in the second app?
Update:
the structure in the website as following:
the estore app is adding the forms cookie
I added same machine element in both config (estor config and bol config)
same authentication element:
<authentication mode="Forms">
<forms loginUrl="~/account/" slidingExpiration="true" timeout="10080" requireSSL="true" />
</authentication>
Update 2:
I tried to set the domain although it is not needed because all apps in the same domain but still not working, this is a snapshot for cookies with domain has been set:

Related

ASP.Net 4 Forms Authentication in IIS 7.5 - Default Document No Longer Working

I've recently migrated a web app from .Net 3.5 to .Net 4 and changed the app pool to Integrated mode in IIS 7.5. This app has 2 parts: the first is open to the public and the second is by login only. I use forms authentication for login which is configued thusly in the root web.config:
<authentication mode="Forms">
<forms loginUrl="~/private/login.aspx" protection="All" timeout="20" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="~/private/default.aspx" cookieless="UseCookies" enableCrossAppRedirects="true" />
</authentication>
In the root web.config I have the default authorization to to deny unauthenticated users, thusly:
<authorization>
<deny users="?" />
</authorization>
BUT I have the setting below configured in the root web.config to allow everyone to see the welcome page:
<location path="Default.aspx">
<system.web>
<authorization>
<allow users="?,*" />
</authorization>
</system.web>
This has been working great for years but now, if I don't explicily put Default.aspx in the URL, the forms redirect module causes the login page to be served. I've verified that I have my default pages configured correctly and they are enabled in IIS7. I have also tried specifying them in web.config. I have verified that the DefaultDocumentModule is sequenced before the DirectoryListing module.
If I remove the element the problems "goes away" but the effect would be to default to allow all users and this is completely undesireable.
I'm out of ideas. Suggestions?
Thanks
I
Seems like some kind of default doc issue. If you look in IIS Manager at the site, what is in the "Default Document" list. Is it possible that something other than Default.aspx is higher in the list? If something matching this is found in your root web, it will attempt to go there first and thus be redirected to login.
Are you explicitly setting the default document in your web.config? as in:
<defaultDocument enabled="true">
<files>
<clear />
<add value="Default.aspx" />
<add value="Default.htm" />
<add value="index.htm" />
<add value="index.html" />
<add value="iisstart.htm" />
</files>
</defaultDocument>
OK, I had a Microsoft Premier Support Engineer dig into this for me. We sat down together at my workstation and went through (a) the environment and app configuration and (b) possible solutions.
He referenced this MS "Fast Publish" article which suggests that I remove the ExtensionLessURL handlers from IIS via MMC. Well, we're a huge organization with servers out the wazoo and I could not guarantee that this change would always be honored so I didn't want to do that. We tried using web.config to remove them but that did not work.
So, I showed him this solution from another StackOverflow thread (posted by Dmitry.Alk) and he said it was a good work-around for now. It works great for this particular situation.
The Fast Publish article references this hotfix A update is available that enables certain IIS 7.0 or IIS 7.5 handlers to handle requests whose URLs do not end with a period which I've got to sell to our IT "department".
I don't call what I've written here an "answer" but I wanted to share what I've come to learn in case others happen upon this thread.

How can build a basic logon page using ASP.NET 4.0 using Active Directory?

I am trying to build a very basic website using ASP.NET to allow users access the private information by logging into the company Active Directory. Any help is really appreciated.
You will want to set up configuration in the web.config file to tell the ASP.Net app to use forms authentication:
<authentication mode="Forms">
<forms loginUrl="Login.aspx" cookieless="UseCookies" />
</authentication>
Then you will need to create a membership provider that will connect to AD for authentication. Fortunately Microsoft has provided an AD membership provider out of the box, so you can use that. If you set it as the defaultProvider, ASP.Net will automatically use it for authentication.
<membership defaultProvider="AspNetActiveDirectoryMembershipProvider">
<providers>
<add name="AspNetActiveDirectoryMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADConnectionString"
connectionUsername="<domainName>\administrator"
connectionPassword="password"/>
</providers>
</membership>
Finally, you will need to set up a connection string to connect to your domain controller:
<connectionStrings>
<add name="ADService" connectionString="LDAP://myCompany.com/DC=myCompany,DC=com"/>
</connectionStrings>
Look here for a good reference with more details.

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

We have an internal ASP.NET Webforms application running on a Windows 2008/IIS7 server which has been running fine until we installed MVC3.
Now any requests redirect to /Account/Login?ReturnUrl=%2f.
The website is Webforms not MVC. Because it is an internal only site we have Windows Authentication enabled for the root folder.
We have several other websites on the same server that have not been affected by this problem, but this is the only site where the root folder is set to Windows Authentication.
I solved the problem by adding the following lines to the AppSettings section of my web.config file:
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
I fixed it this way
Go to IIS
Select your Project
Click on "Authentication"
Click on "Anonymous Authentication" > Edit > select "Application
pool identity" instead of "Specific User".
Done.
Updated answer for MVC 4, heavily borrowed from this page and ASP.NET MVC issue with configuration of forms authentication section (and answered on both pages)
<appSettings>
...
<add key="PreserveLoginUrl" value="true" />
</appSettings>
...
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="43200" /> <!--43,200 in minutes - 30 days-->
</authentication>
Just remove
<authorization>
<deny users="?"/>
</authorization>
from your web.config file
that did for me
It's resolved the IIS request auto redirect to default page(default.aspx or login page)
By adding the following lines to the AppSettings section of my web.config file:
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
My solution was to add the tag
[AllowAnonymous]
over my GET request for the Register page. It was originally missing from the code I was mantaining!
A solve this adding in the option defaultURL the path my application
<forms loginUrl="/Users/Login" protection="All" timeout="2880" name="001WVCookie" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="/Home/Index" cookieless="UseCookies" enableCrossAppRedirects="false" />
We added some WCF SOAP related things to an existing IIS site and it caused this problem, with the site refusing to honour the web.config authentication redirect.
We tried the various fixes listed without success, and invented a work around of mapping the new weird URL back to the one we've been using for years:
<urlMappings enabled="true">
<add mappedUrl="~/loginout.aspx" url="~/Account/Login"/>
</urlMappings>
That worked but it's ugly. Eventually we traced it down to a web.config entry added by Visual Studio some time earlier:
<add key="webpages:Enabled" value="true" />
As we'd been unable to work out precisely what that does, we took it out, which solved the problem for us immediately.
Open web.config,then Change
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
To
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" timeout="2880" />
</authentication>
change to ~/Default.aspx
Be ware with this:
RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
}
After 4 hours, of trying everything... Windows 2008 R2 the files were green in Window Explorer. The files were marked for encryption and arching that came from the zip file. unchecking those options in the file property fixed the issue for me.
If nothing works then add authentication mode="Windows" in your system.web attribute in your Web.Config file. hope it will work for you.
Drezus - you solved it for me. Thanks so much.
In your AccountController, login should look like this:
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
Similar setup, identical problem. Some installations would work, but most would start redirecting (http 302) to /Account/Login?ReturnUrl=%2f after a successful login, even though we're not using Forms Authentication. In my case after trying everything else, the solution was to switch the Application Pool Managed Pipeline Mode from from Integrated to Classic, which cleared up the problem immediately.

ASP:Login Not Authenticating

I am currently learning form authentication using a SQLMembership provider. The ASP:Login control does not seem to authenticate. Here is the structure of my test site on my local machine:
~/LoginTest/
Default.aspx
CreateUser.aspx
lostpassword.aspx
web.config
/login/
Login.aspx
ProtectedStuff.aspx
web.config
In the web.config file of the LoginTest folder I have added the following nodes:
<connectionStrings>
<add name="EvgSqlConnection" connectionString="connection string" />
</connectionStrings>
<authentication mode="Forms">
<forms name="LoginTest" loginUrl="~/login/Login.aspx" path="/login"
cookieless="UseCookies" />
</authentication>
<membership defaultProvider="mySqlProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add
name="mySqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="EvgSqlConnection"
applicationName="LoginTest"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="true"
passwordFormat="Hashed" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="mySqlRoleProvider" cacheRolesInCookie="true" cookieProtection="All">
<providers>
<clear/>
<add name="mySqlRoleProvider" applicationName="LoginTest" connectionStringName="EvgSqlConnection"
type="System.Web.Security.SqlRoleProvider"/>
</providers>
</roleManager>
In the web.config in the login folder I have the following:
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
</system.web>
</configuration>
So what this is supposed to do from what I have read is deny users access to anything in the login folder. In this case my test file is ProtectedStuff.aspx which is nothing more than a page with a label. What is currently happening is that everything seems to work except the ASP:Login control. I can currently create a new user with the ASP:CreateUserWizard on CreateUser.aspx. I can recover a new password using the question and answer set up using the ASP:PasswordRecovery control on lostpassword.aspx. I can enter the correct name and password in the ASP:Login control on Login.aspx. The only thing that doesn't seem to work is the actual authentication. Whenever I try to go to ProtectedStuff.aspx it kicks me back to Login.aspx like it is supposed to when you are not authenticated. Further, I can enter the wrong user name or wrong password and the Login control complains. I can see my user in the website administration page, I can see that the user is assigned a role.
There is no custom code behind any of these controls, all I have done is copied in the SqlProvider name into the MembershipProvider attribute of these controls. SQL Server 2000 is configured with an NT AUTHORITY\Network Service user that has aspnet_Membership Full Access checked. the config files seem to be okay, all the controls seem to be able to read and write to the database correctly, only the Login control doesn't seem to authenticate the user. What else should I be looking for?
I'd start by removing the path attribute from your Forms element:
Specifies the path for cookies issued by the application. The default value is a slash (/), because most browsers are case-sensitive and will not send cookies back if there is a path case mismatch.
If that still fails, I'd get hold of Fiddler and see what cookies are being sent back to the client and to the server after logging in.

ASP.NET Membership - Which user is authenticated and which user is impersonated?

i'm a little confused while trying to find out how ActiveDirectory and ASP.NET Membership work... I've created a new MVC project and removed the AccountController / Views. I've changed the Web.Config so that it uses ActiveDirectory and automatically authenticates users based on their current Windows login:
Web.Config
<authentication mode="Windows">
<forms
name=".ADAuthCookie"
timeout="10" />
</authentication>
<membership defaultProvider="MyADMembershipProvider">
<providers>
<clear/>
<add
name="MyADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADConnectionString"
connectionUsername="MYDOMAIN\myuser"
connectionPassword="xxx"
/>
</providers>
</membership>
This works nicely, as I can do the following to get the users username like this:
User.Idenity.Name() 'Gives MYDOMAIN\myuser
Looking at the following, actually makes me confused:
Threading.Thread.CurrentPrincipal.Identity.Name() 'Gives MYDOMAIN\myuser
1. Shouldn't the thread identity be IUSR_WORKSTATION or ASPNET_WP username?
2. What's the difference between Authentication and Impersonation?
myuser is the Authenticated user on that application, that's why your CurrentPrincipal is giving you MYDOMAIN/myuser. The application impersonates IUSR_WORKSTATION when it uses resources like the database, and is a completely different issue.
If you go to Project on your toolbar, and select ASP.NET Configuration, it will open a website that lets you access these settings and create users, roles etc.

Resources