BETA O Shoulder está em beta — Os resultados às vezes podem estar incorretos. Seu feedback molda o que corrigimos a seguir. Compartilhar feedback
🔄

Cross-Site Request Forgery (CSRF)

🛡️ 3 regras detectam isto

Cross-Site Request Forgery (CSRF)

The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.

When a web server is designed to receive a request from a client without any mechanism for verifying that it was intentionally sent, then it might be possible for an attacker to trick a client into making an unintentional request to the web server which will be treated as an authentic request.

Prevalência
Média
3 linguagens cobertas
Impacto
Alto
3 regras de severidade alta
Prevenção
Documentada
3 exemplos de correção
2 Prevenção
2 Prevenção

Como corrigir esta vulnerabilidade

Estratégias de prevenção para Cross-Site Request Forgery baseadas em 3 regras de detecção do Shoulder.

Angular Missing HTTP Security Interceptor HIGH

Create HTTP interceptors to centralize authentication tokens and CSRF protection across all requests

+21 -22 javascript
- import { HttpClient } from '@angular/common/http';
- import { Injectable } from '@angular/core';
- 
- @Injectable({ providedIn: 'root' })
- export class UserService {
-   constructor(private http: HttpClient) {}
- 
-   getUsers() {
-     return this.http.get('/api/users', {
-       headers: { Authorization: `Bearer ${this.getToken()}` }
-     });
-   }
- 
-   updateUser(id: string, data: any) {
-     // Easy to forget auth header on new endpoints
-     return this.http.put(`/api/users/${id}`, data);
-   }
- 
-   private getToken(): string {
-     return localStorage.getItem('token') || '';
-   }
- }
+ import { Injectable } from '@angular/core';
+ import { HttpInterceptor, HttpRequest, HttpHandler, HTTP_INTERCEPTORS } from '@angular/common/http';
+ import { AuthService } from './auth.service';
+ 
+ @Injectable()
+ export class AuthInterceptor implements HttpInterceptor {
+   constructor(private auth: AuthService) {}
+ 
+   intercept(req: HttpRequest<any>, next: HttpHandler) {
+     const token = this.auth.getToken();
+     if (token) {
+       req = req.clone({
+         headers: req.headers.set('Authorization', `Bearer ${token}`)
+       });
+     }
+     return next.handle(req);
+   }
+ }
+ 
+ // In app.module.ts
+ // providers: [{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }]
  
Django Missing CSRF Protection HIGH

Ensure CsrfViewMiddleware is enabled and never use @csrf_exempt on state-changing views

+4 -4 python
- from django.views.decorators.csrf import csrf_exempt
- from django.http import JsonResponse
- 
- @csrf_exempt
+ from django.views.decorators.csrf import csrf_protect
+ from django.http import JsonResponse
+ 
+ @csrf_protect
  def transfer_funds(request):
      amount = request.POST['amount']
      recipient = request.POST['recipient']
      process_transfer(request.user, recipient, amount)
      return JsonResponse({'status': 'transferred'})
  
Missing CSRF Protection (Gin) HIGH

Add CSRF middleware to protect state-changing endpoints

+11 -4 go
  package main
  
- import "github.com/gin-gonic/gin"
- 
- func main() {
-     r := gin.Default()
+ import (
+     "os"
+     "github.com/gin-gonic/gin"
+     "github.com/utrack/gin-csrf"
+ )
+ 
+ func main() {
+     r := gin.Default()
+     r.Use(csrf.Middleware(csrf.Options{
+         Secret: os.Getenv("CSRF_SECRET"),
+     }))
      r.POST("/transfer", transferMoney)
      r.Run(":8080")
  }
  
4 Sinais de Alerta
4 Sinais de Alerta

O que observar nas revisões de código

Estes padrões indicam vulnerabilidades potenciais de Cross-Site Request Forgery (CSRF). Procure-os durante revisões de código e auditorias de segurança.

🟠
HttpClient used without security interceptors. Missing centralized authentication, CSRF protection, and security headers angular-http-interceptor-missing
🟠
View handles POST/PUT/DELETE without @csrf_protect or @ensure_csrf_cookie decorator django-missing-csrf-protection
🟠
Django views that handle POST/PUT/DELETE requests without CSRF protection django-missing-csrf-protection
🟠
State-changing endpoints lack CSRF protection go-gin-missing-csrf-protection
🔍

Escaneie seu código para Cross-Site Request Forgery (CSRF)

O Shoulder CLI encontra padrões vulneráveis em todo o seu código.