MVC Forms LoginUrl is incorrect - asp.net-mvc

I have an ASP.NET MVC 3 application with forms authentication. For some reason that I cannot see, the login redirect url is /Account/Login?ReturnUrl=%2fSecure%2fAction instead of /Account/LogOn?ReturnUrl=%2fSecure%2fAction. The difference is subtle, its using /Account/Login instead of /Account/LogOn.
My web.config forms section is correct. Would else could possibly affect the login url??
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="720" />
</authentication>

This is a known issue. I had the same problem with my custom authorize attribute. I found the solution somewhere on the net, can't remember where. Just add this to appSettings in your web.config
<add key="loginUrl" value="~/Account/LogOn" />
Note: This works with MVC 3, I didn't try it with previous versions.
EDIT:
Found it mentioned in release notes, but it seems that they've changed the setting name and forgot to update release notes for RTM version.

I ran into a similar problem sometime ago. After a few months I discovered the root of the problem: I had added a 'deployable dependency' on 'ASP.NET Web Pages with Razor Syntax'. This adds a reference to: WebMatrix.Data.dll
This assembly has a class with a static constructor that does the following:
static FormsAuthenticationSettings()
{
FormsAuthenticationSettings.LoginUrlKey = "loginUrl";
FormsAuthenticationSettings.DefaultLoginUrl = "~/Account/Login";
}
Check if you are referencing this dll.

frennky's answer helped me get to this. I needed all of these in my web.config:
<appSettings>
<add key="loginUrl" value="~/Authentication/LogOn" />
</appSettings>
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Authentication/LogOn" timeout="2880"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>

To fix this problem, which still exist in MVC 3 you have to remove the WebMatrix.*.dll from _bin_deployableAssemblies and bin folders respectively.

Instead of this:
<appSettings>
<add key="loginUrl" value="~/Authentication/LogOn" />
</appSettings>
You could use this:
<appSettings>
<add key="PreserveLoginUrl" value="true" />
</appSettings>
It worked for me.

Is it originating from the redirect contained within your LogOn action result?
Search your project for the string LogIn and you may find where it is specified?

I just ran into this issue (like 6 years later and this page doesn't rank high in searches anymore...) my fix was similar to santiagoIT.
Because I added authentication to a project that didn't previously have it I pretty much "cheated" by copying required authentication code from a default project template which included:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
The forms authentication url was using web.config for all my aspx pages but bombed when I added the Authorize attribute.
Changing the LoginPath fixed my issue.

After Trying Many technique in .net MVC 5 in VS2015 I ended up here.
Its was hard to understand but yet very Simple.
Whatever we code within Form loginURL was later removed OR replaced by the web.config itself.And this line in the Web.Config does it.
<remove name="FormsAuthentication"/>
Comment the line out in web.config and then it won't go to "Account/Login" automatically. I tested in VS2015 and it works like a charm. :)

Related

MVC 4 Windows Authentication

I'm relatively new to MVC, I need to retrieve username and pass it to my company library that checks for user credential.
Web.config
<authentication mode="Windows" />
<authorization>
<allow users="*"/>
<deny users="?"/>
</authorization>
Controller
[Authorize]
public class MVCAuthen : Controller
{
public string GetCredentials()
{
var userName = HttpContext.Current.User.Identity.Name;
string credential = library.Getcredential(userName);
return credential;
}
}
My question is I keep getting blank when I try to retrieve username. Can someone tell me what I'm doing wrong or how I retrieve username?
Note: I'am trying to do this locally since I'm trying to debug it.
First you should be using a Internet Application or Intranet Application template.
Then on the web.config you should comment or remove the forms authentication and use the windows authentication. Something like this:
<--
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
-->
<authentication mode="Windows" />
And add this in the 'appSettings'
<appSettings>
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
</appSettings>
Now go to you solution explorer, right click the project and go to properties. There you must change Windows Authentication to enabled.
If you do not want to allow any anonymous access you may disable Anonymous Authentication too.
Once that is done you can add the [Authorize] on any Controller or Action.
Then you should be able to login with your windows password.
If you are able to login and view the page then you can retrieve the user name like this.
var username = HttpContext.User.Identity.Name;

How to get current windows user login name in MVC4 with .net Framework4.0

I have been trying to the get the current windows user name, but finally NO.
Below are the ways which I have tried but could not get the user name, Am getting empty value
STEP I have tried with
string usr System.Web.HttpContext.Current.User.Identity.Name;
Got empty value
STEP Checked in my local ISS under Security and Enabled Windows Authentication
STEP in my project I have checked the radio button to use "Use Visual Studio" Development Server
STEP in my web.config file I have selected Form=Windows
<authentication mode="Windows">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
STEP: I have also tried with authorization
<authentication mode="Windows" >
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<authorization>
<deny users="?"/>
</authorization>
STEP: I hosted in my development server and made a check of Anonymous Authenticate = Disable and Windows Authentication = Enable
STEP: Authorize (I have used this on top of controller)
string str = System.Web.HttpContext.Current.User.Identity.Name
but got empty value
I have tried all these way to get the current user name but am getting empty value. I am trying to get it under controller. Is there a way to get this? Please advice.
Set this in web.config:
<configuration>
....
<system.web>
<authentication mode="Windows" />
....
</system.web>
</configuration>
This enabled Windows authentication to get your Windows user name.
Next, if you're using Internet Explorer, you need to add "http://localhost" to the list of valid intranet sites (in IE Internet Options > Security > Local Intranet > Sites > Advanced and then add http://localhost to that list). This allows IE to pick up the current Windows user and launch your web site automatically, without prompting for the username/password again.
In your HomeController's Index method:
public ActionResult Index()
{
// get the currently logged on Windows user
ViewBag.UserName = HttpContext.User.Identity.Name;
return View();
}
and then in your view:
<h3>Hello, #ViewBag.UserName !</h3>
That's it !

Asp.net MVC 5 redirect to Account/Login

I'm learning ASP.NET MVC. I have MVC version 5.2.2.0
I attached Authorize attribute to an action method Index() in Employee controller.
In the Web.config file, I changed authentication tag data as follows:
<system.web>
<authentication mode="Forms">
<forms loginurl="~/Authentication/Login"></forms>
</authentication>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
What is expected is that when localhost:port/Employee/Index is accessed, the user should be redirected to localhost:port/Authentication/Login
But it is redirecting to localhost:port/Account/Login
By looking at other links, I tried the following things:
1.Added
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
<add key="loginUrl" value="~/Authentication/Login" />
<add key="PreserveLoginUrl" value="true" />
to appSettings section of Web.config
2.Changed IIS 8 Anonymous Authentication from Specific User to Application Pool Identity
3.When the above two didn't work, I changed authentication tag to
<authentication mode="Windows" />
But none worked.
EDIT
Don't do the things 1, 2, 3 I mentioned above. Just do the changes mentioned in the answer
The problem is that you will have the OWIN middleware configured by default to redirect to "/Account/Login" for cookie authentication.
Open /AppStart/Startup.Auth.cs and edit the following block of code to target our own URL :-
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
Maybe this has changed. I'm learning ASP.NET 5 (dnx451 and MVC 6.0.0-rc1-final) and there you have to define the default redirect adress for login in the service: "ConfigureServices" method not in the "Configure" method.
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<IdentityUser, IdentityRole>(configure =>
{
//add some requirements
configure.User.RequireUniqueEmail = true;
configure.Password.RequiredLength = 8;
//define the default page if a call must be [Autorized]
configure.Cookies.ApplicationCookie.LoginPath = "/Auth/Login";
})
.AddEntityFrameworkStores<AuthContext>(); //use entity framework to store the user data
}
Comment the following line out in web.config and then it won't go to "Account/Login" automatically. I tested in VS2015 and it works fine.
Line to be commented out:
<remove name="FormsAuthentication"/>

Problems with IIS and Custom Membership Provider + Custom Role Provider

I have developed my own classes for Custom Membership and Role providers.
Everything works locally. Nonetheless, after deploying the solution to IIS for testing, my login action seems to work (at least, the action validates the username+password and the user appears to be authenticated) but whenever I try to access actions that are decorated with annotations like
[Authorize(Roles="Employee, Admin")]
I keep getting redirected to the login page, as if the user didn't have the necessary role (he does, though).
So locally, the application succeeds in validating users and checking the authenticated user's roles before executing actions (thus, I assume that my methods on both classes are correct) but on IIS it looks like the role provider isn't working properly. Anyone happens to know where might I be wrong or how can I get a better view on my problem?
In my Web.Config:
<system.web>
(...)
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<membership defaultProvider="CustomMembershipProvider">
<providers>
<clear />
<add name="CustomMembershipProvider" type="MyApplication.Infrastructure.CustomMembershipProvider" connectionStringName="DBEntities" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="CustomRoleProvider">
<providers>
<clear />
<add name="CustomRoleProvider" type="MyApplication.Infrastructure.CustomRoleProvider" connectionStringName="DBEntities" applicationName="/" />
</providers>
</roleManager>
(...)
</system.web>
Thanks in advance.
EDIT: Aditional Info.
I just modified one of my actions' anotation to simply [Authorize] and it works. So, I believe that the authentication works and the problem must be related to the Role provider.
I'm using Entity Framework for my Data Model, the con. string is as follows:
I managed to register a user and log in using the that newly created account, which would mean that the DB connection and the Custom Membership Provider(?) are working properly.
A "#foreach (String str in Roles.GetRolesForUser(User.Identity.Name)){#str} prints the roles locally and doesn't print anything when deployed.
Ok, I fixed it. Here's the explanation in case someone needs it in the future:
After narrowing out the causes (as seen in my edits), I figured out that the problem must be related to my CustomRoleProvider.
That class has methods like this one:
public override string[] GetRolesForUser(string Username)
{
List<string> roles = new List<string>();
using (DBEntities _db = new DBEntities())
{
try
{
var dbRoles = from r in _db.UserRole
where r.Users.Username == Username
select r;
foreach (var role in dbRoles)
{
roles.Add(role.Role.Name);
}
}
catch
{
}
}
return roles.ToArray();
}
So I was catching an exception and not doing anything with it. I removed the try-catch block, and got this message:
There is already an open DataReader associated with this Command which must be closed first.
A bit of stackoverflowing and I found this: There is already an open DataReader associated with this Command which must be closed first
Turns out my local connection string had MultipleActiveResultSets=true but the connection string on my publish settings didn't. I modified my publish settings and voilĂ , seems to be working now.
I don't really know the advantages/disadvantages of having that setting, but it is working and I really need to move on. Thank you all for your help anyway.
I have had the similar issue. After adding machineKey to web.config everything works all right.
<system.web>
<machineKey validationKey="2E417D4AC04F20FA6CE1CF1EFE23FBF1695BF6981B605B1B8628D2182C43D0B10E48C4A83FDCE0D1D6300095D9EE1B8746A37E2C3256554405983DCAA7622875" decryptionKey="FA6D35C22BF7E5E9E4438052B924CCC017521137C5EB017D07C7038B80C5F726" validation="SHA1" decryption="AES" />
</system.web>

ASP.NET MVC Beta Authorize attribute sends me to wrong action

Today I started playing with the MVC 3 Beta. Started with an application from default MVC 3 template, added a new action in the Home controller as follows(with a view for it)
[Authorize]
public ActionResult Secured()
{
ViewModel.Message = "This is secured area, only authenticated users should be here.";
return View();
}
Now when I try to go to navigate to Secured action I get a 404 page not found error.
Here is the authentication section from my web.config.
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
If I understood it right the Authorize attribute should result in a 401 unauthorized HTTP response which should be intercepted by the authentication handler and redirect me to the loginUrl. Which should result in Account/LogOn action.
My MVC 2 application works as expected and takes me to Account/LogOn action, am I missing something? or Is this a bug in MVC 3 beta?
It doesn't work with the RTM any more
You need to add
<add key="loginUrl" value="~/Account/LogOn" />
to the appSettings in the Web.Config
The issues is in ConfigUtil in WebMatrix.WebData
private static string GetLoginUrl()
{
return ConfigurationManager.AppSettings[FormsAuthenticationSettings.LoginUrlKey] ?? FormsAuthenticationSettings.DefaultLoginUrl;
}
staticFormsAuthenticationSettings()
{
LoginUrlKey = "loginUrl";
DefaultLoginUrl = "~/Account/Login";
}
ScottGu replies to a similar question on his blog that this is apparently a bug.
The workaround is to add this entry:
<add key="autoFormsAuthentication" value="false" />
to your <appSettings/> section in the web application's root web.config file.
After I delete WebMatrix*.dll in bin directory, everything is OK.
MVC 4 exhibits the same problem. However on MVC 4 if authentication mode is correctly set to ="Forms" in the configuration file, like in the following, the problem disappears:
<authentication mode ="Forms">
<forms loginurl = "your login" timeout ="2880" slidingExpiration="true">
</authentication>
It works for me. Take out the mode and it gives you trouble.

Resources