spring-boot - 无法从其他来源调用安全的 Spring Boot Rest 服务
问题描述
我有 3 个弹簧启动应用程序:
localhost:8081 (认证服务器) localhost:8083 (UI) localhost:8101 (上传服务)
当用户访问它时,localhost:8083/app
它会将其重定向到localhost:8081/login
向他们展示一个表单以发布他们的凭据,并将用户重定向回localhost:8081/app
并显示该网站。在这一点上没有问题。
但是,我想添加一个上传功能,用户可以将一些文件拖放到输入文件中,文件类型如下:
<input type="file" multiple style="height: 100%; width: 100%; z-index: 100; opacity:0" v-bind:name="uploadFieldName" v-bind:disabled="isSaving" v-on:change="filesChange($event.target.name, $event.target.files);">
然后它将localhost:8101/upload
通过 Axios 调用调用以上传文件。
为了避免 CSRF 问题,我添加了
<meta th:name="_csrf" th:content="${_csrf.token}"/>
<meta th:name="_csrf_header" th:content="${_csrf.headerName}"/>
到 HTML 和 JS 我有以下设置 Axios 以使用令牌并发送 cookie:
var csrfHeader = $("meta[name='_csrf_header']").attr("content");
var csrfToken = $("meta[name='_csrf']").attr("content");
axios.defaults.headers = {
'XSRF-TOKEN': csrfToken
}
axios.defaults.withCredentials = true;
我在 JS 中的调用如下:
upload(formData){
var url = 'http://localhost:8101/upload';
return axios.post(url, formData);
}
在我的上传服务后端,我只需获取文件并写下它们的名称来测试它是否有效:
@RestController
public class AssetController {
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void importAssets(@RequestParam("upload") MultipartFile[] files){
for(MultipartFile file: files){
System.out.println(file.getOriginalFilename());
}
}
}
为了允许其他域(UI 应用程序)访问上传服务,我将 CORS 映射设置如下:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
我还在这里读到我需要为多部分文件上传添加这个:
public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
@Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(servletContext, new MultipartFilter());
}
}
最后我的安全配置如下:
@EnableOAuth2Sso
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.antMatcher("/**")
.authorizeRequests()
.antMatchers("/login**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
}
当我尝试上传文件时,我看到 2 个具有 OPTION 状态的 localhost:8101/upload 调用都具有相同的响应和请求标头:
回复:
HTTP/1.1 302
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
Set-Cookie: XSRF-TOKEN=0ef5a80f-4ffc-49ab-bfb0-813ae4ca149e; Path=/
Location: http://localhost:8101/login
Content-Length: 0
Date: Thu, 23 Aug 2018 19:57:08 GMT
要求:
OPTIONS /upload HTTP/1.1
Host: localhost:8101
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:8083
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
Access-Control-Request-Headers: xsrf-token
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,tr;q=0.8
但是 POST 不会发生。因此,为了进一步测试,我允许/upload**
如下SecurityConfig
:
@EnableOAuth2Sso
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.antMatcher("/**")
.authorizeRequests()
.antMatchers("/login**","/upload**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
}
随着它开始工作,我可以在网络中看到一个 OPTION 和一个 POST ,并且我有以下请求和响应标头:
要求:
POST /upload HTTP/1.1
Host: localhost:8101
Connection: keep-alive
Content-Length: 2507057
Origin: http://localhost:8083
X-XSRF-TOKEN: 4b070c11-9250-40d6-9d2a-d6587e814382
XSRF-TOKEN: 52f8fd81-2c80-493e-b7c6-f0a458b8c2e9
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7lG6mO10sPzrDU5l
Accept: */*
Referer: http://localhost:8083/toybox
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,tr;q=0.8
Cookie: JSESSIONID=0EF7E75D8A8187BC7B5FB74341207E76; TSESSION=4A8DE8A4A4A430DF2AC9AF14A0BD0E50; XSRF-TOKEN=4b070c11-9250-40d6-9d2a-d6587e814382
回复:
HTTP/1.1 200
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
X-Application-Context: toybox-asset-service:8101
Access-Control-Allow-Origin: http://localhost:8083
Vary: Origin
Access-Control-Allow-Credentials: true
Content-Length: 0
Date: Thu, 23 Aug 2018 20:05:47 GMT
同样在日志中,我可以看到发布的文件名:
cat-pet-animal-domestic-104827.jpeg
kittens-cat-cat-puppy-rush-45170.jpeg
所以调用成功。但是,由于我希望它localhost:8101/upload
受到保护,以便只有授权用户才能上传文件,所以不允许任何人自由使用它不是一种选择。
经过几个小时的研究,我得出的结论是,不知何故,Axios 没有发送 cookie。因为在安全/upload
场景中,我看到请求中没有发送任何 cookie。
我的问题是:
- 如果我的理论是正确的,我如何将 cookie 与请求一起发送?
- 我可以选择其他解决方案/配置吗?
任何帮助,将不胜感激。谢谢你。
编辑 1: 我使用 oauth2 作为身份验证服务器,并且我在 UI 和上传服务的 application.properties 中有以下设置:
security.oauth2.client.client-id=client
security.oauth2.client.client-secret=secret
security.oauth2.client.access-token-uri=http://localhost:8081/oauth/token
security.oauth2.client.user-authorization-uri=http://localhost:8081/oauth/authorize
security.oauth2.resource.user-info-uri=http://localhost:8081/me
解决方案
localhost:8081 (Authentication server) localhost:8083 (UI) localhost:8101 所有这些都将被浏览器视为不同的域。因此,其中一个设置的 cookie 不会随请求一起发送给其他人。你有2个选项在这里
第一个选择是:如果你想坚持传统的身份验证方式,让你的 Auth 服务器处理所有请求,让它代理 UI 和 Upload 服务请求到相应的上游服务。您可以使用其他方式,例如防火墙 - iptables/firewalld 或安全组/ACL(如果您在云上)来控制对其他 2 个应用程序(UI 和上传)的访问
第二种选择是:现代化您的堆栈,将 oauth2 服务器作为身份验证服务器,在对用户进行身份验证后发出 oauth2/jwt 令牌。您的 javascript(来自在客户端浏览器上运行的网页)应将该令牌与所有后续请求一起发送。您的其他服务(UI 和上传)将提供与 Auth 服务器对话以验证令牌的有效性的规定。如果发现无效,将它们重定向到相应的页面。
推荐阅读
- c++ - 什么样的 GCC 优化可能会根据是否打印来改变双精度?
- javascript - firebase 数据未添加到数组 ionic 3
- twilio - Twilio JS 在 VoIP 呼叫中发送数字
- mongodb - 一次删除不同文档中多次出现的嵌入数组元素
- postgresql - postgres启动后如何防止docker退出
- c# - 在前端保存一个从 api 检索为字节数组的 excel 文件
- windows - 捕获 Dos 窗口进度
- c# - 在 .NET 中使用 SHA 256 的 PBKDF2
- c# - 在运行时修改导致 InvalidProgramException 的 IL 代码
- swift - 如何在新故事板中将数据传递给 ViewController