gpt4 book ai didi

java - Shiro No SecurityManager 调用代码可访问

转载 作者:行者123 更新时间:2023-11-29 04:08:28 27 4
gpt4 key购买 nike

我正在尝试集成 Spring Boot 和 Shiro。当我尝试在我的一个 Controller 中调用 SecurityUtils.getSubject() 时,发生了异常:org.apache.shiro.UnavailableSecurityManagerException:调用代码无法访问 SecurityManager,绑定(bind)到 org.apache.shiro.util.ThreadContext 或作为 vm 静态单例。这是无效的应用程序配置。

我只是按照一些教程和文档来配置 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 No SecurityManager 调用代码可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56678301/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com