Automatic User Authentication Framework for Controllers in ASP.NET MVC? - asp.net

In rails I could do something like this to make sure a user is authenticated before accessing an action in the controller:
before_filter :checked_logged_in, :only => [:edit, :update]
I was wondering if ASP.NET MVC had something similar or if there was a framework out there that could essentially do something like the following:
For certain methods with actions that take a certain parameter, I want to point the action to a method, check to see if the user owns that object, and if so, proceed to the controller action. If not, I want to redirect him to another action where I can show him he has invalid credentials.
So basically I am looking for a sort of "before_filter." Anyone know of anything out there that can do this? Thanks!

They are called Action filters in ASP.Net MVC, you can read more here http://www.asp.net/mvc/tutorials/understanding-action-filters-cs.
Asp.net MVC comes with an Authorize filter to indicate actions that requiere the user to be authenticated.
Usage:
[Authorize]
public ActionResult Index()
{
}

Related

Are all incoming requests handled by AuthorizeAttribute in ASP.NET MVC?

I am developing a ASP.NET MVC 5 website which uses local STS for authentication.
I subclassed the AuthorizeAttribute to customize authentication/authorization process, added MyAuthorizeAttribute to GlobalFilters.
When user came in without authenticated, MyAuthorizeAttribute.OnAuthorize successfully caught it and create a SignInRequest to redirect to STS. That is what I want.
I observed that when user authenticated successfully and STS redirected user back, user's browser POSTed a SAML token embedded in request body to my MVC web application, this is by design, and I expected MyAuthenticateAttribute could catch this request, so I can extract the token from request body, check and validate it, however, MyAuthenticateAttribute.OnAuthorize() function didn't get called this time, it directly went to controller.
So is there anything wrong? Where should i catch and handle the token POSTed from user? Thanks.
You need to decorate your action method with [Authorize] attribute or if you want authorization to happen for all actions in a controller, then set that attribute on the controller itself.
Also take a look at the usage of [AllowAnonymous] at https://www.codeproject.com/Articles/1008731/Insight-of-ASP-NET-MVC-s-Authorize-Attribute
AuthorizeAttribute is both an Attribute and a IAuthorizationFilter. Attributes don't actually do anything, the MVC framework scans for where this attribute is added and registers it as a filter on the fly.
However, rather than decorating controllers or action methods with it, you could add it as a global filter:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AuthorizationAttribute());
filters.Add(new HandleErrorAttribute());
}
}
By the same token, you can create your own IAuthorizationFilter or subclass AuthorizeAttribute to do whatever you want. If registered globally, it will always run for all actions and then you can use it to do custom authorization of requests globally.

ASP.NET Web API get user identity in controller constructor

Is good idea to get user identity in ASP.NET Web API controller constructor, for example:
public PagesController(PageValidator pageValidator, PageMapper pageMapper, PagesManager pagesManager, UsersManager usersManager)
:base(usersManager)
{
_pageValidator = pageValidator;
_pageMapper = pageMapper;
_pagesManager = pagesManager;
if (User.Identity.IsAuthenticated)
_pagesManager.UserId = usersManager.GetByEmail(User.Identity.Name).Id;
}
Is always User.Identity was correct populated before this call raise?
This has bitten me a few times. Depending on where/how you are performing your authentication, you need to be careful where you access your identity, particularly in controller constructors.
For example, whilst the controller action is invoked AFTER an IAuthenticationFilter is instantiated, the controller's constructor is called before AuthenticateAsync; meaning any authentication you do in AuthenticateAsync will not be available in your controller's constructor (like in your example).
I typically don't rely on things being available during controller construction (unless handled by DI). Instead access the identity as you need it in your controller actions.
If you are looking at making identity lookup easier (i.e. pulling in your user object based on the User.Identity.Name property) create a base controller class that has a property or method that does it for you, then have your controllers inherit from that...
public User AuthenticatedUser
{
get
{
if (User.Identity.IsAuthenticated)
{
return usersManager.GetByEmail(User.Identity.Name);
}
return null;
}
}
EDIT
See here for a detailed breakdown of the Web.API lifecycle, showing controller creation occurring prior to authentication.
Yes. You can use this property in Controller in any place. ASP.NET has request pipeline: (http://www.dotnetcurry.com/aspnet/888/aspnet-webapi-message-lifecycle).
As you can see Authorization is early stage step in request pipeline.
Controller creation is the latest stage.

Return to the page initiated post-back. Best practice

I have ASP.NET MVC site with authentication dialog (login/password) that is accessible on every page. When user provides login/password post-back is initiated to special controller, not the same as the one generated the page with dialog.
I do some authentication stuff and wish to return user's browser to the same page request came from. I do the following (simplified):
protected ActionResult Authorize(string login, string password)
{
...
return Redirect(Request.UrlReferrer.AbsoluteUri);
}
what is the best practice to perform such action?
Thank you in advance!
In the default Membership of ASP.NET they simply use a returnUrl parameter in the query string. I find that this gets the job done quite well. It also allows me to bounce them to a different url if that is what the requirement is.
There is nothing wrong with the way you are doing it now, I just prefer the flexibility of the query string parameter.

Application design in Spring MVC

I'm new to Spring MVC and trying out a simple project.It will contain a simple adding, viewing, updating and deleting user work flows. It will have login page and once authenticated the user will be taken to a welcome screen which will have links to add, view, update and delete users. Clicking on any of the links will take to individual pages where the user can do the specific tasks. What I'm doing here is, I'm using a MultiActionController to group together all requests related to User work flow. So the request from "Add User" link will handled by the addUser method in the UserController which will redirect the user to the "Add User" page, and the user can then fill in the details and save the new user. Now here is where I'm getting confused. Where should I put the save process of the new user, should I put that in new method inside UserController, or use the same "addUser" method. What is the best way to handle this kind of scenario.
I hope I was able to clear my question.
did you try to check the Petclinic example which is in the Spring distribution? There you can find all the CRUD operation examples and much more...
Based on your example I suggest that you implement a "goto action page" method and a "perform action" mthod in your UserController. For the AddUser operation, the "goto action page" method might be AddUserPage() which performs any necessary initialization and setup required for the "add user" page then forwards the request to the "add user" web page and the "perform action" method might be AddUser() in which you implement the action of adding a user to your website.
For a "Delete User" action, you might have a "DeleteUserPage" and a "DeleteUser". etc.
The idea here being that you need a method in the MultiActonController to send the user to the correct page and another method to implement the desired action. The name of the methods is not important, but I suggest that you name them consistantly (for instance, xxxPage() sends the user to the xxx activity page and xxx() implements the xxx activity).

ASP.NET MVC and ASP.NET membership provider - Handle authentication globally

I'm building a small app with ASP.NET MVC and I'm using the ASP.NET membership provider for handling users. Hooked this up to the login page of the basic MVC template.
What is the best practice for checking a valid authentication globaly? I basically want to redirect to the front page or the login page if the user's not authenticated on all my pages.
-anders
The way we did it, back in the days of MVC Preview 4 or so, was to create a new "BaseController" class, which every other controller then inherits from. This BaseController class uses the Authorize attribute
[Authorize]
public class BaseController : Controller
{
...
}
The rest of our controllers then inherited from this one
public class HomeController : BaseController
{
...
}
Haven't had to work with MVC for a few months now, so I can't say if this is still applicable, so proceed with caution...
You should just annotate any action you want to authenticate with [Authorize], and optionally with some required roles:
[Authorize()]
public ActionResult Index() {
...
return View();
}
This includes your home page action, if you wish. Unauthorized attempts will be always redirected to the login page.
this may be slightly over complicated, but another approach could be to put a custom HTTP Module in the pipeline to redirect the request if the user isn't authenticated.

Resources