我正在使用Shiro注释来检查这样的授权:
@RequiresPermissions("addresses:list")
public ModelAndView getCarrierListPage() {
return new ModelAndView("addressList", "viewData", viewData);
}
我的问题是:如果用户没有注释所需的权限,则会抛出异常。如果发生异常,我宁愿将用户重定向到其他URL。我该怎么做?
这是我的shiro过滤器配置:
<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>
答案 0 :(得分:1)
看起来你正在使用Spring。我在SpringMVC中通过在控制器中提供ExceptionHandler来处理它。
@ExceptionHandler(TheSpecificException.class)
protected ModelAndView handleSpecificException(ApplicationException e, HttpServletRequest request)
{
// code to handle view/redirect here
}
答案 1 :(得分:1)
没有Spring MVC,你也可以使用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();
}
}
答案 2 :(得分:0)
在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>