8

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>
simplfuzz
  • 12,479
  • 24
  • 84
  • 137

3 Answers3

1

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
    }
Jeff
  • 3,549
  • 1
  • 14
  • 11
1

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();
    }

}
Vladislav Bauer
  • 952
  • 8
  • 19
0

add configuration in spring-servlet.xml:

<beans:bean
    class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <beans:property name="exceptionMappings">
        <beans:props>
            <beans:prop key="org.apache.shiro.authz.UnauthorizedException">/403</beans:prop>
            <beans:prop key="org.apache.shiro.authz.AuthorizationException">/login</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>
vivia
  • 2,983
  • 1
  • 13
  • 8