SpringBoot3 集成 Shiro
Spring Boot 3 整合 Shiro 的步骤大致如下:
- 添加依赖:在
pom.xml
中添加 Shiro 和 Spring Boot 的相关依赖。
<dependencies>
<!-- Shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.8.0</version>
</dependency>
<!-- 其他依赖 -->
</dependencies>
- 配置 Shiro:在
application.properties
或application.yml
中配置 Shiro。
# Shiro 配置
shiro.sessionManager.globalSessionTimeout = 86400000
shiro.unauthorizedUrl = /unauthorized
- 创建 Shiro 配置类:配置 ShiroFilterFactoryBean,Realm 等。
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 配置登录请求
shiroFilterFactoryBean.setLoginUrl("/login");
// 配置权限不足时跳转的页面
shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
// 定义访问权限
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/admin/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(customRealm());
return securityManager;
}
@Bean
public CustomRealm customRealm() {
return new CustomRealm();
}
}
- 创建 Realm 类:实现用户认证和授权。
public class CustomRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
// 获取用户信息
// 设置角色和权限
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addRole("admin");
simpleAuthorizationInfo.addStringPermission("user:delete");
return simpleAuthorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
// 实现认证逻辑
UsernamePasswordToken token = (
评论已关闭