Using Authorize attribute i may specify roles which is allowed to access the resources.
[Authorize(Roles="User")]
But if i have admin user which is allowed to go to any resource i need specify this one as well
[Authorize(Roles="User, Administrator")]
But may be there is some way i can say somehow that Administrator allowed to go anywhere and not to specify this one in Authorize attribute?
So i mean if somewhere in code(on controller or on action) would be this [Authorize(Roles="User")] it means that Administrator role allowed to go there as well.
Or may be i may set it to all Authorize roles dynamically how when application start?
Any ideas?
UPDATED:
Currently i have one admin controller with Authorize attribute [Authorize(Role="Administrator")] and i have some actions in some another controllers with attributes [Authorize(Role="User")] so i will need to add "Administrator" there as well if i didn't find better solution.
I think this will work for you. Create your own base controller, with the AuthorizeAttribute, then make your other Controllers inherit your base class.
[Authorize(Roles="Admin")]
public class MyFancyController : Controller
{
}
[Authorize(Roles = "TaxPayer")]
public class WizardController : MyFancyController
{
...
This is scary though, in my opinion.
How many controllers/Actions do you have? What if you forget about this later and maybe you have a page you don't want Admins to access?
Will debugging the code become more difficult?
[Authorize(Roles = "User, Admin")]
public class PrestamosController : Controller
{
// controller details
}
You can create a custom filter and use it to decorate your Actions or Controllers with it.
This is a simple structure I've used quite a lot:
public class AuthorizationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
return;
}
var actionName = filterContext.ActionDescriptor.ActionName;
var controllerName = filterContext.Controller.GetType().Name;
bool isAuthorized =false;
// Put your logic here !!!!
if (!isAuthorized) {
filterContext.Result = new HttpUnauthorizedResult();
return;
}
}
}
You can read some more here
This is what I do: make sure users who are in the "Admin" role are also in the "User" role.
You need the concept of Static Role and Runtime Role. Here is a simple example:
Your role list and their levels:
Role: Admin | Level: 1
Role: Editor | Level: 2
Role: Viewer | Level: 3
Users and their Static Role (Static Role is the role you assigned to users):
User: John | Role: Admin
User: Sam | Role: Editor
User: Peter | Role: Viewer
At run time you generate a Run Time Role by using Static Role and Role Levels, Users with higher level of roles automatically obtain the roles in lower levels. So, after calculation, the Run Time Roles for these Users will be:
User: John | Role: Admin, Editor, Viewer
User: Sam | Role: Editor, Viewer
User: Peter | Role: Viewer
And then, you can simply use [Authorize(Roles="Viewer")], Users with higher Level of permissions (e.g. John, Sam) can access to it too. Because they must also have the Viewer role at run time.
The point of using Static Role and Run Time Role is that Static Role makes the role assignment easier. And Run time role make the resources authorization easier.
Related
I want to develop dynamic roles authorization using .net core webAPI, my structure is that user have one role and the role have some function or features to access
my question is there is any way yo get the function name where authorization policies applied
as example I have the following code
[Authorize(Roles = "Admin", Policy = "isHasPermission")]
public async Task<IActionResult> GetAllAsync()
{
var users = await _userService.GetAllAsync();
var userDtos = _mapper.Map<IList<UserDto>>(users);
return Ok(DataMessage.Data(new { users = userDtos }));
//return Ok(userDtos);
}
and my policy is something like that
protected override async Task HandleRequirementAsync(
AuthorizationHandlerContext context,
isHasPermissionRequirement requirement)
{
/*
CAN I GET THE FUNCTION NAME "GetAllAsync" HERE!
TO VALIDATE IF IT IS ONE OF USER'S FEATURE
*/
return await Task.CompletedTask;
}
So that I need to get the function name in the policy to validate user's permissions, if it is possible or not?
You are doing it backwards: The way policies work is that you say that a certain action has requirements. It is not a valid requirement to then circle back to where the policy is used. Policies should be completely separate from what you are trying to access. If a certain thing specifies a policy, then just the presense of the policy should be all that’s necessary.
If you want to have your logic actually check what you are trying to access, then you could look into authorization filters instead. When they are called, they pass an AuthorizationFilterContext which also contains information about the route and action the user is trying to access. With that, you can get the action name for example using (context.ActionDescriptor as ControllerActionDescriptor).ActionName.
Member have many jobs. A member can add, delete or update Jobs. Currently there are actions (add, delete or update) defined in a controller which are called through jQuery.ajax(). We are sending job id and member id to perform the operation. Member id is necessary because there is a role admin who can modify the job on behalf of members, so we need to identify the member. But sending member id is dangerous as anyone can send the request by modifying the member id.
I know, we can add constraint do restrict that only admin can modify the jobs or a member can modify only his jobs. My question is, Do I need to add these constraints in the action of the controller or Is there any Grails way to do that. I have google, the same thing is handled in Ruby and Rails by using routes. And in grails I have skim through RESTful URL mapping, which is perhaps used for this purpose.
Can anyone points me to right direction, thanks. I am using Grails 2.1.1.
You can implement some realization of AbstractPersistenceEventListenerService to not allow perform actions with entity that constains id of not logged in user. Example:
class MultiTenantPersistenceEventListenerService extends AbstractPersistenceEventListenerService {
def springSecurityService
#Override
protected AbstractPersistenceEventListener createPersistenceEventListener(Datastore datastore) {
return new MultiTenantPersistenceEventListener(datastore)
}
}
class MultiTenantPersistenceEventListener extends AbstractPersistenceEventListener {
MultiTenantPersistenceEventListener(final Datastore datastore) {
super(datastore)
}
#Override
protected void onPersistenceEvent(AbstractPersistenceEvent event) {
def entity = event.getEntityObject() // could be your Job domain entity
def user = springSecurityService.getCurrentUser() //current logged in user
if(entity.hasProperty('userId')){ // every job belongs to User
if(entity.userId != user.id){
throw new AccessDeniedException("Acces Denied !")
}
}
}
}
I'd recomment to use grails spring-security-plugin. There is a lot of information in web about plugin and it's easy configurable. Plugin allows you to perfrom controller's action in secure way. For example:
#Secured(['ROLE_USER'])
def followAjax = { ... }
#Secured(['IS_AUTHENTICATED_REMEMBERED'])
def personal = { ... }
For more information - plugin and spring-security with grails.
You can use Authorize attribute to authorize the user,
e.g
[CustomAuthorize(Roles=SiteRoles.Admin|SiteRoles.HelpDesk)]
public ActionResult Index()
{
return View();
}
This is a nice approach for making website secure.
go through these link, this will help you.
custom authorization with asp.net mvc
asp.net mvc authorization
I am working in MVC3. I have created 3 roles: Administrator,Manager and Staff and have manager1 and manager2 in manager role. I want to give add,edit,view,delete privilege to manager. I don't want to give delete privilege to manager1. Can i override the rights of user over roles?If yes please tell me how to do it using membership class?Any good articles on providing privileges?
Use the deny technique..
public class DenyAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return !base.AuthorizeCore(httpContext);
}
}
use this like authorizeattribute only.
first, membership providers doesn't provide any priveleges, they just stores account, profile, roles.
access to some actions you can give to roles and/or users, setting attibute [AuthorizeAttribute(Roles = "role1", Users = "manager2")] on controllers and actions. so using these technic you can extend priveleges for manager2.
I am making a web application using asp.net mvc 3, which has login also.
There are 3 different types of users who will be using the site: Administrator, Operator & Distributor.
How can I create a login that restricts a Distributor from accessing Administrator's & Operator's part of the website. Similarly an Operator should not be able to access Administrator & Distributor part. Also Administrator should not be able to access other type of user's part. i.e. the site should redirect an Administrator type of user to his own part of website after login.
And finally no one should able to access their own part of website without login.
Please could anyone help me.
Look into the membership model of ASP.NET. This model is used to authenticate and authorize users for different parts of your web application.
With the membership model, define three roles within your application: Administrator, Operator and Distributor. Of course, also create users within your application and divide them over these roles.
Last up is the actual authentication and authorization. Use the Authorize attribute to define which role a user must have to access a certain part of your website.
[Authorize(Roles = "Operator")]
public ActionResult OperatorOnlyStuff()
{
return View();
}
And to make sure users should be logged in to even access anything on your site, define a custom authenticated route constraint.
public class AuthenticatedRouteConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return httpContext.Request.IsAuthenticated;
}
}
And use this custom authenticated route constraint in your default route:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { isAuthenticated = new AuthenticatedConstraint()}
);
Is there an integrated way in asp.net mvc 3, to permit authentification and actions based on the time of the day ?
For example, if it's 18:00 o'clock, users that belong to a specific role are not allowed to log in or if they are already authenticated, they will be automatically logged out or not being able to do actions.
I guess in the log in method I could check for user role and time of day and then on each action, I will also check for role and time of day and permit but is there and easier way to accomplish this ?
UPDATE:
I guess there is no easier way to just set the time and user/roles so I ended up implementing the answer(solution).
You could write a custom Authorize attribute and override the AuthorizeCore method in which you would perform the necessary check:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
return false;
}
// At this stage standard authorization passed =>
// you could now check the user roles in the database
// and the time of the day and return true or false from here
...
}
}
and now all that's left is decorate your controllers/actions with this custom attribute.