ASP.NET MVC Beta Authorize attribute sends me to wrong action - asp.net-mvc

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.

Related

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 !

MVC Custom errors not working in IIS8.5 (but working locally)

I can't get ANY custom error pages to appear in IIS8.5!
When I run my MVC 5 app locally in Visual Studio, custom error pages are displayed. But when I deploy to IIS on my webserver, and navigate to the site sub-page with a 'bad URL' my custom 404 page should be displayed, but the default generic 404 page is shown instead.
Here is what I've done:
web.config
customError section has been deleted.
Added the following section
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<remove statusCode="500" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
<error statusCode="500" responseMode="ExecuteURL" path="/Error/ServerError" />
</httpErrors>
</system.webServer>
Controller
namespace MyApp.Controllers
{
[Authorize(Roles = "MyRole")]
public class ErrorController : Controller
{
[AllowAnonymous]
public ActionResult NotFound()
{
Response.StatusCode = 404;
return View();
}
[AllowAnonymous]
public ActionResult ServerError()
{
Response.StatusCode = 500;
return View();
}
}
}
Views
Very simple and straight forwards (not included here).
IIS
Verified the IIS Error Page feature is identical to what's in my config. A page for each error status code. Feature and Pages are set to 'custom'.
Checked Windows Features\Web Server (IIS)\Web Server\Common HTTP Features\HTTP Errors is installed.
Developer Tools
Navigating to a sub-page spelt incorrectly shows I'm getting a 404 Client Error.
Help
I've tries many things! Am I missing something? IIS environmental issue, i.e. a setting somewhere?
Custom errors work in my IDE but not on IIS. I've spent over a day on this! Read many pages, articles, and similar questions on SO.
After several days of investigating, finally found the issue.
In IIS, my website was residing as an Application under the Default Web Site, e.g. Default Web Site\MyDevSite. (All my dev sites are under the default web site).
When I moved the website to it's own IIS site, custom error pages are now being displayed!
If anyone knowns the reason why having an Application in IIS prevents custom error pages from being displayed, please add a comment here. It would be good to understand why this occurs.
I hope this helps somebody out. Had me going for quite a while.
How are you browsing IIS? If you're doing it from the same machine, then you aren't going to see your custom error pages, because the customErrors section will default to using RemoteOnly if not specified.
the problem is with the path in web.config(path="/Error/NotFound"). the url path of NotFound page will be changed when you move your website under the Default Web Site. So, give the correct url of the page at path then it will work(this is worked for me).

forms authentication gives a too long query string [duplicate]

This question already has an answer here:
ASP.NET MVC 5 : Endless redirect to the login page using the site template
(1 answer)
Closed 8 years ago.
Im trying to make a (temporary) login storing the users in my web.config file.
After adding deny to the web.config file it gives me this error
HTTP Error 404.15 - Not Found
The request filtering module is configured to deny a request where the query string is too long.
The url looks like this
http://localhost/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%252525252525252FAccount%252525252525252FLogin%252525252525253FReturnUrl%252525252525253D%25252525252525252FAccount%25252525252525252FLogin%25252525252525253FReturnUrl%25252525252525253D%2525252525252525252FAccount%2525252525252525252FLogin%2525252525252525253FReturnUrl%2525252525252525253D%252525252525252525252FAccount%252525252525252525252FLogin%252525252525252525253FReturnUrl%252525252525252525253D%25252525252525252525252FAccount%25252525252525252525252FLogin%25252525252525252525253FReturnUrl%25252525252525252525253D%2525252525252525252525252FAccount%2525252525252525252525252FLogin%2525252525252525252525253FReturnUrl%2525252525252525252525253D%252525252525252525252525252FAccount%252525252525252525252525252FLogin%252525252525252525252525253FReturnUrl%252525252525252525252525253D%25252525252525252525252525252FAccount%25252525252525252525252525252FLogin%25252525252525252525252525253FReturnUrl%25252525252525252525252525253D%2525252525252525252525252525252FAccount%2525252525252525252525252525252FLogin%2525252525252525252525252525253FReturnUrl%2525252525252525252525252525253D%252525252525252525252525252525252FAccount%252525252525252525252525252525252FLogin%252525252525252525252525252525253FReturnUrl%252525252525252525252525252525253D%25252525252525252525252525252525252FAccount%25252525252525252525252525252525252FLogin%25252525252525252525252525252525253FReturnUrl%25252525252525252525252525252525253D%2525252525252525252525252525252525252FAccount%2525252525252525252525252525252525252FLogin%2525252525252525252525252525252525253FReturnUrl%2525252525252525252525252525252525253D%252525252525252525252525252525252525252FAccount%252525252525252525252525252525252525252FLogin%252525252525252525252525252525252525253FReturnUrl%252525252525252525252525252525252525253D%25252525252525252525252525252525252525252F
(without deny it sets the cookie but i can still access all the pages)
This is how it looks in my web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" name=".ASPXAUTH" slidingExpiration="true" timeout="1440" path="/" defaultUrl="~/">
<credentials passwordFormat="Clear">
<user name="matchUser80" password="123Match789"/>
</credentials>
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
And my controller
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
if (FormsAuthentication.Authenticate(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
FormsAuthentication.RedirectFromLoginPage(model.UserName, false);
if (returnUrl != null)
{
return Redirect(returnUrl);
}
return View();
}
ModelState.AddModelError(string.Empty, "Wrong username or password");
return View(model);
}
I'm using MVC 5.
You should use attributes instead of web.config configuration to authorize your mvc application. Web config configuration should be used only with web form applications.
Decorate your Login action (both get and post version) with [AllowAnonymous] attribute.
User [Authorize] attribute for other controllers.
Read this article to see how to secure your mvc application.
Update
I reproduced your problem locally with default mvc project and i had this in my web.config:
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
Everything started working after i commented the <remove name="FormsAuthentication" /> part

500 error happen in ASP.NET MVC site when submit the google recaptcha code

I use google recaptcha plug-in for ASP.NET in my asp.net mvc site. It works fine when I run it from my local work station. But it is wired after I deploy it on the serve, it could load correctly but page will return 500 internal error when I submit the page with the recaptcha code. If I just leave it blank and submit the page, no error at all.
So, I think it may be brought by some connection issue between google service?
do anyone have some idea about the issue and have any resolution?
the code is quite simple, just set public/private keys in the web.config and use HTML.RAW(recaptcha.generator...) to render the component in the page.
The code is simple: in the view, just add
#Html.Raw(Html.GenerateCaptcha("captcha", "clean"))
And in the controller, just use
[HttpPost]
[RecaptchaControlMvc.CaptchaValidator]
public ActionResult ActionName(Model model, bool captchaValid)
{
if(captchaValid)
{
ModelState.AddErro("....");
}
}
web.config:
<appSettings>
<add key="ReCaptchaPrivateKey" value="**************" />
<add key="ReCaptchaPublicKey" value="***************" />
</appSettings>

MVC Forms LoginUrl is incorrect

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. :)

Resources