开发者

SpringSecurity如何配置跨域访问

开发者 https://www.devze.com 2024-08-22 10:38 出处:网络 作者: chinoukin
目录说明其他总结说明 Java后端web服务有很多种方法可以实现跨域访问,配置很简单,今天这里我们用SpringSecurity的方式配置跨域访问
目录
  • 说明
  • 其他
  • 总结

说明

Java后端web服务有很多种方法可以实现跨域访问,配置很简单,今天这里我们用SpringSecurity的方式配置跨域访问

配置方法如下:

package com.wisea.config;

import org.springframework.conandroidtext.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 SeandroidcurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    }

    @Bean
    public CorsFilter corsFilter() {
        UrpythonlBasedCorsConfigurationSource source = new Urlwww.devze.comBasedCorsConfigurationSource();

        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时,上面这段代码就必须了。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号