Domanda

I have a method in my resource with @RequiresGuest annotation. When logged in user hits the link it rightfully throws an UnauthenticatedException with this message

Attempting to perform a guest-only operation. The current Subject is not a guest (they have been authenticated or remembered from a previous login). Access denied.

But how do I handle it? How do I, for example, redirect the request to logout page?

È stato utile?

Soluzione

This is usually dependent upon your chosen MVC framework:

  • Some UI mechanisms (e.g. JSP) allow you to have an 'error page' that you can use to process any exception.
  • More elegant UI frameworks have 'catch all' exception handlers and/or controllers that allow you to do anything you want (inspect the exception, set an HTTP status code, redirect the end user to an error page specific to that particular problem, etc).

However, if you do not wish to use an MVC mechanism for this, it is possible to create a Servlet Filter that would do this:

The filter would execute the FilterChain in a try/catch block, catching an AuthorizationException. If it catches one, it issues a 302 redirect to an 'unauthorizedUrl'.

The reason Shiro's existing filters do not do this is because they authorize the Subject before ever invoking the FilterChain: if the Subject does not meet authorization criteria, the filter chain is never even invoked (and therefore there is no AuthorizationException to catch).

If you would like to see alternative behavior in Shiro, please file an issue and discuss it as a potential new feature.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top