kristofferahl / FluentSecurity

Fluent Security configuration for ASP.NET MVC
MIT License
163 stars 47 forks source link

IsInRoleFrom #50

Closed mdmoura closed 11 years ago

mdmoura commented 11 years ago

Hello,

Could a IsInRole be added to FluentSecurity? For example:

x.IsInRoleFrom(() => HttpContext.Current.User.IsInRole);

This would be a good way to avoid a round trip to database when using Forms Authentication.

This could be used in a custom policy ... Or maybe even in the RequireRole policy ...

Thank You, Miguel

chandu commented 11 years ago

@shapper Can you please provide a use case so that it clear as to how/when this would be used?

mdmoura commented 11 years ago

When using Forms Authentication the IPrincipal is defined on Authentication Module as follows: HttpContext.Current.User = new GenericPrincipal((FormsIdentity)HttpContext.Current.User.Identity, _service.GetUserRoles(user));

Then on a controller, attribute, view or anywhere else you can use the following: HttpContext.Current.User.IsInRole("Admin")

So isn't FluentSecurity doing a redundant database call to get all roles?

Using the existent GetRolesFrom I did the following: x.GetRolesFrom(() => { return new [] { "Admin", "Coll", "Memb" }.Where(y => HttpContext.Current.User.IsInRole(y)).ToList(); });

This avoids the call to the database ... Maybe not elegant but ...

kristofferahl commented 11 years ago

I haven't tried this myself but something like this should work as well.

configuration.GetRolesFrom(() => Roles.GetRolesForUser(HttpContext.Current.User.Identity.Name));

I don't think we'll be adding anything specific for IPrincipal and roles. I want to keep it as loosely coupled as possible so I'm hoping the above is a good enough solution to your problem. Let me know what you think!

mdmoura commented 11 years ago

Yes, it makes sense to keep it loosely ... I was trying to figure the best way to do this.

I will probably keep using my suggestion:

x.GetRolesFrom(() => { return new [] { "Admin", "Coll", "Memb" }.Where(y => HttpContext.Current.User.IsInRole(y)).ToList(); });

Your suggestion is good to but I am not using Roles Provider. I am using only Forms Authentication.

kristofferahl commented 11 years ago

OK, I did not know that only worked for RolesProvider. Will keep that in mind moving forwad. Thanks!