【问题标题】:Mapping Shiro exceptions at the service layer在服务层映射 Shiro 异常
【发布时间】:2025-12-06 18:25:02
【问题描述】:

我正在使用 Spring 3.2.3 和 Shiro 1.2.0 来保护对服务的访问。这可行,但会导致引发特定于 Shiro 的异常。我想抛出一个特定于应用程序的异常。这是否可能,无论是使用 Shiro 还是 Spring 级别的映射?我知道我可以使用 Spring 将控制器异常映射到视图,但我不确定如何在服务层处理它。我的设置:

服务接口:

public interface CaseService {
  Case getCase(Integer id);
}

服务实现:

@Service
public class CaseServiceImpl implements CaseService {
  @RequiresAuthentication
  public Case getCase(Integer id) {
    // ...
  }
}

在没有经过身份验证的主题的情况下测试上述内容时,我确实收到了预期的异常,但它是 org.apache.shiro.* 异常。我尝试使用 Spring 的 @ExceptionHandler 来处理 Shiro 异常。它没有效果,但我认为它需要在控制器层工作。

【问题讨论】:

  • 出于好奇,你为什么不选择 Spring Security 而不是 Apache Shiro?
  • 我开始在以前的项目中使用 Spring Security,但无法让它工作(我不再记得这个问题了)。我试过 Shiro 并且很容易让它工作,所以现在我更熟悉它了。当我有时间时,我可能会再看看 SS,但到目前为止,我已经能够对 Shiro 做我想做的事情,除了自定义例外。

标签: spring spring-mvc shiro


【解决方案1】:

如果没有理由您绝对需要使用 @RequiresAuthentication 注解,您可以调用以下自定义实用程序类来返回您需要的异常。

public class UserAuthenticationUtil {
  /**
   * Check that the current user bound to {@link ThreadLocal} is authenticated.
   * @throws ApplicationSpecificException If the current user is not authenticated.
   */
  public static void checkUserAuthenticated () throws ApplicationSpecificException {
    if (!SecurityUtils.getSubject().isAuthenticated()) {
      throw new ApplicationSpecificException("User is not authenticated!");
    }
  }
}

Here is the code/class 处理 @RequiresAuthentication 注释,如果你想验证它是相同的逻辑。 Here is the API documenation 也是。

【讨论】:

  • 谢谢,贾斯汀。这是个好主意。使用实用程序类在应用程序代码中占用相同数量的行,并让我能够控制异常。