我正在尝试集成 Spring Boot 和 Shiro。当我尝试调用SecurityUtils.getSubject()
时在我的一个 Controller 中,发生了异常:
org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration.
我刚刚按照一些教程和文档来配置 Shiro,这是我的 ShiroConfig
类:
@Configuration
public class ShiroConfig {
@Bean
public Realm realm() {
return new UserRealm();
}
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName(PasswordEncoder.getALGORITHM());
hashedCredentialsMatcher.setHashIterations(PasswordEncoder.getITERATION());
return hashedCredentialsMatcher;
}
@Bean
public UserRealm shiroRealm() {
UserRealm userRealm = new UserRealm();
userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return userRealm;
}
@Bean
public SessionsSecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(shiroRealm());
return securityManager;
}
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
defaultAdvisorAutoProxyCreator.setUsePrefix(true);
return defaultAdvisorAutoProxyCreator;
}
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
definition.addPathDefinition("/login", "anon");
definition.addPathDefinition("/register", "anon");
definition.addPathDefinition("/api/**", "user");
return definition;
}
}
这是导致异常的代码:
@PostMapping("/login")
@ResponseBody
public Object login(@RequestParam("username") String username,
@RequestParam("password") String password) {
if (username.equals("") || password.equals("")) {
return "please provide complete information";
}
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
Subject subject = SecurityUtils.getSubject(); // this line caused exception
...
}
我对这个异常感到非常困惑。有人可以帮忙吗?
编辑 我正在使用 Spring Boot 2.1.6.RELEASE 和 shiro-spring-boot-starter 1.4.0。
最佳答案
您是否使用 shiro-spring-boot-web-starter 依赖项而不是 shiro-spring-boot-starter 依赖项?
根据此文档,这似乎是 Spring Boot Web 应用程序所必需的。
https://shiro.apache.org/spring-boot.html#Spring-WebApplications
关于java - Shiro 调用代码无法访问 SecurityManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56678301/