SpringSecurity+springBoot前后端分离项目,解决跨域问题和token失效或为空获取不到返回的状态码问题
1.由于写的微服务项目想部署到服务器上,但是微服务太多,就把微服务整成了单体项目,微服务项目的跨域是使用的gateway网关进行断言进行跨域,也使用了全局跨域配置,配置如下:
package com.dhnsoft.gateway.config;
/**
* 统一跨域解决
* @author dhn
* @date 2021/6/27 14:59
*/
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsFilter() {
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//1) 允许的请求方式
config.addAllowedMethod("*");
//2) 允许的域
config.addAllowedOrigin("*");
//3)允许的头信息
config.addAllowedHeader("*");
//2.添加映射路径,我们拦截一切请求
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
//3.返回新的CorsFilter.
return new CorsWebFilter(source);
}
}
2.但是变成单体项目后,就舍弃了GateWay网关,准备使用了@CrossOrigin注解进行跨域,但是发现security里面的一个方法还是无法跨域。
public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
this.authenticationManager = authenticationManager;
this.tokenManager = tokenManager;
this.redisTemplate = redisTemplate;
this.setPostOnly(false);
this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/acl/login","POST"));
}
3.然后我就又使用了以上的全局跨域配置类,但是最后又出现了bug,发现前端还是报跨域错误,后端却可以获取到数据,然后我使用了另外一种全局跨域。
package com.dhnsoft.education.config;
/**
* @Description
* @ClassName CrosConfig
* @Author dhn
* @date 2022.05.07 23:27
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").
allowedOrigins("*"). //允许跨域的域名,可以用*表示允许任何域名使用
allowedMethods("*"). //允许任何方法(post、get等)
allowedHeaders("*"). //允许任何请求头
allowCredentials(true). //带上cookie信息
exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
}
}
4.这时候前台可以获取数据了,后台oken失效或为空获取不到返回的状态码问题,是因为springsecurity的配置也要允许跨域访问,springsecurity配置类里加上.cors()即可。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
.authenticationEntryPoint(new UnauthorizedEntryPoint())
.and().csrf().disable()
.cors().and() //这里加入了security跨域
.authorizeRequests()
.anyRequest().authenticated()
.and().logout().logoutUrl("/admin/acl/index/logout")//退出请求
.addLogoutHandler(new TokenLogoutHandler(tokenManager,redisTemplate)).and()
.addFilter(new TokenLoginFilter(authenticationManager(), tokenManager, redisTemplate))
.addFilter(new TokenAuthenticationFilter(authenticationManager(), tokenManager, redisTemplate)).httpBasic();
}