在使用Spring Boot Security与Vue.js构建前后端分离的应用时,你需要处理几个关键的技术点,包括认证(Authentication)和授权(Authorization),以及如何处理跨域请求(CORS)、前端路由、后端API保护等。以下是一个基本的概述和步骤,帮助你开始这样的项目。
1. 搭建Spring Boot后端
添加Spring Boot Security依赖
在你的Spring Boot项目的pom.xml
中添加Spring Security依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置Spring Security
在Spring Boot应用中配置Security,定义用户、角色和权限。你可能需要自定义WebSecurityConfigurerAdapter
类来配置HTTP安全策略。
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
// 跨域配置,通常应该在CORS Filter中处理
}
// 配置用户详情服务(内存、数据库等)
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
}
2. 搭建Vue.js前端
创建Vue项目
使用Vue CLI创建一个新的Vue项目。
vue create my-vue-app
cd my-vue-app
集成Axios进行HTTP请求
安装Axios用于在Vue应用中发送HTTP请求到Spring Boot后端。
npm install axios
在Vue组件中使用Axios进行API调用,并处理认证信息(如JWT令牌)。
import axios from 'axios';
axios.create({
baseURL: 'http://localhost:8080',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
}
});
// 使用axios进行GET、POST等请求
axios.get('/api/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
3. 处理认证和授权
JWT(JSON Web Tokens)
Spring Boot Security可以配置为使用JWT来处理认证信息。在登录成功后,后端会生成一个JWT令牌,并将其发送给前端。前端在随后的请求中会将此令牌包含在HTTP请求的头部中。
Vue Router 导航守卫
在Vue中,你可以使用Vue Router的导航守卫来检查用户是否已登录或拥有访问特定路由的权限。
router.beforeEach((to, from, next) => {
const publicPages = ['/login', '/register'];
const authRequired = !publicPages.includes(to.path);
const loggedIn = !!localStorage.getItem('jwtToken');
if (authRequired && !loggedIn) {
next('/login');
} else {
next();
}
});
4. 跨域资源共享(CORS)
由于你的前端和后端可能运行在不同的域或端口上,因此你需要配置CORS以允许跨域请求。这通常在Spring Security配置中通过添加一个CORS配置过滤器来实现。
/**
* 跨域设置
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许所有路径
.allowedOrigins("http://example.com", "http://www.example.com") // 允许的源
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法
.allowedHeaders("*") // 允许的HTTP头部
.allowCredentials(true) // 是否允许发送Cookie
.maxAge(3600); // 预检请求的缓存时间(秒)
// WebMvcConfigurer.super.addCorsMappings(registry);
}
}
注意:在生产环境中,你应该限制允许的源和头,以提高安全性。
5. 部署和测试
确保你的前端和后端都能正确运行,并进行全面的测试