1

I want to restrict some pages on my site depending on user permissions saved in the database.

The error will originate in the service/data access layer.

I have discovered that if I throw an UnauthorizedAccessException then the status code returned by the asp.net pipeline is 401, which results in a YSOD instead of going to the MVC custom error page.

From reading around it seems that I need to be returning 403 error instead. I have created a custom exception type to use in place of UnauthorizedAccessException. How do I configure MVC to return 403 response on this error? How do I then set the filter to redirect to my custom forbidden page on this error? Am I taking the correct approach?

5
  • One way which I handled 403 was; in Application_Error after all logging etc., check the error code, if it is 403, redirect it to 403 action in Errors controller which shows a nice custom view for 403 erros.
    – Yahya
    May 19, 2014 at 9:12
  • Will watch this space for better ideas.
    – Yahya
    May 19, 2014 at 9:13
  • @Yahya but how to force MVC to interpret error as 403 status? May 19, 2014 at 10:09
  • Have you had a look at this? stackoverflow.com/a/2578795/125740
    – Yahya
    May 19, 2014 at 11:20
  • Your custom exception type should inherit from UnauthorizedAccessException.
    – Rudey
    Oct 2, 2018 at 13:16

1 Answer 1

0

Maybe you could consider Authentication build into asp.net MVC... The thing is that you can just add [Authorize] attribute to your controller or [Authorize(Users="Alice,Bob")] for users and [Authorize(Roles="Administrators")] for groups.

Link to MSDN article for reference. And a tutorial for auth in mvc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.