Spring Boot 3 和 JDK 17 的组合尚未广泛可用,因为 Spring Boot 3 是基于 Java 17 的发布候选版本。Spring Boot 2.5.x 是最后支持 Java 8 的 Spring Boot 版本。
考虑到这一点,我将提供一个示例配置,展示如何在 Spring Boot 2.5.x(最接近 Spring Boot 3 的稳定版本)中使用 Shiro 和 JWT 以及 Redis。
@Configuration
public class ShiroConfig {
@Bean
public Realm realm() {
// 配置 Realm 用于身份验证
return new MyRealm();
}
@Bean
public DefaultWebSecurityManager securityManager(Realm realm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm);
return securityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 配置 Shiro Filter 规则
return shiroFilterFactoryBean;
}
}
public class MyRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
// 实现认证逻辑
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
// 实现授权逻辑
}
}
@Configuration
public class JwtConfig {
@Value("${jwt.secret}")
private String secret;
@Bean
public JWTTokenFilter jwtTokenFilter() {
return new JWTTokenFilter();
}
// 其他 JWT 配置 Bean
}
public class JWTTokenFilter extends AuthenticatingFilter {
@Override
protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
// 实现 JWT 登录尝试检测逻辑
}
@Override
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
// 实现创建 JWT Token 逻辑
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
// 实现访问拒绝时的逻辑
}
}
@Configuration
public class RedisConfig {
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
return new LettuceConne