Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shiro: Handling Exceptions thrown by annotations

I am using using Shiro annotations to check for authorization like this :

@RequiresPermissions("addresses:list")
    public ModelAndView getCarrierListPage() {
        return new ModelAndView("addressList", "viewData", viewData);
    } 

My question is this : If the user doesn't have permissions as required by the annotation, an exception is being thrown. I would rather like to redirect user to a different URL in case of an exception. How do I do that?

Here is my shiro filter configuration :

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"/>
    <property name="loginUrl" value="/showLoginPage"/>
    <property name="filterChainDefinitions">
    </property>
</bean>
like image 809
simplfuzz Avatar asked Aug 08 '12 11:08

simplfuzz


2 Answers

It looks like you're using Spring. I handled this in SpringMVC by providing an ExceptionHandler in the controller.

    @ExceptionHandler(TheSpecificException.class)
    protected ModelAndView handleSpecificException(ApplicationException e, HttpServletRequest request)
    {
       // code to handle view/redirect here
    }
like image 52
Jeff Avatar answered Sep 30 '22 18:09

Jeff


Without Spring MVC you also can use ExceptionMapper:

@Provider
@Component
public class GenericExceptionMapper implements ExceptionMapper<ShiroException> {

    @Override
    public Response toResponse(final ShiroException ex) {
        return Response.status(ex instanceof UnauthenticatedException ? Response.Status.UNAUTHORIZED : Response.Status.FORBIDDEN)
                .entity(ex.getMessage())
                .type(MediaType.TEXT_PLAIN_TYPE)
                .build();
    }

}
like image 40
Vladislav Bauer Avatar answered Sep 30 '22 20:09

Vladislav Bauer