gpt4 book ai didi

java - 加载swagger-ui.html页面时,请求host :port/and host:port/csfr

转载 作者:搜寻专家 更新时间:2023-10-31 19:51:36 25 4
gpt4 key购买 nike

我有一个 Spring boot 2 应用程序(rest API)并使用 Springfox Swagger 2 库,包括 UI 库。当我打开位于 http://localhost:8080/swagger-ui.html 的 swagger 界面时,一切都按预期工作,但是发出了两个请求,在记录器中给出了 404 结果:

http://localhost:8080/ (nothing is mapped to the root of my app)
http://localhost:8080/csfr (this mapping also doesn't exist, but I know it stands for 'cross site forged request')

显然 Swagger 这样做是因为它“支持”某种类型的 csfr token 检查 explained here .是否可以配置这些 404 调用已经进行了几个月的调查,所以我现在正在考虑实现端点。我找不到有关实际实现内容的信息。 swagger 期望什么样的 header / token ,它将如何处理其中的信息?我可以使用它来使我的应用程序(或 swagger 端点)更安全或更易于访问吗?简而言之:有什么意义 :)?

最佳答案

让我一一回答你的问题。

Why are the request made to http://localhost:8080/ and http://localhost:8080/csrf?

这是因为,Springfox Swagger 默认启用了对 CSRF 的支持。这样做的目的是,每当您尝试访问应用程序中的任何 swagger 端点时,它都会按以下顺序检查 CSRF token 并将其附加到请求 header 。

  • / 上提供的元标记中的 CSRF token
  • 端点/csrf
  • 您的 cookie 中的 CSRF token

Springfox Swagger 附加 CSRF token 的原因是,如果您的应用程序启用了CSRF 保护,如果它们没有 CSRF token 作为一部分,那么对 swagger 端点的请求将会失败标题。

What kind of header/token is swagger expecting, and what will it do with the information in it?

正如我之前所说,swagger 需要一个 CSRF token ,当您尝试访问任何 swagger 端点时,它会将其附加到请求的 header 。

Can I use this to make my app (or the swagger endpoint) more secure or accessible?

在您的应用中启用 CSRF 保护 将使您的应用免受 CSRF 攻击,而不必只是通过提供 CSRF token 以 Swagger 附加到 header 。如果您在您的应用中启用了 CSRF 保护,您必须通过上述 3 种方式中的任何一种提供 CSRF token ,以访问您应用中的任何 swagger 端点。开启CSRF保护的使用可以阅读here .

I'm failing to find information on what to actually implement

如果您没有在您的应用中启用 CSRF 保护,那么为 swagger 实现 CSRF token 条款是没有用的,因为它只是多余的。但是如果你想为 swagger 实现 CSRF token 提供,你可以通过以下 3 种方法中的任何一种来实现:

1) 在 / 提供的元标记中的 CSRF token

<html>
<head>
<meta name="_csrf" content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
</head>

这是为了防止您使用任何模板机制,如 JSP、thymeleaf 等。

2) 端点/csrf

定义端点 /csrf 以提供 CSRF token 。

  @RequestMapping("/csrf")
public CsrfToken csrf() {
//logic to return the CSRF token
}

3) cookie 中的 CSRF token

搜索的默认 cookie 名称是 XSRF-TOKEN,返回的默认 header 名称是 X-XSRF-TOKEN。 Spring Security 提供了一种将 CSRF token 存储在 cookie 中的方法,如 swagger 所要求的,配置如下

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
}

实现上述 3 种方法中的任何一种都会提供带有 CSRF token 的 swagger 以附加到请求 header 。

以上内容引用自GitHub PR它为 Springfox swagger 和我之前链接的 Spring 安全文档提供了 CSRF 支持。

目前有一个关于默认启用的 CSRF 支持的未决问题 here ,以及几个带有修复程序的公开 PR #2639#2706 .

关于java - 加载swagger-ui.html页面时,请求host :port/and host:port/csfr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55582023/

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