springboot+vue jwt令牌前后端代码
时间: 2024-12-31 12:27:24 浏览: 5
### 关于 Spring Boot 和 Vue 实现 JWT 令牌的前后端代码示例
#### 后端部分 (Spring Boot)
为了创建基于JWT的身份验证服务,在`pom.xml`文件中引入必要的依赖项[^2]:
```xml
<dependencies>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- JWT Library -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
</dependencies>
```
配置类用于设置安全策略并定义如何处理身份验证请求。
```java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/auth/**").permitAll() // Allow all users to access authentication endpoints.
.anyRequest().authenticated(); // All other requests require authentication.
JwtTokenFilterAuthentication filter = new JwtTokenFilterAuthentication();
filter.setAuthenticationManager(authenticationManagerBean());
http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
}
}
```
编写控制器来接收登录请求,并返回带有访问令牌的响应给前端应用。
```java
@RestController
@RequestMapping("/auth")
public class AuthController {
private final AuthenticationManagerBuilder auth;
public AuthController(AuthenticationManagerBuilder auth){
this.auth=auth;
}
@PostMapping("/login")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
try{
String username = loginRequest.getUsername();
String password = loginRequest.getPassword();
Authentication authentication = auth.getObject().authenticate(
new UsernamePasswordAuthenticationToken(username,password));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = TokenProvider.generateToken(authentication);
return ResponseEntity.ok(new JwtResponse(jwt));
}catch(BadCredentialsException ex){
throw new BadCredentialsException("Invalid credentials");
}
}
}
```
#### 前端部分 (Vue.js)
安装 `axios` 库以便发送HTTP请求至服务器。
```bash
npm install axios
```
在 Vuex store 中管理用户的认证状态以及存储获取到的token。
```javascript
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
isAuthenticated: false,
token: null
},
mutations: {
SET_AUTHENTICATED(state, status) {
state.isAuthenticated = status
},
SET_TOKEN(state, token) {
localStorage.setItem('jwt', JSON.stringify(token))
state.token = token
}
},
actions: {
async login({ commit }, {username, password}) {
const response = await axios.post('/api/auth/login', {username, password})
let data=response.data
if(data && data.accessToken){
commit('SET_AUTHENTICATED', true)
commit('SET_TOKEN',data.accessToken )
return Promise.resolve(response)
}else{
return Promise.reject('Failed to log in')
}
}
}
})
```
组件内调用store中的action方法完成登录操作。
```html
<template>
<div id="app">
<form v-on:submit.prevent="handleLogin()">
用户名:<input type="text" name="username" v-model="credentials.username"/><br/>
密码:<input type="password" name="password" v-model="credentials.password"/><br/>
<button type="submit">登陆</button>
</form>
</div>
</template>
<script>
export default {
data(){
return {
credentials:{
username:'',
password:''
}
};
},
methods:{
handleLogin:function () {
this.$store.dispatch('login',this.credentials).then(()=>{
console.log('Logged In');
}).catch((err)=>{
alert(err.message || "Error logging in.");
});
}
}
};
</script>
```
阅读全文