【问题标题】:Shiro: Handling Exceptions thrown by annotationsShiro:处理注释抛出的异常
【发布时间】:2012-08-05 11:46:52
【问题描述】:

我正在使用 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>

【问题讨论】:

    标签: java spring spring-mvc shiro


    【解决方案1】:

    看起来您正在使用 Spring。我在 SpringMVC 中通过在控制器中提供一个 ExceptionHandler 来处理这个问题。

        @ExceptionHandler(TheSpecificException.class)
        protected ModelAndView handleSpecificException(ApplicationException e, HttpServletRequest request)
        {
           // code to handle view/redirect here
        }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        在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>
        

        【讨论】:

          猜你喜欢
          • 2014-01-07
          • 2013-05-27
          • 2020-06-12
          • 2013-07-24
          • 1970-01-01
          • 1970-01-01
          • 2011-10-10
          • 2011-11-23
          • 1970-01-01
          相关资源
          最近更新 更多