Shiro: handling annotation exceptions

I use Shiro annotations to verify authorization as follows:

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

My question is this: if the user does not have the permissions required by the annotation, an exception is thrown. I would prefer to redirect the user to a different URL in case of an exception. How to do it?

Here is my 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> 
+8
java spring spring-mvc shiro
source share
3 answers

It looks like you are 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 } 
+1
source share

Without Spring MVC, you can also 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(); } } 
+1
source share

add configuration to 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> 
0
source share

All Articles