Secure coding guidance
For Web and Mobile teams using Strivacity as their OAuth 2.0 and OpenID Connect Provider
Introduction
This guide outlines secure implementation practices for building web and mobile applications using Strivacity as your OAuth 2.0 and OpenID Connect provider. Whether you're integrating via browser-based flows, React Native, Flutter, iOS, or Android, these practices are designed to help you prevent common security issues such as:
- Token leakage
- Cross-site scripting (XSS)
- Improper session management
We align our guidance with leading industry standards and frameworks, including:
- OWASP Application Security Verification Standard (ASVS)
- OWASP Cheat Sheet Series
- SEI CERT Secure Coding Standards
- NIST Cybersecurity Framework
1. Core Principles of Secure Development
1.1 Input Validation and Output Encoding
Validate all user input strictly using allow-lists where possible, at both the client and server-side. Apply context-sensitive output encoding for HTML, JavaScript, URL, and CSS to prevent injection attacks. Avoid using dangerous JavaScript functions such as innerHTML, eval, and setTimeout with string arguments. This principle applies to all data received, including API inputs (query parameters, headers, body).
1.2 Content Security Policy (CSP)
Implement a strong Content Security Policy to restrict the execution of potentially harmful scripts and control where browser-side JavaScript can send data. Specifically:
script-src
: restricts where scripts can be loaded from.
connect-src
: controls the destinations scripts can connect to. These help mitigate the effects of XSS if a vulnerability is present and restrict data exfiltration.
1.3 Essential HTTP Security Headers
Ensure the following headers are present in all responses to reduce attack surface and limit the damage caused by client-side vulnerabilities:
Content-Security-Policy
Strict-Transport-Security
X-Content-Type-Options
Referrer-Policy
Permissions-Policy
X-Frame-Options
(to prevent clickjacking)
1.4 Secure API Design and Implementation
Rate Limiting: Implement rate limiting on all API endpoints, especially authentication, registration, and password reset flows, to protect against brute-force attacks and denial-of-service.
Granular Access Control (Authorization): Beyond authentication, implement robust authorization checks at the API level (e.g., Role-Based Access Control (RBAC), Attribute-Based Access Control (ABAC)) to ensure users can only access resources and perform actions for which they have explicit permission.
Secure Error Handling: Provide generic error messages to users to avoid revealing sensitive information (e.g., internal server details, database errors, stack traces) that could aid an attacker. Log detailed error information internally for debugging and security monitoring.
API Gateway Security: If using an API gateway, leverage its capabilities to enforce security policies such as authentication, authorization, rate limiting, and Web Application Firewall (WAF) integration.
1.5 Logging, Monitoring, and Alerting
Comprehensive Logging: Implement detailed logging of security-relevant events, including successful and failed authentication attempts, authorization failures, critical user actions (e.g., password changes, profile updates), security policy violations, and input validation failures.
Secure Log Storage: Ensure logs are stored securely, are tamper-proof, and retained for an appropriate period.
Security Monitoring and Alerting: Establish systems to actively monitor logs for suspicious patterns or anomalies (e.g., repeated failed logins, unusual access times or locations, rapid data access) and configure automated alerts for immediate investigation.
2. Secure Token Handling Guidance
2.1 Web Applications
Avoid using localStorage
or sessionStorage
for storing sensitive data such as JWT access tokens or refresh tokens due to their susceptibility to XSS attacks. Prefer in-memory storage for short-lived access tokens, or use secure, HttpOnly
cookies for session tokens and refresh tokens. If localStorage
or sessionStorage
must be used for non-sensitive data, ensure strict protections against XSS are in place.
2.2 React Native
Never use AsyncStorage
for tokens. Use platform-specific secure storage solutions:
iOS: Keychain Services
Android: Encrypted Shared Preferences or Keystore
Recommended libraries include react-native-keychain
and expo-secure-store
(for bare workflow apps).
2.3 Flutter
Implement a custom SDKStorage
interface to manage token storage securely. Use flutter_keychain
on iOS and equivalent secure storage solutions for Android.
2.4 iOS SDK
Strivacity uses ASWebAuthenticationSession
to conform with RFC 8252, preventing the use of embedded WebViews and ensuring secure redirect handling. Token storage is abstracted through a Storage
interface, and refresh tokens are supported for maintaining sessions.
2.5 Android SDK
The Android SDK uses Custom Tabs in line with best practices from the AppAuth library and RFC 8252. Token storage can be implemented securely using the Storage
interface. The SDK supports refresh tokens and secure token exchange flows.
2.6 Storing Tokens in Secure Encrypted Cookies
In web applications, storing tokens in HttpOnly
, Secure
, and SameSite
cookies is a strong defense against XSS attacks, as JavaScript cannot access these cookies. When using opaque tokens, the token value can be securely stored inside an encrypted session cookie using libraries such as gorilla/securecookie
(Go), iron
(Node.js), or similar libraries in other languages.
This approach has several advantages:
- Reduces exposure of tokens to client-side attacks.
- Tokens are protected in transit and at rest (within the cookie).
- Supports traditional session-style authentication with modern OAuth 2.0 flows.
However, this method requires token introspection at the backend for each request, which will introduce performance overhead. Implementations should consider caching introspection responses and balancing token lifetime with application responsiveness.
This strategy is particularly useful when using opaque tokens issued by Strivacity, which are of suitable size for encrypted cookies and benefit from centralized validation.
3. How Strivacity Helps You Build Securely
3.1 Secure Identity Flows
Strivacity inherently supports the OAuth 2.0 Authorization Code flow with Proof Key for Code Exchange (PKCE), which effectively prevents authorization code interception attacks. The platform supports refresh token rotation and detection of reuse, which helps invalidate tokens that may have been compromised, significantly reducing the impact of leaked refresh tokens.
3.2 SDK-Level Support
Strivacity offers robust SDKs for major platforms including JavaScript, React Native, Flutter, iOS, and Android. These SDKs provide secure mechanisms for both hosted UI and native integration patterns, including hooks for deep linking, token lifecycle events, and authentication fallback handling.
3.3 Secure by Default
Strivacity services are designed with security in mind:
- They send appropriate HTTP security headers by default.
- They support CSP-compliant integrations.
- They integrate with Web Application Firewalls (WAFs) and support adaptive access policies to reduce the risk of unauthorized access based on context and risk signals (e.g., device, location, behavior).
- They enforce strong password practices aligned with NIST recommendations, including breached password detection.
4. XSS Prevention When Using localStorage or sessionStorage
Web Storage APIs such as localStorage
and sessionStorage
expose stored data to all JavaScript executing in the same origin. If an attacker is able to inject script through an XSS vulnerability, they can easily read these tokens and exfiltrate them.
To mitigate this risk:
- Use a strict Content Security Policy that blocks inline scripts and untrusted sources (
'unsafe-inline'
and'unsafe-eval'
). - Avoid DOM manipulation methods that inject untrusted HTML or scripts. Prefer
textContent
overinnerHTML
when inserting user-provided data. - Sanitize all user-provided HTML using robust libraries like DOMPurify before rendering.
- Apply context-sensitive output encoding to all data rendered from untrusted sources.
- Only use Web Storage for non-sensitive data when comprehensive XSS protections are already in place across the application. The safest approach is to avoid browser-accessible persistent storage for any credential material or security-critical tokens.
5. Mitigating XSS Risks When Storing JWTs in SPAs
Single-Page Applications (SPAs) often rely on JWTs for session state. Where these tokens are stored and how they are protected is critical to securing the application.
Storing access or refresh tokens in localStorage
or sessionStorage
introduces a significant risk of token theft via XSS. Instead, tokens should ideally be held in memory and discarded on reload. While this means tokens are lost when the page reloads or crashes, it significantly reduces exposure to XSS attacks by limiting the window of opportunity for an attacker to steal them.
Advanced applications may isolate token access by running token-handling logic in a Web Worker or within an iframe with a restrictive sandbox attribute, requiring secure message passing to access the token indirectly. This adds a crucial layer of separation between the token and the potentially unsafe DOM context.
If tokens must be stored persistently, use secure HttpOnly
cookies for refresh tokens, coupled with backend-controlled access and robust CSRF protection (e.g., SameSite cookies, CSRF tokens). This prevents client-side JavaScript from accessing the cookie directly, mitigating XSS token theft.
Strivacity supports:
- In-memory token storage by default in its SDKs.
- Refresh token rotation and automatic invalidation upon reuse to prevent replay attacks.
6. Recommendations for Implementation Teams
- Follow OWASP Secure Coding Best Practices: Integrate secure coding principles at every stage of the Software Development Lifecycle (SDLC), from design to deployment.
- Conduct Thorough Code Reviews: Focus specifically on input handling, DOM interaction, token lifecycle management, authentication, and authorization logic.
- Automate Security Scans: Integrate static application security testing (SAST), dynamic application security testing (DAST), and software composition analysis (SCA) tools into your CI/CD pipeline to identify vulnerabilities early.
- Dependency Management: Regularly update all third-party libraries, frameworks, and Strivacity SDKs to their latest secure versions. Subscribe to security advisories for your dependencies.
- Contextual Output Encoding: Avoid applying output encoding inside generic filters or interceptors. Always encode data at the final "sink" (where it's rendered) to ensure context-sensitive protection.
- Target ASVS Levels: Aim for OWASP ASVS Level 2 or 3 for applications handling personal, financial, or regulated data to ensure a higher standard of security assurance.
- Threat Modeling: Conduct regular threat modeling exercises during design and development to proactively identify potential attack vectors and vulnerabilities specific to your application's architecture and functionality.
- Secure Session Management: Ensure sessions are properly invalidated on logout, and implement appropriate idle and absolute session expiration times.
- Least Privilege for Clients: Configure Strivacity application clients with the absolute minimum scopes required for their functionality.
- Secure Redirect URIs: Carefully configure and validate redirect URIs in Strivacity to be as specific as possible, preventing open redirect vulnerabilities.
7. Vulnerability Management & Continuous Improvement
- Regular Security Assessments: Complement automated testing with periodic manual penetration testing, vulnerability assessments, and consider implementing a bug bounty program.
- Patch Management: Establish a robust patch management process for all underlying infrastructure, operating systems, and application components.
- Data Minimization: Only collect, process, and store the minimum amount of personal and sensitive data necessary for your application's functionality. Implement strong encryption for data at rest and in transit (always use HTTPS/TLS).
8. Learn More
- OWASP Cheat Sheet Series: https://cheatsheetseries.owasp.org/
- OWASP ASVS: https://owasp.org/www-project-application-security-verification-standard/
- SEI CERT Secure Coding: https://wiki.sei.cmu.edu/confluence/display/seccode/SEI+CERT+Secure+Coding+Standards
- Strivacity Developer Hub: https://www.strivacity.com/learn-support/developer-hub
- OAuth 2.1 Security Best Practices: https://oauth.net/2.1/
- NIST Cybersecurity Framework: https://www.nist.gov/cyberframework
- CVE Databases (e.g., NVD): https://nvd.nist.gov/
Summary
Strivacity provides secure identity flows and client SDKs designed to reduce exposure to common threats. However, application developers bear significant responsibility for handling contextual security, XSS mitigation, secure API design, and safe storage of tokens within their applications.
Ensure you:
- Validate and encode user input properly at all layers.
- Prevent XSS vulnerabilities at the source and through layered defenses.
- Choose secure token storage patterns for your specific platform.
- Integrate Strivacity SDKs and configure Strivacity services according to their best practices and the principle of least privilege.
- Implement robust logging, monitoring, and regular security testing.
Security is a shared responsibility. Strivacity handles the underlying identity infrastructure. Your implementation team is responsible for ensuring the secure use of that infrastructure and for implementing strong application-level security controls in the context of your specific web and mobile applications.
Updated 15 days ago