Input Validation and Sanitization
Proper input validation and sanitization are critical for securing your application during the OAuth 2.0 flow and when handling data received from Mubarokah ID. This helps prevent common web vulnerabilities such as Cross-Site Scripting (XSS), injection attacks, and other issues arising from processing untrusted data.Key Principles
- Validate All External Inputs: Treat any data received from external sources as untrusted. This includes:
- Parameters from the authorization redirect (
code,state,error,error_description). - Data from the token endpoint response (
access_token,refresh_token,scope, etc.). - User information received from API endpoints (
/api/user,/api/user/details).
- Parameters from the authorization redirect (
- Server-Side Validation is Crucial: While client-side validation can improve user experience, server-side validation is essential for security as client-side checks can be bypassed.
- Be Specific: Validate against expected formats, types, lengths, and ranges.
- Fail Closed: If validation fails, reject the request or data, and log the incident. Do not attempt to “fix” invalid input.
Validation During OAuth Flow
Authorization Callback (redirect_uri)
When Mubarokah ID redirects the user back to your redirect_uri:
Token Endpoint Response
When you exchange an authorization code or refresh token for new tokens:The PHP code example above is conceptual and demonstrates server-side validation logic for a token response. Adapt it to your specific language and framework.
Validating User Information (from API responses)
- Data Types: Validate that fields match their expected types (e.g.,
idis a number/string,emaillooks like an email,profile_pictureis a URL if present). - Sanitize for Display: If you are displaying any user information directly in your application (especially in HTML), ensure it is properly sanitized/escaped to prevent XSS vulnerabilities. Use template engine features or libraries designed for this.
- Example (Blade in Laravel):
{{ $userData->name }}(auto-escapes) - Example (JavaScript, if setting innerHTML):
element.textContent = userData.name;(safer thaninnerHTML)
- Example (Blade in Laravel):
General Best Practices
- Use Well-Tested Libraries: Leverage existing libraries for OAuth 2.0 client flows and data validation in your chosen language/framework, as they often have built-in protections.
- Regular Expression (Regex) Wisely: For complex string formats, use regex for validation but ensure your regex patterns are not susceptible to ReDoS (Regular Expression Denial of Service) attacks.
- Error Handling: Implement robust error handling for validation failures. Log attempts that fail validation for monitoring and security analysis.
- Security Headers: Implement security headers like Content Security Policy (CSP) to mitigate the impact of XSS vulnerabilities even if some unsanitized input makes it through.