This project is read-only.

Custom security Implementation using attributes

Topics: Core, Customizing Orchard
Apr 2, 2013 at 4:13 PM
I have been trying to implement custom security and met some problems.
Basically i need security for employees grouped up it teams, team leaders etc. (Employee is authorized to see only his data on website, TeamLead is authorized for all employees in his team and so on)
I have content and non-content types in my custom module.
For Content items i can implement custom IAuthorizationServiceEventHandler to handle custom authorization logic.
For non content items it is a bit complicated.

Generally approach is use custom AuthorizeAttribute implementation and place all code there.
For me problem here is using my database Repositories. I can't hook up Autofac Dependency Injection to the code of this Attribute implementation and so i can't retrieve user/employee data and relations and respective Team data.

I have also tried to use AuthorizationFilterAttribute from Skywalker's blog to resolve WorkContext and use DI this way, but with this approach i don't know how to retrieve respective User Identity that is used to call action.

Attribute looks like this
[ResourceAuthorize(Level = AuthorizationLevels.OwnerOrAdministrator, Key = "id")]
public ActionResult ListByEmployee(int employeeId)

class ResourceAuthorizeAttribute : AuthorizeAttribute, IDependency

In AuthorizeCore method of attribute i need to use some custom logic to check for user roles, team etc.

Please suggest me approach for resolving this custom security issues.
Probably i should use something else not custom attributes?
Apr 13, 2013 at 3:10 PM
DobrYaroslav wrote:
with this approach i don't know how to retrieve respective User Identity that is used to call action.
Perhaps I'm misunderstanding, but if you have the WorkContext, you can access the current user, right?
Apr 17, 2013 at 10:26 AM
Tnx for the answer. You are right, i can access current user from WorkContext, i just had not enough time to dig down to it before the vacation. Now when i have some more understanding in this field i've started to think that AuthorizationFilterAttribute can't be a solution in my case, because it's used for ApiControllers only and i can't return common View for them(if i understand it correctly).
So the question here stays. How can i handle this custom authorization logic without completely rewriting everything from scratch?
Apr 17, 2013 at 10:43 AM
For "regular" (non-api) controllers you can use attributes that implement IAuthorizationFilter.
IAuthorizationFilter.OnAuthorization receives a context variable that exposes an ActionResult called Result, which you can set to any ActionResult you like, including a view, redirect, etc.
Apr 17, 2013 at 12:29 PM
Thank you very much, that helps a lot.
It works like that perfectly.