要在Angular 16网页应用和Flask API之间实现CSRF防护,可以使用以下解决方法:
pip install Flask-WTF
然后,在Flask应用的配置中添加一个秘钥:
app.config['SECRET_KEY'] = 'your_secret_key'
接下来,在需要进行CSRF防护的路由函数中,使用@csrf_protect
装饰器:
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)
@app.route('/api/endpoint', methods=['POST'])
@csrf_protect
def api_endpoint():
# 处理请求
这样,Flask API就会自动为每个POST请求生成一个CSRF令牌,并在每个请求中验证令牌。
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) {}
getCsrfToken() {
return this.http.get('/api/csrf_token');
}
然后,在发送请求时,将CSRF令牌添加到请求头中:
import { HttpClient, HttpHeaders } from '@angular/common/http';
constructor(private http: HttpClient) {}
sendRequest() {
this.getCsrfToken().subscribe((token: string) => {
const headers = new HttpHeaders({'X-CSRF-TOKEN': token});
this.http.post('/api/endpoint', data, {headers}).subscribe(response => {
// 处理响应
});
});
}
这样,Angular 16网页应用就会在每个POST请求中包含CSRF令牌,并将其发送到Flask API进行验证。
请注意,上述代码示例中的/api/csrf_token
和/api/endpoint
是示例的API端点,你需要根据实际情况进行修改。
同时,为了确保安全性,建议将CSRF令牌存储在HTTP-only的Cookie中,并从Cookie中获取令牌来发送请求。这样可以防止跨站脚本攻击。
希望能对你有所帮助!