Spring Cloud + Vue前后端分离-第13章 网站开发
由于提出的查询涉及的内容较多,我将提供一个简化的示例来说明如何在Spring Cloud和Vue前后端分离的项目中集成JWT(JSON Web Tokens)来确保API的安全性。
后端(Spring Cloud):
- 添加依赖(在
pom.xml
中):
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
- 创建JWT的工具类:
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class JwtTokenUtil {
private static final String SECRET_KEY = "my_secret";
public static String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + 864000000))
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}
public static boolean validateToken(String token, String username) {
String userNameFromToken = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody()
.getSubject();
return (userNameFromToken.equals(username) && !isTokenExpired(token));
}
private static boolean isTokenExpired(String token) {
Date expiration = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody()
.getExpiration();
return expiration.before(new Date());
}
}
- 在安全配置中使用JWT:
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// ... 其他配置 ...
.csrf().disable() // 禁用CSRF保护
.addFilter(new JwtAuthenticationFilter(authenticationManager()));
}
}
前端(Vue.js):
- 安装axios和vue-axios插件:
npm install axios vue-axios --save
- 在Vue中使用axios发送请求:
import axios from 'axios';
import VueAxios from 'vue-axios';
// 在Vue中使用axios
Vue.use(VueAxios, axios);
// 登录方法
methods: {
login() {
this.axios.post('/api/login', { username: this.
评论已关闭