使用Spring Security进行auth api调用时出现Cros错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Spring Security进行auth api调用时出现Cros错误相关的知识,希望对你有一定的参考价值。

我已经按照以下步骤设置了Cros,用于具有弹簧安全性的Spring Boot应用程序。具有Spring安全性和jwt令牌的Spring-boot应用程序。

我正在使用其他域的api,所以我在所有控制器上使用交叉源。

所有不需要auth令牌(JWT)的api调用在以下配置下都可以正常工作。但是所需的jwt令牌所用的api调用失败,并出现以下错误。

我正在尝试添加过滤器,但无法正常工作。有人可以帮我吗

谢谢。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Import(SecurityProblemSupport.class)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final AuthenticationManagerBuilder authenticationManagerBuilder;

    private final DomainUserDetailsService userDetailsService;

    private final TokenProvider tokenProvider;

//    private final CorsFilter corsFilter;
    private final SecurityProblemSupport problemSupport;

    @Autowired
    public SecurityConfig(AuthenticationManagerBuilder authenticationManagerBuilder, DomainUserDetailsService userDetailsService, TokenProvider tokenProvider, SecurityProblemSupport problemSupport) {
        this.authenticationManagerBuilder = authenticationManagerBuilder;
        this.userDetailsService = userDetailsService;
        this.tokenProvider = tokenProvider;
//        this.corsFilter = corsFilter;
        this.problemSupport = problemSupport;
    }

        @PostConstruct
    public void init() {
        try {
            authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
        } catch (Exception e) {
            throw new BeanInitializationException("Security configuration failed", e);
        }
    }

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

        http.cors().disable().csrf().ignoringAntMatchers("/api/**", "/reports/**", "/utils/**").and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
                .antMatchers("/", "/*.html", "/**/*.js", "/**/*.png", "/**/*.css", "/**/*.woff2", "/**/*.woff",
                        "/**/*.ico", "/**/*.ttf", "/**/*.jpg")
                .permitAll().antMatchers("/api/auth/**", "/api/util/**", "/api/feed/getJobs", // feed can be seen
                                                                                                // without auth
                        "/api/user/user-details/**", // user details can be seen without auth
                        "/v2/api-docs/**", "/actuators/**", "/api-docs/**", "/utils/**")
                .permitAll().anyRequest().authenticated().and().apply(securityConfigurerAdapter()).and()
                // handle an authorized attempts
                .exceptionHandling()
                .authenticationEntryPoint((req, rsp, e) -> rsp.sendError(HttpServletResponse.SC_UNAUTHORIZED));
    }

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

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    private JWTConfigurer securityConfigurerAdapter() {
        return new JWTConfigurer(tokenProvider, userDetailsService);
    }

没有jwt的GET,POST,PUT,DELETE api调用正在工作。

使用JWT的API调用无法正常工作,出现以下错误

Access to XMLHttpRequest at 'http://localhost:8082/api/feed/posted-by-me' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

有人可以告诉我我在做什么错吗?

我在前端使用Angular 9来调用API。

答案

问题是我在上述类上使用的过滤器无法正常工作。因此我创建了如下所示的新过滤器类,然后它按预期方式开始工作。

package com.happyconnects.web.api.config;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, Authorization, Cache-control, remember-me");

        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}

以上是关于使用Spring Security进行auth api调用时出现Cros错误的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Grails/Spring Security 插件中禁用 /login/auth

使用 REST 和 Javaconfig 在 Spring Security 中摘要 Auth

Spring Security:未调用自定义 UserDetailsS​​ervice(使用 Auth0 身份验证)

Spring Security 配置:Basic Auth + Spring Cloud Gateway

通过 Active Directory LDAP 使用 Spring-Security 进行身份验证

手动设置spring security auth记住我