springboot shiro jwt redis
时间: 2023-04-28 21:05:29 浏览: 169
Spring Boot是一个基于Spring框架的快速应用开发工具,可以简化Spring应用的创建和配置。
Apache Shiro是一个强大且灵活的Java安全框架,可用于身份验证,授权,加密和会话管理。
JWT(JSON Web Token)是一种开放标准(RFC 7519),它定义了一种简洁的自包含方式,用于在各方之间安全地传输信息。
Redis是一个开源的内存数据库,支持存储键值对数据,常用于缓存和消息队列等。
相关问题
springboot+jwt+shiro+redis例子
可以的,我可以为您提供一个基于Spring Boot、JWT、Shiro和Redis的例子。这个例子将演示如何使用这些技术实现用户认证和授权,并且将用户的状态存储在Redis中。
首先,您需要创建一个Spring Boot项目并添加所需的依赖。
在pom.xml文件中添加以下依赖:
```
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.7.1</version>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
```
接下来,创建一个名为`JwtUtils`的JWT工具类,用于生成和验证JWT令牌。您可以参考以下代码:
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Date;
@Component
public class JwtUtils {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private int expiration;
@PostConstruct
public void init() {
secret = Base64.getEncoder().encodeToString(secret.getBytes());
}
public String generateToken(String username) {
Date now = new Date();
Date expiryDate = new Date(now.getTime() + expiration * 1000);
return Jwts.builder()
.setSubject(username)
.setIssuedAt(now)
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public String getUsernameFromToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
return claims.getSubject();
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
}
```
然后,创建一个名为`RedisUtils`的Redis工具类,用于操作Redis。您可以参考以下代码:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtils {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void set(String key, Object value, long expiration) {
redisTemplate.opsForValue().set(key, value, expiration, TimeUnit.SECONDS);
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
public void delete(String key) {
redisTemplate.delete(key);
}
public boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
}
```
接下来,创建一个名为`JwtRealm`的Shiro Realm,用于验证JWT令牌和授权。您可以参考以下代码:
```java
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class JwtRealm extends AuthorizingRealm {
@Autowired
private JwtUtils jwtUtils;
@Autowired
private RedisUtils redisUtils;
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JwtToken;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// TODO: 实现授权逻辑
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
JwtToken jwtToken = (JwtToken) token;
String username = jwtUtils.getUsernameFromToken(jwtToken.getToken());
if (username == null || !jwtUtils.validateToken(jwtToken.getToken())) {
throw new AuthenticationException("无效的令牌");
}
// TODO: 查询用户信息并返回认证信息
return new SimpleAuthenticationInfo(username, jwtToken.getToken(), getName());
}
}
```
最后,创建一个名为`JwtToken`的Shiro Token,用于封装JWT令牌。您可以参考以下代码:
```java
import org.apache.shiro.authc.AuthenticationToken;
public class JwtToken implements AuthenticationToken {
private String token;
public JwtToken(String token) {
this.token = token;
}
@Override
public Object getPrincipal() {
return token;
}
@Override
public Object getCredentials() {
return token;
}
}
```
以上是一个基于Spring Boot、JWT、Shiro和Redis的例子。您可以根据您的需求进行修改和扩展。希望对您有帮助!
springboot整和jwt、shiro、redis
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的基本实现步骤,具体实现可以根据自己的需求进行调整和扩展。
阅读全文