SpringSecurity如何配置跨域访问
更新时间:2024年08月22日 09:08:45 作者:chinoukin
这篇文章主要介绍了SpringSecurity如何配置跨域访问方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
说明
java后端web服务有很多种方法可以实现跨域访问,配置很简单,今天这里我们用SpringSecurity的方式配置跨域访问
配置方法如下:
package com.wisea.config;
import org.springframework.context.annotation.Bean;
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.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
其他
看网上的配置里会有代码如下:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
...
}实际上并不起什么作用,总结,当工程中开启了@EnableWebSecurity的时候,我们只需要让spring容器中存在一个CorsFilter的跨域过滤器即可。
some days 几天发现问题:
当请求的中有redirect时,上面这段代码就必须了。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Spring Boot整合Kafka+SSE实现实时数据展示
本文主要介绍了Spring Boot整合Kafka+SSE实现实时数据展示2024-06-06
SpringCloud Gateway 路由配置定位原理分析
本节主要了解系统中的谓词与配置的路由信息是如何进行初始化关联生成路由对象的。每个谓词工厂中的Config对象又是如何被解析配置的2021-07-07


最新评论