实例: vue3 用store保存登录用户信息 前台用vue3 后台Springboot 假设有一个users表,用security来判定,工具前后端都使用idea
时间: 2024-03-17 10:45:10 浏览: 149
好的,下面是一个简单的实例,演示如何使用Vue3和Spring Boot来实现用户登录和保存用户信息到Vuex store中。
前端部分:
1. 创建Vue3项目并安装Vuex库:
```
vue create myproject
cd myproject
npm install vuex --save
```
2. 在src目录下创建store目录,并新建一个index.js文件来定义和导出Vuex store:
```javascript
import { createStore } from 'vuex'
const store = createStore({
state: {
user: null
},
mutations: {
setUser(state, user) {
state.user = user
},
clearUser(state) {
state.user = null
}
},
actions: {
login({ commit }, user) {
// Send login request to the backend
// ...
// If login succeeds, commit the user to the store
commit('setUser', user)
},
logout({ commit }) {
// Send logout request to the backend
// ...
// If logout succeeds, clear the user in the store
commit('clearUser')
}
},
getters: {
isLoggedIn(state) {
return !!state.user
},
getUser(state) {
return state.user
}
}
})
export default store
```
3. 在main.js中导入store并挂载到Vue实例中:
```javascript
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
createApp(App).use(store).mount('#app')
```
4. 在登录页面中创建一个表单来输入用户名和密码,并将其提交到Vuex store中:
```html
<template>
<form @submit.prevent="login">
<input v-model="username" placeholder="Username">
<input v-model="password" placeholder="Password">
<button type="submit">Login</button>
</form>
</template>
<script>
import { mapActions } from 'vuex'
export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
...mapActions(['login']),
onSubmit() {
this.login({ username: this.username, password: this.password })
}
}
}
</script>
```
5. 在需要访问用户信息的组件中,使用Vuex的mapGetters函数来获取用户信息:
```html
<template>
<div v-if="isLoggedIn">
Logged in as: {{ username }}
<button @click="logout">Logout</button>
</div>
<div v-else>
Not logged in
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
export default {
computed: {
...mapGetters(['isLoggedIn', 'getUser']),
username() {
return this.getUser.username
}
},
methods: {
...mapActions(['logout'])
}
}
</script>
```
后端部分:
1. 使用Spring Boot创建一个RESTful API,用于处理用户登录和注销请求:
```java
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenProvider tokenProvider;
@Autowired
private UserRepository userRepository;
@PostMapping("/login")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginRequest.getUsernameOrEmail(),
loginRequest.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = tokenProvider.generateToken(authentication);
return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
}
@PostMapping("/logout")
public ResponseEntity<?> logoutUser(HttpServletRequest request) {
// Invalidate session and clear authentication token
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
SecurityContextHolder.clearContext();
return ResponseEntity.ok(new ApiResponse(true, "Successfully logged out"));
}
}
```
2. 创建一个User实体类,并创建一个UserRepository接口来访问users表:
```java
@Entity
@Table(name = "users")
public class User extends DateAudit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Size(max = 40)
private String name;
@NotBlank
@Size(max = 15)
private String username;
@NaturalId
@NotBlank
@Size(max = 40)
@Email
private String email;
@NotBlank
@Size(max = 100)
private String password;
// getters and setters
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
Boolean existsByEmail(String email);
}
```
3. 使用Spring Security来保护API,并使用JwtTokenProvider类来生成和验证JWT:
```java
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/auth/**")
.permitAll()
.anyRequest()
.authenticated();
// Add JwtAuthenticationFilter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
@Component
public class JwtTokenProvider {
private static final Logger logger = LoggerFactory.getLogger(JwtTokenProvider.class);
@Value("${app.jwtSecret}")
private String jwtSecret;
@Value("${app.jwtExpirationInMs}")
private int jwtExpirationInMs;
public String generateToken(Authentication authentication) {
UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
Date now = new Date();
Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);
return Jwts.builder()
.setSubject(Long.toString(userPrincipal.getId()))
.setIssuedAt(new Date())
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
public Long getUserIdFromJWT(String token) {
Claims claims = Jwts.parser()
.setSigningKey(jwtSecret)
.parseClaimsJws(token)
.getBody();
return Long.parseLong(claims.getSubject());
}
public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
return true;
} catch (SignatureException ex) {
logger.error("Invalid JWT signature");
} catch (MalformedJwtException ex) {
logger.error("Invalid JWT token");
} catch (ExpiredJwtException ex) {
logger.error("Expired JWT token");
} catch (UnsupportedJwtException ex) {
logger.error("Unsupported JWT token");
} catch (IllegalArgumentException ex) {
logger.error("JWT claims string is empty.");
}
return false;
}
}
```
以上就是一个简单的使用Vue3和Spring Boot实现用户登录和保存用户信息到Vuex store中的实例。其中,涉及到了Vue3的Vuex库、Spring Boot的RESTful API、Spring Security和JwtTokenProvider等技术,需要在前后端都进行配置和编码。
阅读全文