MVC Authorization asks for login everytime - asp.net-mvc

I am using autorize attribute on controller
[Authorize(Roles = "Investor")]
public class InvestorIncomeController : Controller
{
// some stuff
When I register new account and try to use this controller everytime it asks for login again and after logging again it works.
In webconfig file
<system.web>
<authentication mode="Forms" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
I want if user logs in one time he shouldn't need to login again and again.

You should put this attribute above your Register method.
[AllowAnonymous]
public ActionResult Register()
{
}

Related

How can I redirect unauthorized users to a login page

I'm using MVC5 and AD authorization. I want to redirect to a login page if there is no authorization. So I added some setting in web.config as below.
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
But after it. When I start to debug. the homepage's URL is like below.
What's wrong with it? it seems returnUrl is the problem. any suggestions to fix it?
http://localhost:62435/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%...................
2019/08/05
I've solved my problem by setting the steps below.
change the web.config's setting.
From
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
To
<authentication mode="None" />
add code as below.
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
// I've add code here
filters.Add(new AuthorizeAttribute());
}
}
By the way, I'm using UseCookieAuthentication.
I don't understand FormsAuthentication. and the difference between CookieAuthentication and FormsAuthentication.
It looks like your Login action on the Account controller is secured, maybe with the Authorize attribute. Unauthenticated users need to be able to access Login so use the AllowAnonymous attribute with it.
[AllowAnonymous]
public ActionResult Login()
...
Also, you said you're using MVC but your web.config Forms Authentication refers to login.aspx. Based on this - I think it just needs to be ~/Account/Login

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;

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

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;

Allow Anonymous to call certain action in asp.net mvc 3

I have an action named ForgetPassword. Every time an anonymous tries to retrieve the action he /she is redirected to the Login Page. Below are my implementations.
public ActionResult ForgotPassword(string UserName)
{
//More over when i place a breakpoint for the below line
//its not even getting here
return View("Login");
}
And here is a portion of my web.config file
<location path="">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
<location path="Content">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="Scripts">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="Images">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<authentication mode="Forms">
<forms loginUrl="/Home/Login" timeout="5" slidingExpiration="false" />
</authentication>
As you are denying everyone from application by using.
<authorization>
<deny users="?"/>
</authorization>
IMHO, you should not use web.config to control the authentication of your application instead use Authorize attribute.
Add this in your Global.asax file under RegisterGlobalFilters method
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute()); //Added
}
or you can decorate also your controller with [Authorize]
[Authorize]
public class HomeController : Controller
{
...
}
If you are using ASP.NET MVC4, For action which require Anonymous access use AllowAnonymous attribute
[AllowAnonymous]
public ActionResult ForgotPassword() {
//More over when i place a breakpoint for the below line
//its not even getting here
return View("Login");;
}
As per Reference, You cannot use routing or web.config files to secure your MVC application. The only supported way to secure your MVC application is to apply the Authorize attribute to each controller and use the new AllowAnonymous attribute on the login and register actions. Making security decisions based on the current area is a Very Bad Thing and will open your application to vulnerabilities.
From this link: http://weblogs.asp.net/jongalloway/asp-net-mvc-authentication-global-authentication-and-allow-anonymous
If you are using MVC 3 you can't do:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
}
Why it's global and AllowAnonymous attribute doesn't work on MVC 3.
So you need build your own filter. It's working for me (MVC 3), you can check the complete solution here.
using System.Web.Mvc;
using MvcGlobalAuthorize.Controllers;
namespace MvcGlobalAuthorize.Filters {
public sealed class LogonAuthorize : AuthorizeAttribute {
public override void OnAuthorization(AuthorizationContext filterContext) {
bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
if (!skipAuthorization) {
base.OnAuthorization(filterContext);
}
}
}
}
I assume you're setting an "Authorize" attribute on your controller, which will force login for every controller action.
I recommend to remove that attribute from the controller, and set it to each action one by one.
or upgrade to MVC 4 and use the AllowAnonymous attribute.
If you are using ASP.NET MVC4 you can try to put allowanonymous attribute on your action like this:
[AllowAnonymous]
public ActionResult ForgotPassword(string UserName)
{
//More over when i place a breakpoint for the below line
//its not even getting here
return View("Login");
}
For more information take a look at Jon Galloway's article:
Global authentication and Allow Anonymous

Resources