Reputation: 5409
I've been tasked to create a custommembership provider for our methods for our MVC 4.0 project.
Based on a attribute ([Authorize]
?) it has to spot whether the attempted user is allowed to use the method or not.
Currently i've got this:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class TestAuthorize : CodeAccessSecurityAttribute
{
public TestAuthorize(SecurityAction action)
: base(action)
{
}
public override IPermission CreatePermission()
{
throw new NotImplementedException();
}
}
When I add
return new PrincipalPermission(null,null,true)
I expect the permission to be valid and the user has access to the method.
When I add
return new PrincipalPermission(null.null,false)
I expect the permission to be invalid and the user will be denied access to the method.
However, It only stops from continuing when I use a throw new SecurityException("You are denied access")
which also forces the MVC application to stop unless this exception is handled at client side (using a try catch).
Is it possible for us to handle this exception in our MVC project?
as an example of what we wish to have done by use of attributes:
[TestAuthorize(SecurityAction.Demand)]
public List<string> GetList()
{
//if access, return new List();
//if no access, return null;
}
Upvotes: 1
Views: 299
Reputation: 7140
Pretty sure you want to be inheriting from AuthorizeAttribute
here, not CodeAccessSecurityAttribute
. In your attribute, you override AuthorizeCore
and simply return true
if the user should be allowed to continue, and false
if they're not authorised to do whatever it is that method does. A false
result will trigger a HTTP-401 Unauthorised
response, which ASP.NET automatically handles by redirecting the user to the login page so they can log in as someone with the right access, although you can change this behaviour if you wish.
In fact, you might not even need to create your own attribute; if you're using the existing ASP.NET MVC mempership provider, or you can get whatever you're using to play nice with it, then the existing AuthorizeAttribute
will work for you.
Upvotes: 1