gpt4 book ai didi

authentication - Spring Data REST 中的 CORS 预检请求

转载 作者:行者123 更新时间:2023-12-03 22:42:37 25 4
gpt4 key购买 nike

我有一个 Spring Boot/Spring Data REST 服务,允许访问许多资源。其中一些资源(例如 /detections)可以免费访问,其他资源(例如 /users)需要基本的 HTTP 身份验证。通过使用 CURL 测试 REST 服务,一切都按预期工作。当我尝试从 Angular2 网络应用程序访问该服务时出现问题。

在这种情况下,我在访问未 protected 资源时没有问题 http://api.mydomain.com/detections :

this.http.get(this.DETECTIONS_API_ENDPOINT).subscribe(
response => {
...
},
error => {
...
}
);

但是,如果我尝试通过使用正确的用户名和密码传递所需的 header 来访问 protected 资源 http://api.mydomain.com/users:

    let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Basic ' + btoa(username+':'+password));

return this.http.get(this.USERS_API_ENDPOINT, { body: "", headers: headers }).subscribe(
response => {
...
},
error => {
...
}
);

我收到(在 Firefox 控制台中)一个错误,提示 cross-origin request blocked... Reason: CORS preflight request successfull(请注意,这是我从意大利语翻译过来的。我不能在英文中找到确切对应的错误消息。这两个调用之间的唯一区别似乎是在第二种情况下传递 header ,这会触发发送 OPTIONS 而不是 GET 请求。

这是我的 spring 安全配置:

@Configuration
public class MyAppConfigurationSecurity extends WebSecurityConfigurerAdapter {

private Md5PasswordEncoder md5PasswordEncoder = new Md5PasswordEncoder();

@Autowired
private UserDetailsService myAppUserService;

/**
* HttpSecurity URL configuration settings. Configure authentication necessary for POST but not for GET
*/

@Override
protected void configure(HttpSecurity http) throws Exception
{
http.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/detections").permitAll()
.antMatchers(HttpMethod.GET, "/detections/search/findTop5ByOrderByTimestampDesc").permitAll()
.antMatchers("/users").hasAuthority("ADMIN")
.antMatchers("/roles").hasAuthority("ADMIN")
.antMatchers("**").authenticated()
.and().httpBasic().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}


/**
* Sets custom MyAppUserService bean as user detail service
*/

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

}

这是 CORS 过滤器配置;我按照 Spring Data Rest and Cors 的建议添加了此类,它最初解决了我访问未 protected 资源的 CORS 访问问题。不幸的是,它似乎在 protected 资源的情况下不起作用:

@Configuration
public class MyAppConfigurationCors {

@Bean
public CorsFilter corsFilter() {

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // you USUALLY want this
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("GET");
config.addAllowedMethod("OPTIONS"); // I added this in a second phase, but nothing changes
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}

最佳答案

集成方式请引用Spring文档CORS and Spring Security .

必须首先处理 CORS:

@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;
}
}

关于authentication - Spring Data REST 中的 CORS 预检请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40405838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com