Spring Boot Security OAuth Angular 对预检请求的响应没有通过?

Posted

技术标签:

【中文标题】Spring Boot Security OAuth Angular 对预检请求的响应没有通过?【英文标题】:Spring Boot Security OAuth Angular Response to preflight request doesn't pass? 【发布时间】:2020-08-09 01:36:58 【问题描述】:

来自 Angular 应用程序的登录请求,向 Spring Boot OAuth 服务发出 Web 控制台中的以下错误,

Access to XMLHttpRequest at 'http://localhost:9191/oauth/token' 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.

这是我的角度登录方法

logIn(u_name: string, password: string): Observable<any> 

    const httpOptions = 
      headers: new HttpHeaders(
        'Authorization': 'Basic ' + btoa('mobile:pin'),
        'Content-type': 'multipart/form-data'
      )
    ;

      const requestBody = new HttpParams()
        .set('username', u_name)
        .set('password', password)
        .set('grant_type', 'password');

    return this.http.post('http://localhost:9191/oauth/token', requestBody, httpOptions );
  

这是WebSecurityConfiguration

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter 


    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private CorsFilter corsFilter;

    @Bean
    protected AuthenticationManager getAuthenticationManager() throws Exception 
        return super.authenticationManagerBean();
    

    @Bean
    PasswordEncoder passwordEncoder() 
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    

    @Bean
    CorsConfigurationSource corsConfigurationSource() 
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200/auth/login"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception 
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    

    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class).authorizeRequests().antMatchers("/oauth/token").permitAll()
                .anyRequest().authenticated();

     // i already try with this but it also ended up with the same error
      //  http.cors();
    




CorsFilter配置类



@Configuration
public class CorsFilter extends OncePerRequestFilter 

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException 
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token");
        response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
        if ("OPTIONS".equals(request.getMethod())) 
            response.setStatus(HttpServletResponse.SC_OK);
         else 
            filterChain.doFilter(request, response);
        
    

我在这里做错了什么。提前致谢。

【问题讨论】:

【参考方案1】:

仅在 CorsConfigurationSource bean 中指定来源,而不是整个 url,如链接 https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/cors.html 中所示

【讨论】:

以上是关于Spring Boot Security OAuth Angular 对预检请求的响应没有通过?的主要内容,如果未能解决你的问题,请参考以下文章

Spring Security with Boot

spring boot Security 简单使用

Spring Boot Security

Understand Spring Security Architecture and implement Spring Boot Security

如何使用 Spring-Boot 播种 Spring-Security

Spring Boot整合Spring Security总结