CORS:响应中缺少授权标头(jQuery / Spring)

时间:2018-07-23 14:36:23

标签: spring rest spring-security cors jwt

我有一个运行在localhost:8080上的Spring-Boot Web服务器,还有一个在localhost:80上带有一些“静态” html / js的Apache HTTP服务器。我使用JWT授权实现了RESTful-API。

如果我确实在与REST-API相同的服务器上提供静态html / js,则当我请求/ login-Endpoint时,我成功检索了JWT-Token作为“ Authorization” -Header。

但是,当我这样做时,在我的Apache服务器上提供静态源,则缺少Authorization-Header。我的Javascript:

 $.ajax({
            type: "POST",
            url: "http://localhost:8080/login",
            data: JSON.stringify(data),
            contentType: "application/json",
            dataType: "json",
            success: function (data) {
                alert(data);
            },
            failure: function (errMsg) {
                alert(errMsg);
            },
            complete: function (resp) {
                console.log(resp.getAllResponseHeaders());
                console.log(resp.getResponseHeader("authorization"));
            }
        });

console.log(resp.getAllResponseHeaders()):

pragma: no-cache cache-control: no-cache, no-store, max-age=0, must-revalidate expires: 0

console.log(resp.getResponseHeader(“ authorization”)):

null

我已经做了很多研究,我认为原因是错误的CORS配置。

我的WebSecurity-Class看起来像这样-尽我所能(出于测试目的):

@EnableWebSecurity public class WebSecurity extends WebSecurityConfigurerAdapter {

@Autowired
private PasswordEncoder passwordEncoder;

@Autowired
private UserDetailsServiceImpl userDetailsService;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().authorizeRequests()
            .antMatchers(HttpMethod.POST, SecurityConstants.SIGN_UP_URL).permitAll().anyRequest().authenticated().and()
            .addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilter(new JWTAuthorizationFilter(authenticationManager()))
            // this disables session creation on Spring Security
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

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

 @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }}

还有其他建议吗?

(我调试了Java代码,并成功将JWT-Token添加到响应中-但我的js没有收到它。)

1 个答案:

答案 0 :(得分:0)

您的CORS配置对我来说似乎不正确。

您可以在许多级别上配置Spring的CORS

全局CORS配置

为整个应用程序启用CORS很简单:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

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

如果您使用的是Spring Boot,建议仅声明一个WebMvcConfigurer bean

@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

方法级别

@RestController
@RequestMapping("/account")
public class AccountController {

    @CrossOrigin
    @GetMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @DeleteMapping("/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

班级

@CrossOrigin
@RestController
@RequestMapping("/account")
public class AccountController {

    @GetMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @DeleteMapping("/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

更多详细信息here

编辑1

如果您使用的是Spring Security,则可以这样配置

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // by default uses a Bean by the name of corsConfigurationSource
            .cors().and()
            ...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

更多详细信息here

相关问题