spring-security 如何在sprint Boot 安全中禁用CORS

ulydmbyx  于 2022-11-11  发布在  Spring
关注(0)|答案(3)|浏览(253)

我想在Spring Boot 安全中完全禁用CORS,但我所尝试的一切似乎都不起作用
我尝试添加自定义过滤器并将其作为bean注入,还尝试禁用WebSecurityConfigurerAdapter中的cors,还尝试在configure HttpSecurity方法中添加过滤器。
这些一些链接我已经尝试过:
1:CORS problems with spring boot security的情况下。
第二个:Spring security CORS Filter
我目前的《守则》规定如下:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final CustomUserDetailsService customUserDetailsService;
    private final AuthConfigProperties authConfigProperties;

    public WebSecurityConfig(@Lazy CustomUserDetailsService customUserDetailsService, AuthConfigProperties authConfigProperties) {
        this.customUserDetailsService = customUserDetailsService;
        this.authConfigProperties = authConfigProperties;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(authConfigProperties.getBcryptRounds());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers()
                .antMatchers("/login", "/logout", "/oauth/authorize")
                .and()
                .logout()
                .deleteCookies("JSESSIONID")
                .permitAll()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .csrf()
                .disable();

        http.cors().disable();

    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }

}

当我尝试在前端访问身份验证服务器时,收到以下错误消息:
CORS策略已阻止从源' http://localhost:3000'在' http://localhost:8089/oauth/token'处提取的访问:对预检请求的响应未通过访问控制检查:它不具有HTTP ok状态。

b0zn9rqh

b0zn9rqh1#

这段代码确实有效:

import com.example.myAuthServer.service.CustomUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final CustomUserDetailsService customUserDetailsService;
    private final AuthConfigProperties authConfigProperties;

    public WebSecurityConfig(@Lazy CustomUserDetailsService customUserDetailsService, AuthConfigProperties authConfigProperties) {
        this.customUserDetailsService = customUserDetailsService;
        this.authConfigProperties = authConfigProperties;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(authConfigProperties.getBcryptRounds());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .requestMatchers()
                .antMatchers("/login", "/logout", "/oauth/authorize")
                .and()
                .logout()
                .deleteCookies("JSESSIONID")
                .permitAll()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .csrf()
                .disable();

    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }

}

但是为了得到在原始帖子中显示的错误的红色,你只需要让浏览器知道请求的服务器url具有相同的“允许控制访问源”响应的url。
我们可以通过在客户端应用一个代理来实现这一点,在我的例子中,我使用react。
请在src目录下添加一个名为setupProxy.js的文件。
然后编写以下代码:

const proxy = require("http-proxy-middleware");

module.exports = function (app) {
    app.use(proxy("/oauth/token", {target: "http://localhost:8089"})); // put your host and api
};

并像这样使用它:

fetch("/oauth/token", {
            method: "POST",
            body: qs.stringify(Auth.bodyForNewToken(username, password)),
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                Authorization: "Basic " + btoa("<CLIENT>:<SECRET>")
            }
        });

这段代码只是一个提示,您需要更改必要行!!!.

798qvoo8

798qvoo82#

处理此问题的一种方法是添加WebMvcConfigurer。虽然使用此方法,但您应该考虑环境配置文件(开发、生产等),并且可以保留WebSecurityConfigurerAdapter的默认配置。(无需禁用它)
举个例子:

@Configuration
public class WebMvc implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*")
                .allowedOrigins("*");
    }
}
jvidinwx

jvidinwx3#

自2022年起更新,类WebSecurityConfigurerAdapter已弃用。因此,您需要提供SecurityFilterChain类型的bean。您可以使用以下代码片段禁用cors -

@EnableWebSecurity(debug = true)
public class SecurityConfiguration {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .cors().disable()
                .build();
    }
}

相关问题