Regarding Authorize attribute usage in ASP.Net MVC 4 - asp.net-mvc-4

when we decorate any action with Authorize attribute then how MVC redirect to login form because my login controller name could be different and also view name also could be different. login view also could be stored in different folder instead of shared folder.
so tell me how MVC engine understand that it need to load login form when face Authorize attribute ?
how MVC engine would know where login form template is stored because it location could be different instead of shared folder?
how MVC engine would know what is login controller name if my login controller name is different ?
please discuss 3 points i asked here in details. thanks

The AuthorizeAttribute is a filter, which means that it can execute before the associated controller action. The AuthorizeAttribute performs its main work in the OnAuthorization method. If the user fails authentication, an HttpUnauthorizedResult action result is returned which produced an HTTP 401 status code. In previous versions of ASP.NET MVC the user redirected to the application login page defined in the application's web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
In ASP.NET MVC 5, the redirection process is handled by OWIN middleware components. It redirects unauthenticated requests to a LoginPath value, which
defaults to "/Account/Login":
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType =
DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});

Related

Asp .net core - Authorize access to all files in a folder via roles

I'm upgrading some initial razor code into asp .net razor pages with .net core 5.0. I've been through many examples on the microsoft site, but it seems that I have to set attributes in all of my .cshtml.cs files. that feels just sloppy and error prone because something will be forgotten somewhere.
In .net 4.x razor, I have an _PageStart.cshtml file, I check the user's role, and I redirect them to the login page if they are not in a particular role. I'd like to do the same in asp .net core using a single file or configuration. I don't want to put an attribute on every pagemodel file, that just seems sloppy. I imagine that I would do something like:
options.Conventions.AuthorizeFolder("/Club", "ClubAdmin");
where ClubAdmin is a role in the application and Club is a folder that contains a bunch of razor pages and sub folders. Is this possible?
TIA
To do this, you can define a policy in your Startup.cs file that checks for a role and then configure razor pages to Authorize that folder for that specific policy:
//define the admin policy
services.AddAuthorization(options =>
{
options.AddPolicy("AdminPolicy", policy => policy.RequireRole("Administrator"));
});
services.AddRazorPages(options =>
{
options.Conventions.AuthorizeFolder("/Admin", "AdminPolicy");
});
The RequireRole extension method injects a RolesAuthorizationRequirement handler that will validate for the given role during authorization

ASP.Net Core 2.2 Controller Login Redirect to another [Authorize]Controller Action with Access Token

My Login controller action needs to Redirect(returnUrl); to another Controller action which has [Authorize] attribute. Login controler action generates Access and Refresh Tokens. Currently I append the returnUrl with the access token as query string which is then picked up by JwtBearerEvents.OnMessageReceived and successfully redirected to another controller action. However, this exposes the security token string in the browser address bar. What's the best practices and how to securely achieve this?

Use Anonymous authentication in MVC4 on single controller when the whole application uses Windows Authenticaion

I have an MVC4 Web application which uses Windows Authentication, that is in web.config I have
<authentication mode="Windows" />
And that works fine and everything is ok.
However now I need a controller (an Web API controller in fact) that should be accessed anonymously from a third party component. The problem is that every time I want to invoke this method it requests user credentials.
I tried putting AllowAnonymous attribute to controller and methods but it was not successful.
[AllowAnonymous]
public bool Get(string Called, string Calling, string CallID, int direction)
I checked on both IIS Express and IIS 8 with Anonymous authentication and Windows authentication enabled.
It seems that windows authentication precedes any other authentication and cannot be overridden.
Is there a way to accomplish this?
Add this to your Web.config. Here, my controller is named "WebhookController".
<location path="Webhook">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
See this KB article for more info.
Edit
- As Erik mentioned below, in MVC applications you should not use web.config <authorization> tags for security. Instead, use [Authorize] attributes. Doing so will allow your [AllowAnonymous] attributes to work correctly. You can read more about this here.
The accepted answer seems to be out of date, so...
In your web.config, remove these lines:
<authorization>
<deny users="?" />
</authorization>
In the solution explorer, click your project, then click f4 (or open the properties explorer). Enable Anonymous Authentication.
Now you're free to use the Authorize and AllowAnonymous Attributes. They're pretty straightforward, Authorize means the user needs to be authorized in order to access the action or controller, AllowAnonymous means the opposite. If an unauthorized user attempts to access a controller or action with the Authorize attribute, they'll be redirected to a login page. If you put Authorize on a controller it applies to all the controller's actions, except ones with AllowAnonymous.
web.config should not be touched as indicated here.
In order to achieve desired result AllowAnonymous and [Authorize] (and maybe some custom authorization attribute, if needed) should be used.
Steps to be performed:
Ensure IIS has both Anonymous Authentication and Windows Authentication configured for the web application / web site
All controllers should use [Authorize] attribute. This can be easily achieved if all inherit from a common controller class (e.g. BaseController / BaseApiController). E.g.:
[Authorize]
public class BaseController : System.Web.Mvc.Controller
{
}
[Authorize]
public class BaseApiController : System.Web.Http.ApiController
{
}
Add [AllowAnonymous] attribute to all actions that are supposed to be anonymous. E.g.:
[RoutePrefix("Api/Anonymous")]
[Authorize]
public class AnonymousController : ApiController
{
[HttpGet]
[Route("GetServiceStatus")]
[AllowAnonymous]
public string GetServiceStatus()
{
return "OK";
}
}

Why is ServiceSecurityContext.Current null in an MVC Controller?

I have an ASP.NET MVC 4 project that's using Windows authentication in the Web.config like so:
<system.web>
<authentication mode="Windows" />
</system.web>
However, if I investigate ServiceSecurityContext.Current from a Controller method, it's null. Shouldn't it contain the authentication info of the user since I'm using Windows authentication?
The reason I'm trying to figure this out is because I would like to know what credentials CredentialCache.DefaultNetworkCredentials is using from a Controller method. From what I gathered by reading the MSDN article on the property, it uses the current security context's credentials... which is null.
Thanks for the help!
The ServiceContext classes is intended to be used inside WCF services. It has nothing to do with ASP.NET MVC.
Trying to use ServiceContext.Current inside an ASP.NET MVC application is like trying to use HttpContext.Current inside a console application => you get NULL.
The reason I'm trying to figure this out is because I would like to
know what credentials CredentialCache.DefaultNetworkCredentials is
using from a Controller method
Then you are looking for the User.Identity.Name property:
[Authorize]
public ActionResult Index()
{
string currentUser = User.Identity.Name;
...
}

Authentication causing duplicate page rendering

Let me try to explain this in english :).
I'm having trouble with the authentication in Mvc. I use my layout page to login and to show the other partial views with content.
I decorated the login methods with <AllowAnonymous()> _ to let people login into the page and in my webConfig i have the following entry:
<authentication mode="Forms">
<forms loginUrl="~/" timeout="2880" />
</authentication>
What's happening is when the session expires, the partial view renders the entire page again and i get the entire page twice (one inside the content).
Any help?
You may checkout the following article from Phil Haack which illustrates a nice technique allowing you to prevent the forms authentication module to automatically redirect to the LogOn page but return 401 status code. This could be done conditionally only for AJAX requests. And since the server now returns 401 status code you could detect it on your client side AJAX call and act accordingly.
Thks for the answer, but i solved my problem with the following post :
C# MVC: How to override configured authentication redirect?