axios + spring security的问题

博主在搭建springboot + spring security + vue前后端分离项目时,使用axios的post提交表单,spring security获取表单参数失败。博主给出两种解决方案,一是重写过滤器,但使用remember me功能时可能有问题;二是修改前端提交表单的header参数。

在我搭建springboot + spring security +vue 项目的时候,我遇到了一个问题,在使用前后端分离,登录的时候如果用了axios 的post提交表单,spring security 的UsernamePasswordAuthenticationFilter 中获取表单参数获取不到。

解决这个问题,我查了很多资料,跟了很多次代码,最后解决这个问题,有可能不是最好的解决方法,如果小伙伴们有更好的方案请留言哦!

解决方案1:重写这个过滤器

c02077d8b9f818fddca27fccab9c794aff4.jpg

通过这种方式获取到参数,但是这个有个后续问题,在使用spring security 的remember me 的时候就会出问题,这个有可能是我还没有弄清楚这块。

解决方案2:修改前端提交表单时候的header参数,任然采用spring security 原本的用户名和密码的过滤器

e70d8e21603cb45a8ed23b1706ac458d4ea.jpg

b6414600f04d2eec8e99e247185fc4f6825.jpg

为什么要加这个header信息,因为axios 提交表单的时候89af3a477ad1792fd1305be6dcc8a5eec95.jpg

不是Form Data ,所有不能通过request.getParameter("username")的方式获取参数值,所有在过滤器中不会去验证登录;

 

转载于:https://my.oschina.net/u/3398768/blog/3054946

### 集成 Spring Boot 和 Spring Security 并与 Vue 前端配合使用的解决方案 #### 一、配置跨域支持 为了使 Spring Boot 后端能够接受来自 Vue 前端的请求,需要在 Spring Boot 应用程序中启用 CORS 支持。可以通过全局配置或者特定方法级别的注解来实现。 以下是通过 Java 配置类的方式设置 CORS 的示例: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 允许所有的路径被访问 .allowedOrigins("http://localhost:8080") // 设置允许的前端域名和端口 .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的方法类型 .allowCredentials(true); // 是否允许发送 Cookie 凭证 } }; } } ``` 上述代码片段展示了如何为整个应用程序配置跨域策略[^1]。 --- #### 二、集成 Spring Security Spring Security 提供了强大的身份验证和授权功能。可以按照以下方式将其集成到项目中并适配 Vue 前端的需求。 ##### 1. 添加依赖项 确保 `pom.xml` 文件中包含了必要的依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- 如果使用 JWT --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> ``` ##### 2. 创建安全配置类 创建一个继承自 `WebSecurityConfigurerAdapter` 的配置类以定义安全性规则。 ```java import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/api/public/**").permitAll() // 对公共 API 不做权限校验 .anyRequest().authenticated(); // 所有其他请求都需要认证 http.cors(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password(passwordEncoder().encode("password")).roles("USER"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 此部分实现了基本的身份验证逻辑,并禁用了 CSRF(如果不需要的话),同时启用了 CORS 支持[^2]。 --- #### 三、JWT 认证机制(可选) 对于更复杂的场景,建议采用基于 JSON Web Token (JWT) 的无状态会话管理方案。这有助于提高系统的扩展性和性能。 下面是一个简单的 JWT 工具类实现: ```java import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; public class JwtUtil { private static final String SECRET_KEY = "secret"; public static String generateToken(String username) { return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) // token有效期为1小时 .signWith(SignatureAlgorithm.HS512, SECRET_KEY.getBytes()) .compact(); } public static boolean validateToken(String token) { try { Jwts.parser().setSigningKey(SECRET_KEY.getBytes()).parseClaimsJws(token); return true; } catch (Exception e) { return false; } } } ``` 该工具可用于生成和解析令牌,在实际应用中需进一步完善异常处理以及密钥存储的安全性。 --- #### 四、Vue 前端调用后端接口 在 Vue.js 中发起 HTTP 请求通常借助 Axios 库完成。安装 Axios 后可以在组件内部编写如下代码: ```javascript const axiosInstance = require('axios').create({ baseURL: 'http://localhost:8081', // 替换为 Spring Boot 实际运行地址 }); // 登录示例 function login(username, password) { return axiosInstance.post('/auth/login', {username, password}) .then(response => response.data.token); } export default {login}; ``` 注意调整基础 URL 地址匹配服务器的实际部署环境。 --- #### 总结 以上内容涵盖了从跨域配置到 Spring Security 整合再到 JWT 使用的基础流程。具体实施过程中可能还需要针对业务需求做出相应修改优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值