当前位置: 首页 > news >正文

springboot Security vue

在使用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 {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/api/public/**").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll();// 跨域配置,通常应该在CORS Filter中处理}// 配置用户详情服务(内存、数据库等)@Autowiredpublic 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 {@Overridepublic 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. 部署和测试

确保你的前端和后端都能正确运行,并进行全面的测试

http://www.lryc.cn/news/413625.html

相关文章:

  • 13. 计算机网络HTTPS协议(一)
  • Bean的作用域和生命周期
  • 【Qt】QMainWindow之菜单栏
  • uni-app封装组件实现下方滑动弹出模态框
  • MATLAB(15)分类模型
  • 非虚拟机安装Centos7连接wifi并开机自动联网
  • 怎么选择的开放式耳机好用?2024超值耳机分享!
  • Web 框架
  • 嗖嗖移动业务大厅(JDBC)
  • 大学生编程入门指南:如何从零开始?
  • 如何基于欧拉系统完成数据库的安装
  • 防御笔记第九天(持续更新)
  • html+css+js前端作业和平精英6个页面页面带js
  • 详解基于百炼平台及函数计算快速上线网页AI助手
  • 【TVM 教程】在 CUDA 上部署量化模型
  • 使用 continue 自定义 AI 编程环境
  • 谷粒商城实战笔记-118-全文检索-ElasticSearch-进阶-aggregations聚合分析
  • ansible,laas,pass,sass
  • 【开源分享】PHP在线提交工单源码|工单管理系统源码 (附源码搭建教程)
  • 【深入探秘Hadoop生态系统】全面解析各组件及其实际应用
  • Flink DataStream API编程入门
  • 案例分享|Alluxio在自动驾驶数据闭环中的应用
  • 为什么选择 Baklib 而不是 Salesforce 进行知识库管理
  • 【C++11】解锁C++11新纪元:深入探索Lambda表达式的奥秘
  • c语言排序(2)
  • vue3+ts+element plus开源框架基础
  • RabbitMQ快速入门(MQ的概念、安装RabbitMQ、在 SpringBoot 项目中集成 RabbitMQ )
  • Linux文件与目录管理命令 ls cp rm mv使用方法
  • KubeSphere 部署的 Kubernetes 集群使用 GlusterFS 存储实战入门
  • elasticsearch源码分析-08Serch查询流程