springsecurity 前后端分离 登录后 请求其他接口报302
时间: 2023-08-24 08:07:09 浏览: 59
出现这种情况,可能是因为前后端分离导致登录后没有保存登录状态的问题。
解决方法一般有两种:
1.使用token
前后端分离的情况下,可以考虑使用token来保存登录状态。在用户登录成功后,后端会生成一个token并返回给前端,前端需要将这个token保存到本地,然后在后面的请求中将token作为请求头发送给后端,后端通过校验token来判断用户是否已登录。
2.设置跨域
如果前端和后端不在同一个域名下,需要设置跨域。在Spring Security中,可以通过配置WebSecurityConfigurerAdapter来实现跨域。
具体配置如下:
```
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
```
其中,corsConfigurationSource()方法用于配置跨域,设置允许的域名、请求方式、请求头等信息。在configure(HttpSecurity http)方法中,将cors()方法添加到HttpSecurity中即可启用跨域。