Junior — Middle
What methods can be used to protect an API from unauthorized access and attacks?
sobes.tech AI
Answer from AI
The following methods are used to protect APIs from unauthorized access and attacks:
- Authentication and Authorization: Using tokens (JWT, OAuth), API keys, Basic Auth to verify user rights.
- Encryption: Transmitting data over HTTPS to prevent interception.
- Rate Limiting: Preventing DDoS attacks and abuse.
- Validation and Filtering of Incoming Data: Protecting against SQL injections, XSS, and other attacks.
- Logging and Monitoring: Tracking suspicious activity.
- Using CORS: Controlling access from different domains.
- Protection against CSRF: Using tokens or other mechanisms.
Example of simple authentication using an API key in Go:
func apiHandler(w http.ResponseWriter, r *http.Request) {
apiKey := r.Header.Get("X-API-Key")
if apiKey != "expected_api_key" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Handle the request
}