这篇文章主要介绍了SpringBoot+Spring Security无法实现跨域怎么解决的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringBoot+Spring Security无法实现跨域怎么解决文章都会有所收获,下面我们一起来看看吧。
让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:国际域名空间、雅安服务器托管、营销软件、网站建设、昌江黎族网站维护、网站推广。
SpringBoot+Spring Security无法实现跨域
未使用Security时跨域:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
@AutoConfigureBefore(SecurityConfig.class)
public class MyMvcConfigurer implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry){
LOGGER.info("跨域已设置");
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}整合Security时发现只用上述方法前后端分离时仍存在跨域问题,
解决方法如下:
@Configuration
@AutoConfigureBefore(Swagger2Configuration.class)
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(-1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginProcessingUrl("/user/login")
.loginPage("/singIn.html")
.successHandler(moyuAuthenticationSuccessHandler)
.failureHandler(moyuAuthenticationFailureHandler)
.and()
.apply(moyuSocialSecurityConfig)
.and()
.rememberMe()
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(3600*24*7)
.userDetailsService(userDetailsService)
.and()
.authorizeRequests()
.antMatchers("/user/login","/login","/singIn.html","**","/**").permitAll()
.anyRequest()
.authenticated()
.and()
.cors()
.and()
.csrf().disable();
}
}重点加入代码:
.and() .cors()//新加入 .and() .csrf().disable();
引用Spring Security 项目的跨域处理
最近项目采用了前后端分离的框架,前端和后台接口没有部署到一个站点,出现了跨域问题,什么是跨域,这里就不再赘述,直接说解决办法。
Spring 解决跨域的方式有很多,个人采用了Crosfilter的方式
具体代码如下:
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}配置完成后,测试调用,报错401,依然不行。网上查资料得知,跨域请求会进行两次。具体流程见下图:

每次跨域请求,真正请求到达后端之前,浏览器都会先发起一个preflight request,请求方式为OPTIONS 询问服务端是否接受该跨域请求,具体参数如下图:

但是该请求不能携带cookie和自己定义的header。
由于项目中引入了Spring security ,而我使用的token传递方式是在header中使用authorization 字段,这样依赖Spring Security拦截到 preflight request 发现它没有携带token,就会报错401,没有授权。
解决这个问题很简单,可以使用以下配置
让Spring security 不校验preflight request 。
@Override
public void configure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry registry
= http.authorizeRequests();
registry.requestMatchers(CorsUtils::isPreFlightRequest).permitAll();//让Spring security放行所有preflight request
} 再试就搞定了,但是后端直接配置支持跨域会导致两次请求。还使用另一种方式,使用Nginx 转发一下请求也可以。
关于“SpringBoot+Spring Security无法实现跨域怎么解决”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“SpringBoot+Spring Security无法实现跨域怎么解决”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注创新互联行业资讯频道。
当前标题:SpringBoot+SpringSecurity无法实现跨域怎么解决
文章出自:http://www.jxjierui.cn/article/jscepi.html


咨询
建站咨询
