gpt4 book ai didi

spring-boot - 如何配置我的 NGINX 以在我的 Spring Boot 应用程序上允许 CSRF 保护

转载 作者:行者123 更新时间:2023-12-03 21:02:16 30 4
gpt4 key购买 nike

我试图通过使用 NGINX 反向代理将我的 Spring Boot 应用程序与我的前端(即我的 Angular 7+ 应用程序)分开。
我的 Spring Boot 应用程序的版本是 2.0.3+.RELEASE 并且启用了 CSRF 保护。

我的安全配置如下所示:

    @Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().and()
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and().csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}

我的 nginx.conf 看起来像这样:
events {
worker_connections 768;
}

http {
# Nginx will handle gzip compression of responses from the app server
gzip on;
gzip_proxied any;
gzip_types text/plain application/json;
gzip_min_length 1000;

server {
listen 80;

# Nginx will reject anything not matching /api
location /api {
# Reject requests with unsupported HTTP method
if ($request_method !~ ^(GET|POST|HEAD|OPTIONS|PUT|DELETE)$) {
return 405;
}

# Only requests matching the whitelist expectations will
# get sent to the application server
proxy_pass http://app:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache_bypass $http_upgrade;
}

location / {
root /var/www/ui;
try_files $uri $uri/ /index.html =404;
index index.html index.htm;
}
}
}

考虑以下 http://localhost/api/myResource 的请求 header 我在 POST 请求中收到一条禁止消息:

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: it,it-IT;q=0.9,en;q=0.8,it-CH;q=0.7
authorization: Basic
Connection: keep-alive
Content-Length: 94
Content-Type: application/json
Cookie: SESSION=MTdmNGFmODctMTNiMC00YzRjLWJjNTAtYmVlMTgzMzJkZTli; XSRF-TOKEN=fbe30e1e-1f64-4910-9040-799217c59b51
Host: localhost
Origin: http://localhost
Referer: http://localhost/admin/bundles
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
X-Requested-With: XMLHttpRequest

Spring 应用程序记录以下错误:

Invalid CSRF token found for http://localhost/api/myResource

最佳答案

当显式调用后端 spring boot 服务器时,NON GET 调用应该在 header 中传递 X-XSRF-Token ,

@Injectable()
export class CustomInterceptor implements HttpInterceptor {


constructor(private http: Http,private tokenExtractor: HttpXsrfTokenExtractor) { }


intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

const headerName = 'X-XSRF-TOKEN';
let token = this.tokenExtractor.getToken() as string;
console.log(token)


if (token !== null && !request.headers.has(headerName)) {
request = request.clone({ headers: request.headers.set(headerName, token) });
}

关于spring-boot - 如何配置我的 NGINX 以在我的 Spring Boot 应用程序上允许 CSRF 保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56687941/

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