SpringBoot和vue3实现登录退出【用jwt redis 拦截器..】
以下是一个简化的Spring Boot后端和Vue 3前端实现登录和注销的示例。
后端(Spring Boot):
- 引入依赖(
pom.xml
):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
- 配置Redis和JWT(
application.properties
):
spring.redis.host=localhost
spring.redis.port=6379
jwt.secret=your_secret_key
jwt.expiration=3600000
- 创建JWT工具类:
@Component
public class JwtTokenProvider {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private long expiration;
public String generateToken(Authentication authentication) {
...
}
public boolean validateToken(String token) {
...
}
}
- 创建拦截器:
@Component
public class JwtInterceptor implements HandlerInterceptor {
@Autowired
private JwtTokenProvider tokenProvider;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
...
}
}
- 配置拦截器:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private JwtInterceptor jwtInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor).excludePathPatterns("/login");
}
}
前端(Vue 3):
- 安装axios和vuex:
npm install axios vuex
- 创建Vuex store:
// store.js
import { createStore } from 'vuex'
export default createStore({
state: {
token: null
},
mutations: {
setToken(state, token) {
state.token = token
}
},
actions: {
login({ commit }, userData) {
...
},
logout({ commit }) {
...
}
}
})
- 创建axios实例并配置拦截器:
// http-common.js
import axios from 'axios'
const http = axios.create({
baseURL: 'http://localhost:8080/api',
timeout: 10000,
headers: {'Content-Type': 'application/json
评论已关闭