forms authentication gives a too long query string [duplicate] - asp.net-mvc

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

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;

AllowAnonymous Attribute not working MVC 5

Inside the Azure Portal I set App Service Authentication "On" For my Web App and I use AAD as Authentication Provider.
This has worked great up until now, I need an endpoint that will allow anonymous users, however the attribute [AllowAnonymous] does not work, I am still required to sign in.
Code:
[Authorize]
[RoutePrefix("users")]
public class UsersController : Controller
{
[Route("register/{skypeid}")]
public ActionResult Register(string skypeid)
{
///stuff...
}
catch (Exception ex)
{
return Content(ex + "");
}
ViewBag.Name = name;
return View();
}
[AllowAnonymous]
[Route("exists/{skypeid}")]
public ActionResult Exists(string skypeid)
{
return Content("Hello " + skypeid);
}
I think the code is right, so does it have something to do with the fact that I use App Service Authentication for my Web App?
EDIT:
So, I found the source of the problem, In Azure if you set "Action to take when not Authenticated" to "Sign in with Azure Active Directory", it does never allow anonymous.
However, If I change it to allow anonymous then users are not prompted to sign in when trying to access a control with the [Authorize]-Attribute, it just tells me "You do not have permission to view this directory or page."
Is this intended? It seems really weird. I want users to be redirected to Login if there is an [Authorize]-Attribute.
Screenshots for clarity:
Check your web.config if you have
<authorization>
<deny users="?" />
</authorization>
its override [AllowAnonymous]
add
<location path="YourController/AnonymousMethod">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
to allow anonymous access
I've just written about this in my book - http://aka.ms/zumobook - look in Chapter 6 for the MVC section.
The basic gist of it is that you need to do a little more to enable authentication; most specifically, you need to set up an auth pipeline (Azure Mobile Apps Server SDK will do this for you) and you need to set up a forms redirect within Web.config:
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
<authentication mode="Forms">
<forms loginUrl="/.auth/login/aad" timeout="2880"/>
</authentication>
</system.web>
Since there are several details to adding the Mobile Apps SDK to your ASP.NET application, I'd refer to the referenced chapter for those details.

ASP.NET MVC Login Not Sticking

I'm having an issue with my ASP.NET MVC 5 simple membership provider login code. The code is as follows:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
bool active = true;
if (ModelState.IsValid && WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe))
{
UserDetail userModel = UserDetail.Initialize(model.Email);
FormsAuthentication.SetAuthCookie(model.Email, true);
active = userModel.ActiveBit;
if (active)
{
return Redirect("~/");
}
else
{
WebSecurity.Logout();
ModelState.AddModelError("", "Account is inactive.");
}
}
else
{
ModelState.AddModelError("", "*Either the Username or Password provided is incorrect.");
}
return View(model);
}
The login processes successfully and I can see the authentication cookie (.ASPXAUTH) in the browser. The problem arises on the next page request. The authentication cookie is passed back to the server, but the server seems to have no record of the login any more. When I set a breakpoint and check after processing the login and requesting a new page (after completing the post-login redirect), User.Identity.IsAuthenticated is false as is WebSecurity.IsAuthenticated and WebSecurity.HasUserID. WebSecurity.CurrentUserId is -1 and WebSecurity.CurrentUserName is an empty string.
It's not a database connectivity issue since I do authenticate successfully. I do a roundtrip to the server and back and I am still not authenticated so the common answers I've seen for CurrentUser == -1 don't seem to apply.
I'm a relative newbie on MVC but I had a coworker who's got a decent amount experience on this look at my code and he couldn't find anything either. Thanks for your help.
By default asp.net MVC5 web.config not supporting FormsAuthentication, check below section of your web config file and remove "<remove name="FormsAuthentication" />" if you want to use FormsAuthentication.
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
Authentication timeout configuration
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
</system.web>
Hope this helps.

MVC: Redirecting to login screen

I am taking over an existing ASP.NET MVC 5 project in order to try to understand the MVC framework. I have noticed that when a user is not logged in, and he attempts to go to some of the webpages, then it automatically redirects him to the login screen. I believe that this has something to do with the following in the Web.config file:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
However, some webpages allow access to them (and are not redirected as above) even when the user is not logged in.
So my question is: Where do I configure which web pages will be automatically redirected to the login screen, and which web pages can be accessed without authentication?
This article explains how to do this with forms authentication. A short snippet of the configuration looks like below. Where default1.aspx is given access to.
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<!-- This section denies access to all files in this application except for those that you have not explicitly specified by using another setting. -->
<authorization>
<deny users="?" />
</authorization>
</system.web>
<!-- This section gives the unauthenticated user access to the Default1.aspx page only. It is located in the same folder as this configuration file. -->
<location path="default1.aspx">
<system.web>
<authorization>
<allow users ="*" />
</authorization>
</system.web>
</location>
</configuration>
You can set an [Authorize] attribute on the controller action that will require the user to be authorized, otherwise they will be redirected to the page specified in the config. You can also specify individual roles that are required to access an action or require authorization for all actions on a controller and explicitly turn off authorization for actions.
Authorize Individual Actions
public class HomeController: Controller
{
public string Index()
{
// Not authorized
}
[Authorize]
public string SecretAction()
{
// Authorized (redirects to login)
}
}
Authorize All Actions
[Authorize]
public class HomeController: Controller
{
public string Index()
{
// Authorized (redirects to login)
}
public string SecretAction()
{
// Authorized (redirects to login)
}
}
Authorize All Actions Except For One
[Authorize]
public class HomeController: Controller
{
public string Index()
{
// Authorized (redirects to login)
}
[AllowAnonymous]
public string PublicAction()
{
// Not authorized
}
}
More here: http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx
And here: Authorize attribute in ASP.NET MVC
An easy workaround if you are doing something simple (like a page or two of public content) is just this:
Response.SuppressFormsAuthenticationRedirect = true;

ASP.NET MVC - Authenticate users against Active Directory, but require username and password to be inputted

I'm developing a MVC3 application that will require a user to be authenticated against an AD. I know that there is the option in MVC3 to create an Intranet Application that automatically authenticates a user against an AD, but it uses Windows Authentication and automatically logs them on. This application may be accessed on 'Open' workstations where the user will need to enter their Domain Username and Password. Any examples or online tutorial would be great. An example project would be exceptional.
You can use the standard Internet application template with forms authentication and insert an ActiveDirectoryMembershipProvider into the web.config:
<connectionStrings>
<add name="ADConnectionString" connectionString="LDAP://YOUR_AD_CONN_STRING" />
</connectionStrings>
<system.web>
<authentication mode="Forms">
<forms name=".ADAuthCookie" loginUrl="~/Account/LogOn"
timeout="15" slidingExpiration="false" protection="All" />
</authentication>
<membership defaultProvider="MY_ADMembershipProvider">
<providers>
<clear />
<add name="MY_ADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider"
connectionStringName="ADConnectionString"
attributeMapUsername="sAMAccountName" />
</providers>
</membership>
</system.web>
In this way you get the Internet application template login form, and it validates against AD for you.
Then it's just a matter of some AccountController cleanup to remove reset password/change password/register functionality leaving just Login.
As mentioned above, you can use the membership provider defined in the web.config file.
The code below is within the implementation of the 'AccountController' from the MVC 3 Template code and has been slightly modified to work with ActiveDirectory:
[HttpPost]
public ActionResult LogOn( LogOnModel model, string returnUrl )
{
if( ModelState.IsValid )
{
// Note: ValidateUser() performs the auth check against ActiveDirectory
// but make sure to not include the Domain Name in the User Name
// and make sure you don't have the option set to use Email Usernames.
if( MembershipService.ValidateUser( model.UserName, model.Password ) )
{
// Replace next line with logic to create FormsAuthenticationTicket
// to encrypt and return in an Http Auth Cookie or Session Cookie
// depending on the 'Remember Me' option.
//FormsService.SignIn( model.UserName, model.RememberMe );
// Fix this to also check for other combinations/possibilities
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
If using .NET 3.5 -- then read this article for the alternative:

Resources