springboot整和jwt、shiro、redis
时间: 2023-11-14 17:07:15 浏览: 126
Spring Boot可以集成JWT、Shiro和Redis来实现身份认证和授权,以下是一个基本的实现步骤:
1. 集成JWT
添加依赖
```
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
```
创建JWT工具类
```
public class JwtUtils {
private static final String SECRET_KEY = "jwt_secret_key";
private static final long EXPIRATION_TIME = 864_000_000; // 10天
public static String generateToken(String subject) {
return Jwts.builder()
.setSubject(subject)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}
public static String getSubject(String token) {
try {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getSubject();
} catch (JwtException e) {
return null;
}
}
}
```
使用JWT进行身份认证
```
@RestController
@RequestMapping("/api")
public class UserController {
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
// 验证用户名密码
if (userValid(loginRequest.getUsername(), loginRequest.getPassword())) {
String token = JwtUtils.generateToken(loginRequest.getUsername());
return ResponseEntity.ok(new JwtResponse(token));
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
@GetMapping("/user")
public ResponseEntity<?> getUser(@RequestHeader("Authorization") String authHeader) {
String token = authHeader.substring(7);
String subject = JwtUtils.getSubject(token);
if (subject != null) {
User user = getUserByUsername(subject);
return ResponseEntity.ok(user);
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
}
```
2. 集成Shiro
添加依赖
```
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>1.7.1</version>
</dependency>
```
配置Shiro
```
@Configuration
public class ShiroConfig {
@Bean
public Realm realm() {
return new UserRealm();
}
@Bean
public DefaultWebSecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm());
return securityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean() {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager());
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/api/login", "anon");
filterChainDefinitionMap.put("/api/logout", "logout");
filterChainDefinitionMap.put("/api/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
chainDefinition.addPathDefinition("/api/login", "anon");
chainDefinition.addPathDefinition("/api/logout", "logout");
chainDefinition.addPathDefinition("/api/**", "authc");
return chainDefinition;
}
}
```
创建UserRealm
```
public class UserRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = (String) principals.getPrimaryPrincipal();
Set<String> roles = getUserRoles(username);
Set<String> permissions = getUserPermissions(username);
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.setRoles(roles);
authorizationInfo.setStringPermissions(permissions);
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
String password = getPasswordByUsername(username);
if (password == null) {
throw new UnknownAccountException();
}
return new SimpleAuthenticationInfo(username, password, getName());
}
}
```
使用Shiro进行身份认证
```
@RestController
@RequestMapping("/api")
public class UserController {
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(loginRequest.getUsername(), loginRequest.getPassword());
try {
subject.login(token);
String jwtToken = JwtUtils.generateToken(loginRequest.getUsername());
return ResponseEntity.ok(new JwtResponse(jwtToken));
} catch (AuthenticationException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
@GetMapping("/user")
public ResponseEntity<?> getUser() {
Subject subject = SecurityUtils.getSubject();
if (subject.isAuthenticated()) {
String username = (String) subject.getPrincipal();
User user = getUserByUsername(username);
return ResponseEntity.ok(user);
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
@PostMapping("/logout")
public ResponseEntity<?> logout() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return ResponseEntity.ok().build();
}
}
```
3. 集成Redis
添加依赖
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
配置Redis
```
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1));
return RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
}
}
```
实现Redis缓存
```
@Service
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final RedisTemplate<String, User> redisTemplate;
private final CacheManager cacheManager;
public UserServiceImpl(UserRepository userRepository, RedisTemplate<String, User> redisTemplate, CacheManager cacheManager) {
this.userRepository = userRepository;
this.redisTemplate = redisTemplate;
this.cacheManager = cacheManager;
}
@Override
public User getUserById(Long id) {
String key = "user:" + id;
ValueOperations<String, User> ops = redisTemplate.opsForValue();
if (redisTemplate.hasKey(key)) {
return ops.get(key);
} else {
User user = userRepository.findById(id).orElse(null);
if (user != null) {
ops.set(key, user);
Cache cache = cacheManager.getCache("userCache");
if (cache != null) {
cache.put(key, user);
}
}
return user;
}
}
@Override
public void updateUser(User user) {
userRepository.save(user);
String key = "user:" + user.getId();
redisTemplate.delete(key);
Cache cache = cacheManager.getCache("userCache");
if (cache != null) {
cache.evict(key);
}
}
}
```
以上是整合Spring Boot、JWT、Shiro和Redis的基本实现步骤,具体实现可以根据自己的需求进行调整和扩展。
阅读全文