javascript – 如何在Spring Boot Spring Security应用程序中配置CORS?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 如何在Spring Boot Spring Security应用程序中配置CORS?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含6571字,纯文字阅读大概需要10分钟。
内容图文
![javascript – 如何在Spring Boot Spring Security应用程序中配置CORS?](/upload/InfoBanner/zyjiaocheng/715/bddd34bfc50a48be90254bf9e323fcaf.jpg)
我使用Spring Boot和Spring Security以及Cors支持.
如果我执行以下代码
url = 'http://localhost:5000/api/token'
xmlhttp = new XMLHttpRequest
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState is 4
console.log xmlhttp.status
xmlhttp.open "GET", url, true
# xmlhttp.setRequestHeader "X-Requested-With", "XMLHttpRequest"
xmlhttp.setRequestHeader 'Authorization', 'Basic ' + btoa 'a:a'
do xmlhttp.send
我得到了结果
200
如果我测试错误的凭据,如
url = 'http://localhost:5000/api/token'
xmlhttp = new XMLHttpRequest
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState is 4
console.log xmlhttp.status
xmlhttp.open "GET", url, true
# xmlhttp.setRequestHeader "X-Requested-With", "XMLHttpRequest"
xmlhttp.setRequestHeader 'Authorization', 'Basic ' + btoa 'a:aa'
do xmlhttp.send
而不是获得401(这是春季安全中错误身份验证的标准代码),我得到了
0
以下浏览器通知:
获得http://localhost:5000/api/token
XMLHttpRequest无法加载http://localhost:5000.请求的资源上不存在“Access-Control-Allow-Origin”标头.因此不允许原点’http://localhost:3000‘进入.响应具有HTTP状态代码401.
我正在开发前端代码,需要服务器响应中的有用http状态代码来处理这种情况.我需要比0更有用的东西.响应体也是空的.我不知道我的配置是否错误,或者它是一个软件错误,我也不知道在哪里,如果它是铬(使用arch linux)或spring security.
我的Spring配置是:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
@RequestMapping("api")
public class Controller {
@RequestMapping("token")
@CrossOrigin
Map<String, String> token(HttpSession session) {
return Collections.singletonMap("token", session.getId());
}
}
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("a").password("a").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.anyRequest().authenticated()
.and().httpBasic();
}
}
如果我用curl测试一切都很完美,我认为因为不需要CORS支持,但我尝试用OPTION请求模拟CORS,结果也没问题.
$curl -v localhost:5000/api/token -H "Authorization: Basic YTpha"
* Trying ::1...
* Connected to localhost (::1) port 5000 (#0)
> GET /api/token HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.48.0
> Accept: */*
> Authorization: Basic YTpha
>
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Access-Control-Allow-Origin: http://localhost:3000
< Access-Control-Allow-Methods: POST,GET,OPTIONS,DELETE
< Access-Control-Max-Age: 3600
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Headers: Origin,Accept,X-Requested- With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization
< x-auth-token: 58e4cca9-7719-46c8-9180-2fc16aec8dff
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Sun, 01 May 2016 16:15:44 GMT
<
* Connection #0 to host localhost left intact
{"token":"58e4cca9-7719-46c8-9180-2fc16aec8dff"}
并使用错误的凭据:
$curl -v localhost:5000/api/token -H "Authorization: Basic YTp"
* Trying ::1...
* Connected to localhost (::1) port 5000 (#0)
> GET /api/token HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.48.0
> Accept: */*
> Authorization: Basic YTp
>
< HTTP/1.1 401 Unauthorized
< Server: Apache-Coyote/1.1
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< WWW-Authenticate: Basic realm="Realm"
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Sun, 01 May 2016 16:16:15 GMT
<
* Connection #0 to host localhost left intact
{"timestamp":1462119375041,"status":401,"error":"Unauthorized","message":"Failed to decode basic authentication token","path":"/api/token"}
编辑:
避免误解.我使用1.3.3 Spring Boot.
博客文章写道:
CORS support will be available in the upcoming Spring Boot 1.3 release, and is already available in the 1.3.0.BUILD-SNAPSHOT builds.
Using controller method CORS configuration with @CrossOrigin annotations in your Spring Boot application does not require any specific configuration.
Global CORS configuration can be defined by registering a WebMvcConfigurer bean with a customized addCorsMappings(CorsRegistry) method:
我添加了以下代码以启用全局cors支持.实际上我之前尝试了这个,但结果是一样的.我最近再次尝试过,结果是一样的.
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
问题来自于授权过程之间的重定向,这个想法很有意思.如何将重定向更改为任何资源以避免此冲突?
编辑:
我想我更接近解决方案.我已经测试了我的nodejs服务器,通过添加支持cors没有问题
Access-Control-Allow-Origin:*
对所有要求.
就像Stefan Isele已经提到的那样,Spring安全性似乎重定向或者没有添加CORS头部,这就是为什么请求似乎被破坏了.因此,虽然Spring安全性正在检查身份验证,但它必须添加正确的标头.
有谁知道怎么做?
编辑:
我找到了一个解决方法,这看起来很难看.我已经为spring boot启动了一个github问题,我在其中描述了解决方法:https://github.com/spring-projects/spring-boot/issues/5834
解决方法:
Spring Security现在可以利用我写的this blog post中描述的Spring MVC CORS支持.
要使其工作,您需要在Spring Security级别显式启用CORS支持,如下所示,否则在到达Spring MVC之前,Spring Security可能会阻止启用CORS的请求.
如果您使用的是控制器级@CrossOrigin注释,则只需启用Spring Security CORS支持,它将利用Spring MVC配置:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
}
如果您更喜欢使用CORS全局配置,则可以如下声明CorsConfigurationSource bean:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
}
此方法取代之前推荐的filter-based approach.
您可以在Spring Security文档的dedicated CORS section中找到更多详细信息.
内容总结
以上是互联网集市为您收集整理的javascript – 如何在Spring Boot Spring Security应用程序中配置CORS?全部内容,希望文章能够帮你解决javascript – 如何在Spring Boot Spring Security应用程序中配置CORS?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。