ASP.NET MVC issue with configuration of forms authentication section - asp.net

I have an ASP.NET MVC 3 Beta application running on IIS. In my web.config I defined following section responsible for forms authentication:
<authentication mode="Forms">
<forms
loginUrl="~/Account/LogOn"
name=".VNK"
protection="All"
timeout="43200"
cookieless="UseCookies" />
</authentication>
The defined login address is ~/Account/LogOn.
When I try to get the login url using:
FormsAuthentication.Initialize();
string loginUrl = FormsAuthentication.LoginUrl;
I receive: /VNK/site/Account/Login
Why do I get a different address from the one defined in web.config?
UPDATE: The "/VNK/site/" prefix is not a problem here. The problem is that LoginUrl property of FormsAuthentication class does not reflect the value from web.config. It means that if I change the value of loginUrl attribute in web.config from "~/Account/LogOn" to e.g. "~/foobar", FormsAuthentication.LoginUrl still has value of "/VNK/site/Account/Login". Why ?

I think there is a bug in ASP.NET MVC 3 Beta. This problem does not appear in previous releases of ASP.NET MVC.
If anyone wants to replay this error, he should follow this:
1.Download the mvc framevork.
2.Create new ASP.NET MVC 3 Web Application
3.Applay Authorize attribute on About action in HomeController
[Authorize]
public ActionResult About()
{
return View();
}
4.Start application and invoke About action by clicking on About tab. You will get server error, because application is trying to redirect You to such URL:
http://localhost:[port_num]/Account/Login?ReturnUrl=%2fHome%2fAbout
There is obviously no Login view. There is LogOn view. Url to LogOn action is defined in untouched web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
But application does not reflect that. Have anyone any clue what's going on ?
UPDATE:
I was right, there is a bug in MVC 3 Beta. From known issues:
"There’s a known issue that causes Forms Authentication to always redirect unauthenticated users to /Account/Login, ignoring the forms authentication setting used in Web.config. The workaround is to add the following app setting."
<add key="autoFormsAuthentication" value="false" />
UPDATE 2:
Alexander Prokofyev noticed, that ASP.NET 3 RTM looks for another setting. So you need this line instead:
<add key="loginUrl" value="~/LogOn" />

If you have access to IIS, then append a new application and enable ASP.NET "integrated pipelining" in application pool section by double clicking it.
If your hosting provider does not grant you access to IIS,
then login to the control panel.
Go to websites, under the management tab- enable ASP.NET integrated
pipe lining.
Set your application as a virtual directory
(It worked for me)

So the simple solution was to remove WebMatrix.*.dll from Bin folder in web project. I have done this for my asp.net project since it was redirecting my login to mvc style url.

Updated answer for MVC 4, heavily borrowed from this page and Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server
<appSettings>
...
<add key="PreserveLoginUrl" value="true" />
</appSettings>
...
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="43200" /> <!--43,200 in minutes - 30 days-->
</authentication>

Put the following in appSettings:
<add key="loginUrl" value="~/Account/LogOn" />
You could empty loginUrl from Form Authentication configuration.

I removed the following from my web.config
<remove name="FormsAuthentication" />
and then everything seemed to work. This text had been added by default when I created my project.

The tilde (~) means "the root of my web site" so you don't have to keep using .. or \ to step up and down the web site structure. However, from an IIS perspective you web application may have an additional layer of directory structure which is being reflected when you request the LoginUrl programmatically. I'm unsure as to why you want to retrieve the LoginUrl, the normal state of affairs would have IIS redirect the user to the LoginUrl automatically any time they try to access a page that they are not authenticated for.

I think the server has trouble deciding what ~ means in this case, try giving a more direct url to the login page, such as /Account/LogOn.
Maybe you'll find something useful here http://msdn.microsoft.com/en-us/library/xdt4thhy.aspx

Related

How To Pass UserIdentity/UserName From WebForm application to MVC5 Application?

I have a asp.net webform application (ProA). It was built some time ago by someone else, although I can access source code. Now, I finished another application which is a MVC5 (ProB).
ProA uses asp.net membership for authenticate users. ProB is not using any membership. Now, we want to add user authenticate to ProB, and also some parts of ProB is using username as parameter for some data.
Now, we want to force user login from ProA, then maybe click a link/button, redirect the user to ProB. In ProB, we create an authorize filter to verify the user has the right, then show the pages.
I have tried to use forms authentiction across applications, described in: Forms Authentication Across Applications . But it does not work. The changes I made in web.config is:
<authentication mode="Forms">
<forms name="X.ASPXAUTH" loginUrl="~/Login.aspx" path="/"
protection="All"
enableCrossAppRedirects="true"
/>
</authentication>
Could it be because that one is webform and the other is MVC? Also, ProB actually does not have any membership installed yet, does it affect this form authentiction?
Any other suggestions?
Thanks.
--- Added more info:
1) I'm testing on my local machine. I run both sites in VS2012. What should I use for domain? "localhost"? ".localhost"? or, not use domain at all? seems not working.
2) I added a button on ProA, when clicked, use this redirect to ProB:
HttpContext.Current.Response.Redirect("http://localhost:12345/", false);
Is this the correct way? The HttpContext has the user identity.
3) Does ProB have to have membership? Now, ProB does NOT have membership feature, is it the reason?
You shouldn't have any issues with sharing the authentication across web forms and MVC apps. The underlying technology is the same, .Net uses an encrypted to cookie which has the forms auth ticket.
Read the following MSDN article: https://msdn.microsoft.com/en-us/library/eb0zx8fc.aspx
The main things to note are the domain reference and the machineKey config.
The domain attribute of the forms auth config allows the browser to include that auth cookie with the requests sent to each site. Then the machineKey portion is the part that handles the encryption/decryption.
Both sites must have the config setup up identically for this to work, and also be running on the same domain i.e. xyz.contoso.com and abc.contoso.com
web.config
<configuration>
<system.web>
<authentication mode="Forms" >
<!-- The name, protection, and path attributes must match
exactly in each Web.config file. -->
<forms loginUrl="login.aspx"
name=".ASPXFORMSAUTH"
protection="All"
path="/"
domain="contoso.com"
timeout="30" />
</authentication>
<!-- Validation and decryption keys must exactly match and cannot
be set to "AutoGenerate". The validation and decryption
algorithms must also be the same. -->
<machineKey
validationKey="[your key here]"
decryptionKey="[your key here]"
validation="SHA1" />
</system.web>
</configuration>
EDIT
Use the following link to generate your machine keys: http://www.developerfusion.com/tools/generatemachinekey/

New Asp.Net MVC5 project produces an infinite loop to login page

I am creating a brand new projet with Visual Studio 2013, I choose Asp.Net MVC and the framework 4.5.1 The project is created, then, I do nothing else than F5 to start the default web page. Unfortunately, it produces a redirect to the login page which is redirecting into the login page too. Here is a short version of the url I have in the browser:
http://localhost:5285/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252FAccount%252FLogin%253FReturnUrl%253D%25252FAccount%25252FLogin%25253FReturnUrl%25253D%2525252FAccount%2525252FLogin%2525253FReturnUrl%2525253D%252525252FAccount%252525252FLogin%252525253FReturnUrl%252525253D%25252525252FAccount%25252525252FLogin%25252525253FReturnUrl%25252525253D%2525252525252FAccount%2525252525252FLogin%2525252525253FReturnUrl%2525252525253D%252525252525
I do not have any error in the Event Viewer. But in the screen I see :
"HTTP Error 404.15 - Not Found The request filtering module is
configured to deny a request where the query string is too long."
The website is running with the default setting in IIS Express. How can I fix this problem? I am guessing something is wrong with my Visual Studio 2013?
Edit
It works if I create a brand new website and I host it in IIS. But if I create a new website (without modifying anything) and just hit play (which start IIS Express by default), it doesn't.
Edit 2
I have deleted every websites in the Documents\IISExpress\config\applicationhost.config. I have recompiled everything, and it created this entry :
<siteDefaults>
<logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" />
<traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" />
</siteDefaults>
<applicationDefaults applicationPool="Clr4IntegratedAppPool" />
<virtualDirectoryDefaults allowSubDirConfig="true" />
</sites>
I am still getting the error with IIS Express, not with IIS.
Highlight the project in Visual Studio
Open the 'Properties' panel on the right (or press F4)
Set 'Windows Authentication' to 'Disabled'
Set 'Anonymous Authentication' to 'Enabled'
You are missing [AllowAnonymous] attribute on login action.
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
// code....
}
2nd possibility, specific to IIS Express only: is that, if you created same default WebApplication1 project multiple times, playing with different authentication settings, IIS Express stored additional authentication settings in it's configuration file. Something like:
<location path="WebApplication1">
<system.webServer>
<security>
<authentication>
<windowsAuthentication enabled="true" />
<anonymousAuthentication enabled="false" />
</authentication>
</security>
</system.webServer>
</location>
</configuration>
Configurations are in user's Documents folder Documents\IISExpress\config\, and you should look for:
applicationhost.config
Then just delete xml node <location path="WebApplication1"> mentioned above.
Update for VS 2015+
If you're using Visual Studio 2015 or higher, check this path for the config file:
$(solutionDir)\.vs\config\applicationhost.config
Each solution will have its own config file.
This issue is because of the authentication mode selected(by default) by the MVC 5 Template, which triggers the ReturnUrl Style of redirection that might lead to an infinite loop if not configured correctly.
To disable OWIN startup discovery,add this key to your webconfig file.
<add key="owin:AutomaticAppStartup" value="false"/>
I had to remove (Source Link):
<authorization>
<deny users="?" />
</authorization>
I know I may be late, and this is not directly for the OP's question. But if anyone in the future come here, one more check about AllowAnonymous and Authorize attribute is that, you have to check all child actions too.
For example, I had my Layout (which the Login page also use) that call 2 child actions for breadcrumbs and sidebar, and they did not have AllowAnonymous attribute (the Controller had Authorize attribute).
Hope this help.
In IIS, Select you website and check for Authentication, If you are using Forms Authentication then -
Set 'Windows Authentication' to 'Disabled' ,
Set 'Anonymous Authentication' to 'Enabled'
Set 'Forms Authentication' to 'Enabled'
ASP.Net MVC 5 template adds Microsoft.Owin and related libraries to the project. Since Owin infrastructure doesn't require Forms Authentication, the template also introduces the following key in web.config.
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
Presence of this key could be a reason for undesirable looping back to Login page. Commenting it may help fix the problem for some people.
I faced the same problem because my MVC project was configured for .Net 4.5 but I was using .Net 4.0 as my application pool in IIS. Switched it to .Net 4.5 application pool and the problem was fixed. I hope this helps some one else!
TL:DR? Do not call a protected web API (any web API which requires Authorization) from an authorization page such as ~/Account/Login (which, by itself, does NOT do this.). If you do you will enter into an infinite redirect loop on the server-side.
Cause
I found that the culprit was, indirectly, AccountController::Authorize and the fact that AccountController is decorated with [Authorize].
The root cause was Sammy() being called from HomeViewModel() (Line 6 of home.viewmodel.js), which was accessing a "protected web API". This was being done for /Account/Login, which resulted in /Account/Login redirecting to itself.
Confirmation
You can confirm this is the cause of your problem through several methods:
Decorate AccountController::Authorize with [AllowAnonymous]
Comment out the Sammy() calls made during viewmodel construction.
Solution
The solution was to only emit the app bundle (a.k.a "~/bundles/app") for views which already required authorization. To my knowledge /Account/ views are classic MVC-based views, and are not part of the app datamodel/viewmodel, but I had mistakenly moved the bundle Scripts.Render(#"~/bundles/app") call into _Layout.cshtml (causing protected web API calls to be made for all MVC views, including /Account/.)
in my case: in my _layout.cshtml, i use Html.Action to call Action from Authorize Controller: ex: Html.Action("Count", "Product") -> loop error
fix: decorate by [AllowAnonymous] attribute in that Action (or remove these Html helper from _layout)
I just dealt with this issue for hours on end.
For me, it was in the Startup.Auth.cs file.
This code, when commented out, stopped the redirect loop.
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
Please be aware that this is potentially harmful advice, it's rarely a good idea to modify an applicationhost config file directly, there are usually tools that will do this for you, safely (for example, from within Visual Studio.) Before proceeding, be sure to create a backup copy of this file in the event your IIS Express becomes trashed.
To fix this problem, I took the default IIS configuration file located here :
C:\Windows\System32\inetsrv\config\applicationHost.config
To my document
%userprofile%\documents\iisexpress\config\applicationhost.config
And it worked.
This was because I had some Windows Authentification set and not the anonymous account.
Make sure you have no actions in pipeline that have authorize attribute.
In my case, my layout had navigation menu controller which was missing allowAnonymous attribute.
I solved the same problem thanks to this accepted answer: ASP.NET Login Redirect Loop when user not in role.
It is possible that the controller containing Login action is decorated with an AuthorizeAttribute (even a custom one) while the login action is not decorated with AllowAnonymous attribute. Removing AuthorizeAttribute from the controller and adding AllowAnonymous to login action may be a possible solution.
These answers are more or less pieces of the same puzzle; I'll try to put everything in one place.
Problem that OP described hit my application the moment I implemented the OWIN pipeline and AspNET Identity.
So let's see how to fix it...
OWIN Startup
I guess you need it, because if you don't, then you don't need authentication, and I guess you do.
Except it you're using some old-style authentication, and I guess you don't.
So, don't remove either the OWIN startup attribute...
[assembly: OwinStartupAttribute(typeof(YourApp.Probably_App_Start.SomethingLikeAuthConfig))]
...or the configuration line...
<add key="owin:AppStartup" value="YourApp.Probably_App_Start.SomethingLikeAuthConfig" />
Access restriction on controllers
Now we cleared this up, you need the authentication. This means either each of your controller needs the [Authorize] attribute, or you can do the same to all controllers in one place by registering the thing globally (e.g. in RegisterGlobalFilters(), add line filter.Add(new AuthorizeAttribute())).
In the former case (when securing each controller separately) skip this part, just go to the next one.
In the latter case all of your controllers will be secured against unauthorized acces, so you need an entry point for that authorization - unprotected Login() action.
Just add...
[AllowAnonymous]
...and you should be good.
OWIN cookie configuration
When your user logs in, his browser stores encrypted (hopefully!) cookie in order to simplify things for the system. So, you need cookie - don't delete the line that says UseCookieAuthentication.
What you really have to do is turn off the IIS integrated authentication mechanism for your web application. This means switching off Windows Authentication (Disabled) and enable letting any user in, at least as long as IIS Express is now concerned, by setting Anonymous Authentication (Enabled).
When you start your web site, this will in turn copy these settings into IIS Express configuration (applicationhost.config), and there you should see these two lines:
<windowsAuthentication enabled="false" />
<anonymousAuthentication enabled="true" />
You might have the authorization config in your web.config that says deny users="?". It means the authorization subsystem is instructed to prevent anonymous users from entering.
With OWIN, this still works as designed. You either have to remove this, or make your anonymous user able to access the Login page by using something like...
<location path="Account/Login">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
HTH
I had similar issues where it was in an infinite loop when calling back to the website locally. It turns out that when debugging locally it was redirecting the ports. I updated port numbers in the project properties screen but left the Azure definition the same in the cloud project and everything started to work as expected.
I had the same issue with my Asp.Net MVC 4 project. I resolved it by going to Startup.cs and commenting out the line for ConfigureAuth(app)
public void Configuration(IAppBuilder app)
{
//ConfigureAuth(app);
}
I also made sure that I had Windows Authentication enabled in IIS for my project, and all other authentication options disabled.
For me, this turned out to be caused by my LoginViewModel containing references to translation resources files, apparently being protected by authentication. I removed those references, and the problem was solved.
For me, removing the following block fixed it:
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
Assume
<authentication mode="None" />
in my case it was a very wired problem , i decorated the home controller by non existent role. so it causes a redirection loop.
Go to to your applicationhost.config file and set anonymousauthentication = "true"
<authentication>
<anonymousAuthentication enabled="true" userName="" />
<windowsAuthentication enabled="true">
<providers>
<add value="Negotiate" />
<add value="NTLM" />
</providers>
</windowsAuthentication>
</authentication>

How SetAuthCookie works for two different site

I would like know how SetAuthCookie works for different application on same server?
Currently I have two similar applications with different virtual directories.
How can I make it so that if I login to one of them then it doesn't ask me for login on the other application, and the same for logout?
It is possible if both applications are hosted on the same top level domain. You should specify this domain in your web.config of both applications:
<forms
name="name"
loginUrl="URL"
defaultUrl="URL"
domain="example.com">
</forms>
This way the forms authentication cookie will be emitted with the domain property setup and the client will effectively send it between the 2 applications. Another pre-requisite is that both applications share the same machine keys so that an authentication cookie that was encrypted by the first application can be successfully decrypted by the second application. If both applications are hosted on the same server you could set those machine keys in machine.config, if not then you could set them in web.config of each application:
<system.web>
<machineKey decryption="AES" decryptionKey="C03B1AB0BC1ACCD18EA915CBD87373010AD0DEC430A69871,IsolateApps" validation="AES" validationKey="C0ED7C430148AD4BC6505085DA4FD0DD3EE2453B566FC4EA4C7B3C2DCAB2025A79C774370CA884DF909CE9A3D379E544B7890D0A1CEE164141D3A966999DC625,IsolateApps" />
</system.web>
I've also covered this in the following answer.
Even the post is old but there is an easy solution add "name" in the form tag in web.config, coz if you dont give a name to the cookie it will have a default one
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" name="client" />
</authentication>
for the other application put another name, it works perfectly with me. good luck

Auto logging in to another ASP.NET Application from main Web Application

I'm running the latest version of YetAnotherForum in a folder beneath my main WebApplication. The subfolder is configured as an application in IIS and navigating to the folder and logging in works wonderfully. YAF is setup with a membership provider and uses Forms Authentication.
What I'm trying to do now is to auto login a user into the forum from the main website. The main website uses custom authentication through sessions and cookies. It doesn't use any of the built in ASP.NET authentication or membership components.
So basically what I want to happen is that when a user click on a link to access the forums, they're sent to a processing page that authenticates them into the YAF Application before it sends them over to the subfolder.
Even though the main app doesn't use the built in authentications pieces, I've still set the authentication mode to forms and made sure the tag beneath that matches the one in the YAF web.config. Then, on the processing page I'm calling FormsAuthentication.SetAuthCookie(username, true), then redirecting. But YAF kicks me back to the login page anyway. Not sure where to go from here.
Main site is:
example.com/
web.config:
<authentication mode="Forms">
<forms name=".YAFNET_Authentication" protection="All" timeout="43200" cookieless="UseCookies" />
</authentication>
YAF is:
example.com/yaf (Seperate WebApplication in IIS)
web.config
<authentication mode="Forms">
<forms name=".YAFNET_Authentication" protection="All" timeout="43200" cookieless="UseCookies" />
</authentication>
Processing page is: (in pseudo)
example.com/autoLogin.aspx.cs
public void AutLogin(){
string userName = doStuffToGetUsername();
YAFStuff.CreateUserIfNeeeded(userName);
FormsAuthentication.SetAuthCookie(userName, true);
Response.Redirect("/yaf/");
}
I'd been searching Google for 2 days trying to sort this out, but I finally stumbled onto the solution. I needed a MachineKey that matched on both web.config files for the encryption process.
http://forum.yetanotherforum.net/yaf_postst8780_Custom-membership-and-role-provider-with-YAF-Profile-provider.aspx
Sweet!

ASP.NET Forms Authorization

I'm working on a website built with pure HTML and CSS, and I need a way to restrict access to pages located within particular directories within the site. The solution I came up with was, of course, ASP.NET Forms Authorization. I created the default Visual Studio log in form and set up the users, roles, and access restrictions with Visual Studio's wizard. The problem is, I can't log in to the website with the credentials that I have set.
I'm using IIS 7.
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
I'd guess (since I don't have IIS7 handy ATM) that you'd need to turn off Anonomyous Auth, and enable Forms Auth in the IIS7 sections.
At what point did you insert your login/password? Did you have a look at the tables that where created? Althought your password must be encrypted, maybe it's worth just checking if your user was actually created.
At what point did you insert your login/password? Did you have a look at the tables that where created? Althought your password must be encrypted, maybe it's worth just checking if your user was actually created.
Forms Authentication does not require any form of user database.
Steve, can you please paste in your forms authentication web.config section, also any relevant code to the ASP.NET Login control you were using.
There is not enough information to troubleshoot here yet :)
The web.config section is pretty useless as far as I can tell:
<authentication mode="Forms" />
I looked in IIS 7, and in the Authentication section it says: Anonymous Authentication = Enabled, ASP.NET Impersonation = Disabled, Basic Authentication = Disabled, Forms Authentication = Disabled.
Also, I have made no changes to the code other than dragging a Login object onto the designer and changing the page it points at to index.html.
Currently, the log in fails by displaying the log in failed text.
EDIT: Earlier when I would try to navigate directly to a page that is restricted, I would receive a blue page saying that I had insufficient permissions. Now I can see the pages that are restricted without logging in even though I have anon access denied.
Steve,
I don't think the issue is with your IIS settings. Because forms authentication does not rely on IIS authentication, you should configure anonymous access for your application in IIS if you intend to use forms authentication in your ASP.NET application.
Try this in your web.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<authentication mode="Forms" >
<forms loginUrl="~/login.aspx" defaultUrl="~/">
<credentials passwordFormat="Clear">
<user name="YourUsername" password="superSecret" />
</credentials>
</forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<system.web>
</configuration>
There are better ways to implement forms authentication than hardcoding a username and password into your web.config, but this should work for getting you started.

Resources