ASP.NET MVC application - user authorization/permissions - c#

I have an ASP.NET MVC web application.
There's a welcome page in my application, and i wish for the user to complete some steps on that page before allowing him to use the application.
I'm trying to accomplish 2 things:
Ensure that the user is always redirected to that page until he completes the required steps. Note: the user is logged in when he is at the welcome page.
Ignore all requests made by that user to any of the controllers, except for a few specific requests to a specific controller.
What is the correct way to do the above?
Thanks.

What i have done is:
Create a class that derives from Controller and add the logic to redirect if not Logged in:
public class CustomController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!LoggedIn) //Here you decide how to check if the user is Logged in
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "YourLogInControllerName",
action = "YourLoginActionName"
}));
}
else
{
base.OnActionExecuting(filterContext);
}
}
}
Then all Controllers derive from this CustomController class.

Sounds like you could use the session for that, or other (more persistent) storage if you must make sure the visitors finish these 'required steps', so you can store it when they've fininshed them.

I created a custom authorise attribute that redirected the use to my login page if they didn't meet the criteria I set. This then allowed me to use [AuthorizeAdminArea] on my base controller which stopped access to all areas. I then used [AllowAnonymous] to allow access to the login area.
Take a look at the SimpleMemshipProvider

Use a Role and only allow access to the other controllers if the user has this Role. Add the user to this Role when they have completed the necessary steps.
See http://msdn.microsoft.com/en-us/library/9ab2fxh0.aspx

Related

How unauthorize access redirect user to login page

I am bit new in asp.net mvc. so i have a confusion where it is mention in project that unauthorize access redirect user to login page. before jumping to code i like to understand this and that is why i am positing this question where i am not able to post any code example rather i am looking for concept and guide line.
suppose i am developing a site with ASP.Net MVC core. i have created a empty project where i add two controller.
one is Home and login controller.
Home controller's index action is not protected by Authorized attribute but Home controller's product action is protected.
when user try to access product action then user should be redirected to login page if not signed in. so tell me how to setup project in classic mvc or mvc core where i will mention that user should be redirected to login page if user is not signed in.
i will not use identity rather i will check user credentials from db using ado.net.
please guide me step wise that what i need to follow.
Thanks
You can use type filter attributes to achieve that. For example if you have a BaseController class and it gets inherited in all your Controller classes, you can add a filter attribute there so that you can run your filtering's (for example: Redirect unauthorized user) before or after specific stages in the request processing pipeline.
[CheckAccessPublicStore]
public abstract class BaseController : Controller
{
}
If you want to only filter your Action method
[CheckAccessPublicStore]
public virtual IActionResult Product()
{
return new EmptyResult();
}
Then
public class CheckAccessPublicStoreAttribute : TypeFilterAttribute
{
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.PublicStoreAllowNavigation))
context.Result = = new RedirectToRouteResult(new RouteValueDictionary {
{ "controller", "Customer" },
{ "action", "LogIn" }
});
}
}
For more you can learn here: https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-6.0

ASP.NET MVC route to return user to origin from partial view

I'm using ASP.NET MVC in Visual Studio 2015. The app has the following structure:
MyApp
Controllers
Controller1
Actions
Create
Delete
Details
Edit
IndexPartial
Controller2
Actions
Edit
Controller3
Actions
Edit
Views
Controller1
Create
Delete
Details
Edit
IndexPartial
Controller2
Edit
Controller3
Edit
The app displays Controller1/IndexPartial view on the Controller2/Edit view and on Controller3/Edit. This partial view displays rows of data, each with Edit, Details, Delete buttons which take the user to the Controller1 views for those actions.
When the user is done with the Controller1 action, they need to return to Controller2/Edit or Controller3/Edit via the Back to List button or when the Save/Delete buttons are clicked. But how do we determine where the user originated? Did the user come from the Edit of Controller2 or Controller3?
We've thought of using a session variable. Can RouteConfig.cs be used to track the user's path and help determine where s/he should return? How do we do this via routes in MVC?
Thank you for your help.
Update: This is all done via the server; no JavaScript (Angular, etc.).
The routing engine has nothing to do with what you need. You need to track user navigation and a good way to do this is using ActionFilters.
You can create a custom ActionFilter that checks the UrlReferrer on its OnActionExecuted and decides how to redirect the request to the appropriate Controller/Action.
[Example]
ActionFilter
public class RedirectAfterActionFilter : ActionFilterAttribute, IActionFilter
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Your decision logic
if (filterContext.HttpContext.Request.UrlReferrer.AbsolutePath == "something usefull")
{
filterContext.Result = new RedirectToRouteResult("Your Route Name", routeValues: null); // redirect to Home
}
base.OnActionExecuted(filterContext);
}
}
ActionFilter usage
[RedirectAfterActionFilter]
public ActionResult DoSomethingAndGetRedirected()
{
// Save, Edit or Whatever
//...
return new EmptyResult(); // no need to return since the user will be redirected by the filter
}
Extra: Read How to redirect from a action filter if you dislike to use Route names to redirect.
There are two aspects to this:
The "Back to List" link
The "Save/Delete" actions
As far as the "Back to List" link, your controller should be giving the view all the information it needs to produce a viable GUI. Pass an identifier (or even the actual return URL) to the view in the ViewBag as a dynamic property and let the view render the link to the destination.
For the "Save/Delete" actions, it depends on how they are implemented.
If it's all JS with http requests then the same concept above applies.
If you are posting back to the server however, the controller will have to do the redirection with something like RedirectToAction().
How about storing the previous location in a ViewBag and then populate your button href with the ViewBag content...
Or
You can use Url Referrer, which fectches the previous url that linked to current page.
Of course the best method will depend on your implementantion, without seeing your code those two are the best option that I can think of.

Authorization in ASP.net5

I am trying to see if there is something "out of the box" in ASP.net5 for authorization for my application needs. I am using a group/permission based approach for authorization. Using Identity3 I am using Role as Group and then I have created permissions from this. Each permission has a resource that it links to and 1 or more values, like:
Resource = Page, Permissions = Add, Update, View, Delete
Another complication is that the groups have dynamic names, and dynamic permissions!!
I have started to read about authorization in ASP.net5 and it seems that I have found something called Policies, which sound good. It seems to force you to use Claims, which is possible if I use a ClaimsTransformer to get all my permissions and add them as claims from the Db. But am I right in thinking that I would have to create a policy for each Permission, on each resource? That seems like a lot of setup.
Is there anything that I do not know about is already built in ASP.net5 that I could use? Like an attribute like this
[Authorize("Page", "Delete")]
Which I could add to the PageController Delete method.
If I have to use some sort of service and DI that into the controller to implement this, then that would be fine as well.
There is a ClaimsPrincipalPermissionAttribute that can fit to your requirements.
Or you can implement your own AuthorizeAttribute.
I use AspNet.Security.OpenIdConnect.Server for authorization. But you can also have a look at OpenIddict
In any case you can add the Authorize attribute to any method you want like this
[Authorize(Roles = "Administrator,SimpleUser,AnOtherRole")]
public void MyMethod() {}
Resource based authorization might fulfill your needs, but I am a little confused with the page being the resource, rather than what the page acts upon.
Taking your Page/Delete combination, I would imagine that rather than the resource being Page, your Page Delete action takes a parameter, indicating the page that is to be deleted? (If this is not the case then this approach isn't going to work of course)
In this case you'd do something like
[Authorize]
public class PageController : Controller
{
IAuthorizationService _authorizationService;
public PageController(IAuthorizationService authorizationService)
{
_authorizationService = authorizationService;
}
public Delete(int pageId)
{
var page = pageRepo.GetPage(pageId);
if (await authorizationService.AuthorizeAsync(User, page, Operations.Delete))
{
return View(page);
}
else
{
return new ChallengeResult();
}
}
}
In order to enable this you're write a handler based on page and an Operations requirement (or any old requirement, but a parameterized operations requirement means you can write a single handler and branch accordingly).
We tried very hard to move away from putting data in the attribute, and move it into requirements, because data in attributes is, to be frank, a maintenance nightmare.
One other thing to note; as handlers are resolved through DI you could inject your user to permissions resolver into the handler, which would avoid using claims transformation.
ASP.NET provides authentication mechanism out of the box which is easy to use, example:
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
ViewBag.Message = "This can be viewed only by authenticated users only";
return View();
}
[Authorize(Roles="admin")]
public ActionResult AdminIndex()
{
ViewBag.Message = "This can be viewed only by users in Admin role only";
return View();
}
}
Check this tutorial
Or if you want more sophisticated mechanism you can implement your own memberhsip provider based on the ASP.NET Membership Provider

Dealing with Session timeout in ASP.NET MVC

I am working on a MVC application and I have a requirement of dealing with errors and session timeouts by redirecting the user to different error pages based on few parameters in the query string.
The issue I am facing is that i tried to implement this by saving the required parameters from querystring into a session and then redirecting to error pages. But before every HttpGet and Post action in my controllers I am checking if session is active.
So in case of a situation where session values are lost and not able to read them.
How can I implement this thing in any other way?
You need to check whether the session exists, has the fields you expect and is active. If the session does not exist or does not have a fields you expect, then handle the case when the session does not exist yet/expired. If it is not active, then handle the case when the session is no longer active. If everything is ok, then handle the request normally. If the session expired, then handle it as expired.
to check about session, you can use an ActionFilter like this:
public class SessionActiveFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var activeSession = Session["user"];
if (activeSession == null)
//Here, do a redirect
base.OnActionExecuting(filterContext);
}
}
Also, you can use a third option to save the session, like Redis Cache http://blogs.msdn.com/b/webdev/archive/2014/05/12/announcing-asp-net-session-state-provider-for-redis-preview-release.aspx
I know this is a dead story now. But I post this answer for the new comers. Please see the nice tutorial in codeproject about how to check session values in Action Filters.
In a dynamic web application, the session is crucial to hold the information of current logged in user identity/data. So someone without authentication cannot have access to some Page or any ActionResult, to implement this kind of functionality, we need to check session exists (is not null) in every action which required authentication.So, the general method is as follows:
[HttpGet]
public ActionResult Home()
{
if(Session["ID"] == null)
return RedirectToAction("Login","Home");
}
We have to check the above 2 statements each time and in each ActionResult, but it may cause 2 problems.
Repeat Things: As per the good programming stranded, we don't have to repeat the things. Create a module of common code and access it multiple times/repeatedly
Code missing: We have to write code multiple times so it might happen some time we forget to write code in some method or we missed it.
How To Avoid?
The ASP.NET MVC provides a very great mechanism i.e., Action Filters. An action filter is an attribute. You can apply most action filters to either an individual controller action or an entire controller.
If you want to know more about action filter, please click here.
So we will create a custom Action Filter that handles session expiration and if session is null, redirect to Login Action.
Create a new class in your project and copy the following code:
namespace YourNameSpace
{
public class SessionTimeoutAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
if (HttpContext.Current.Session["ID"] == null)
{
filterContext.Result = new RedirectResult("~/Home/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}
}
Now our Action Filter is created and we are ready to use it. The following code will show you how we can apply attribute to Action or to complete controller.
Apply to Action
[HttpGet]
[SessionTimeout]
public ActionResult MyProfile()
{
return View();
}
Apply to Controller
[SessionTimeout]
public class HomeController : Controller
{
}
Now all actions of Home Controller will check for session when hit with the help of Action Filter. So we have reduced the code and repetitive things. This is the benefits of Action Filters.

How to perform fine grained access control in an asp.net MVC application.

How is everyone else performing fine grained access control in an MVC app? i.e. a user may be related to multiple objects and have different access requirements to each object. Can this be achieved using asp.net identity claims / roles? or do I have to role out my own?
Is there any design pattern I can follow if I need to roll out my own?
No doubt there are plenty of ways to do this, but asp.net-mvc leads itself to extensibility of the AuthorizeAttribute, eg:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class ActionPermissionAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// Override OnAuthorization, not AuthorizeCore as AuthorizeCore will force user login prompt rather than inform the user of the issue.
var controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
var action = filterContext.ActionDescriptor.ActionName;
bool authorised = ... // Check permissions here
if (!authorised)
throw new UnauthorizedAccessException("You are not authorised to perform this action.");
base.OnAuthorization(filterContext);
}
}
this can be applied to the controller (or as base controller) so doesn't need to be on every single action.
The actual check permissions can be as simple or complicated as you want - eg store controller + action + active directory group in a database will allow the permissions to be changed dynamically.

Categories

Resources