3

I'm using the Authorize attribute to filter controller actions based on user roles, but if an unauthorized action is attempted, the user is redirected back to the login page. As I user I would find this confusing and irritating.

How can I instead show an error message informing the user they need certain roles, and remain on the view where they attempted an action?

2 Answers 2

2

You will need to write a custom Authorize attribute which doesn't return a HttpUnauthorizedResult. Also remaining on the same view will be a difficult task as you might need to keep all the context after the request.

Sign up to request clarification or add additional context in comments.

6 Comments

Ouch! Could I maybe return a custom HttpUnauthorizedResult that is routed to an error view, rather than the login view, and provide an ActionLink on the error view back to the starting view?
Writing a cusom 'Authorize' attribute is a lot easier than you think, and it is the cleanest way to deal with your situation, and it is also re-useable throughout your project.
@Profk, if you want to be routed to an error view either Response.Redirect, or return ViewResult inside the filter.
@Saajid, I'm it is quite easy, but I always think too much, like redirecting back to the original view with some kind of directive to display a model popup with error advice. I'll stick to an error view for now.
@Darin, I'm afraid I have now idea where to begin implementing your suggestion. I know it's in my custom attribute, but how would I do Response.Redirect, or, how would my Viewresult return know where to go?
|
0

The solution I found so far is you need to save a session for the current page in _ViewStart (maybe something else in MVC2), then use that in your custom authorization class to redirect to the page and show the message.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.