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

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

Related

location path="" deny users="?" prevents access to domain root ("/") instead of showing RouteConfig default

I am using Katana to secure my site, along with location paths in web.config (as the site is a mixture of ASP.Net web forms and MVC).
My default route is configured like this to allow the login page to be displayed when accessing the domain root (e.g. www.example.com should show the login page at www.example.com/Public/Login):
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Public", action = "Login", id = UrlParameter.Optional }
);
}
Web.config is set to grant access to the login controller URL, but deny everything else that isn't authorized:
<location path="Public/Login">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
<location path="">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
This works fine except for www.example.com. Locally using IISExpress, these URL's:
https://localhost:44374
https://localhost:44374/
redirect to:
https://localhost:44374/Public/Login?ReturnUrl=%2F
This is incorrect, as / should be accessible to anonymous users based on the default RouteConfig MapRoute default.
Can anyone please advise what I'm doing wrong? Is there any way to grant access when only the root is accessed for a domain?
After trying around a dozen suggestions from this site, I finally found this to be the only solution that worked in my case. I'm not sure whether a mix of webforms and MVC controllers causes this issue (routing conflicts?), but adding this to global.asax worked perfectly:
namespace MyApplicationNamespace
{
public class MyApplicationName : System.Web.HttpApplication
{
protected void Application_Start()
{
// leave as is - left here to clarify where new method needs adding
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
if(Request.AppRelativeCurrentExecutionFilePath == "~/")
{
HttpContext.Current.RewritePath("/Public/Login"); // the MVC login controller/action
}
}
}
}

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

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.

Access both register and login pages for anonimus MVC 4

When user open my site, he sees login page (mentioned in routeConfig). But if he tries to access register page (or any other but it's normal), he still be redirected to login page. Both actions are [AllowAnonimus]. In my web config i have such a paragraph
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<authorization>
<deny users="?"/>
</authorization>
I wish I could transfer to register page but not to others and I don't want to put [Authorize] to all actions.
[AllowAnonymous]
public class LoginController : Controller {}
Also you dont really need authentication mode = forms.
Add to webconfig:
<authentication mode="None">
</authentication>
And use your RouteConfig.cs
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
);
Also use the global authentication filters:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
}
}
This will allow [AllowAnonymous] to work all your controllers will need authorization or you can add authorization to just methods if needed.
[AllowAnonymous]
public ActionResult Test() {}
Should mention if you dont want to add [AllowAnonymous] just leave the controller or method be.

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;

Resources