【Java】RuoYi+SpringBoot+前后端分离版添加接口加密(参考)
在RuoYi项目中,前后端分离版本通常会使用JWT来进行接口的加密认证。以下是一个简化的示例,展示了如何在RuoYi项目中添加接口加密的基本步骤:
- 添加JWT依赖:在
pom.xml
中添加JWT的依赖。
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
- 创建JWT工具类:用于生成和验证JWT。
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.UserDetails;
public class JwtTokenUtil {
private static final String SECRET_KEY = "your_secret_key";
public static String generateToken(UserDetails userDetails) {
return Jwts.builder()
.setSubject(userDetails.getUsername())
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}
public static boolean validateToken(String token, UserDetails userDetails) {
String username = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody()
.getSubject();
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
}
private static boolean isTokenExpired(String token) {
return Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody()
.getExpiration()
.before(new Date());
}
}
- 创建JWT过滤器:用于拦截请求并验证JWT。
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
final String authorizationHeader = r
评论已关闭