Authentication overview
MojoAuth specializes in passwordless authentication solutions, designed to simplify user login experiences while maintaining security. The platform provides a suite of methods that eliminate the need for users to create and remember passwords, thereby reducing common security vulnerabilities associated with password management. Integration typically involves using MojoAuth's client-side SDKs to initiate authentication flows and server-side SDKs or direct API calls for token validation and user management. This approach aims to streamline development efforts for implementing secure login systems.
MojoAuth's architecture focuses on providing developers with tools to embed authentication directly into web and mobile applications. The process generally begins with obtaining API keys from the MojoAuth dashboard, configuring allowed redirect URIs, and then integrating the chosen authentication method. The system relies on secure tokens (e.g., JSON Web Tokens) for session management and user identification after successful authentication, following industry standards for API security and user data protection, as outlined in the MojoAuth documentation.
Supported authentication methods
MojoAuth supports several passwordless authentication methods, each designed for different use cases and user preferences. These methods aim to balance convenience with security, often leveraging multi-factor authentication principles without explicit password requirements. Developers can choose the most appropriate method or combine several to offer a flexible login experience.
| Method | When to Use | Security Level |
|---|---|---|
| Magic Link Login | Email-based login, ideal for web applications where users prefer not to enter codes. | High (requires access to user's email inbox) |
| Email OTP Login | Email-based login, suitable for web and mobile apps requiring a one-time code entry. | High (requires access to user's email inbox and code entry) |
| SMS OTP Login | Mobile number-based login, effective for mobile applications and reaching users without email access. | High (requires access to user's registered phone number and code entry) |
| Social Login | Convenient login via third-party providers (e.g., Google, Facebook), suitable for broad user bases. | Variable (depends on the security of the third-party provider and user's account with them) |
Each method is implemented with specific SDKs and API endpoints. For instance, Magic Link and OTP flows typically involve sending a secure, time-sensitive code or link to the user's registered contact method (email or phone number). Upon user interaction (clicking the link or entering the code), MojoAuth verifies the credential and issues an authentication token. Social Login integrates with OAuth 2.0 providers, delegating the initial authentication to services like Google or Facebook and then receiving user identity information back, as described in the OAuth 2.0 specification.
Getting your credentials
To begin using MojoAuth, developers need to obtain API credentials from their MojoAuth dashboard. These credentials typically include a Publishable API Key (for client-side integration) and a Secret API Key (for server-side operations). The process involves:
- Account Creation: Register for a MojoAuth account on their official website.
- Project Setup: Create a new project within the MojoAuth dashboard. Each project can represent a distinct application or environment (e.g., development, staging, production).
- Key Retrieval: Navigate to the project settings or API keys section to find your unique Publishable and Secret API Keys. The Publishable Key is used in client-side SDKs to initialize the authentication widget, while the Secret Key is used on your backend to validate tokens and perform administrative tasks securely.
- Domain Configuration: Configure the allowed redirect URIs and origins in your MojoAuth dashboard. This step is crucial for security, ensuring that authentication callbacks are only processed from trusted domains, preventing unauthorized redirects and potential phishing attacks.
It is critical to keep Secret API Keys confidential and never expose them in client-side code or public repositories. They should be stored securely on your server and accessed only by your backend application. For detailed instructions on credential setup and management, refer to the MojoAuth API Reference.
Authenticated request example
After a user successfully authenticates with MojoAuth, your application receives an authentication token (e.g., a JWT). This token is then used to identify the user and authorize subsequent requests to your backend API. The following Node.js example illustrates how to validate a MojoAuth token on your server-side using the MojoAuth Node.js SDK and then use an authenticated user ID to fetch data.
Step 1: Client-side initiation (Conceptual JavaScript)
<script src="https://cdn.mojoauth.com/js/mojoauth.min.js"></script>
<div id="mojoauth-passwordless-form"></div>
<script>
const mojoauth = new MojoAuth("YOUR_PUBLISHABLE_API_KEY", {
language: "en",
redirect_url: "http://localhost:3000/callback", // Your callback URL
});
mojoauth.signIn().then(response => {
console.log("MojoAuth response:", response);
// Send the `oauth_token` to your backend for validation
fetch('/api/auth/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: response.oauth_token })
})
.then(res => res.json())
.then(data => {
if (data.success) {
console.log("User authenticated on backend:", data.user);
// Redirect or update UI
} else {
console.error("Backend authentication failed");
}
});
}).catch(error => {
console.error("MojoAuth sign-in error:", error);
});
</script>
Step 2: Server-side token validation (Node.js with Express)
const express = require('express');
const MojoAuthSDK = require('mojoauth-node-sdk');
const app = express();
const port = 3000;
app.use(express.json());
const mojoAuth = new MojoAuthSDK("YOUR_SECRET_API_KEY");
// Endpoint to receive and verify the token from the client
app.post('/api/auth/verify', async (req, res) => {
const { token } = req.body;
if (!token) {
return res.status(400).json({ success: false, message: 'Token is required' });
}
try {
const response = await mojoAuth.verifyToken(token);
if (response.isValid) {
// Token is valid, user is authenticated
const userId = response.user.identifier;
console.log(`User ${userId} authenticated successfully.`);
// In a real application, you'd create a session or issue your own JWT here
res.json({ success: true, user: { id: userId, email: response.user.email } });
} else {
res.status(401).json({ success: false, message: 'Invalid or expired token' });
}
} catch (error) {
console.error('Token verification error:', error);
res.status(500).json({ success: false, message: 'Internal server error' });
}
});
// Example of an authenticated API endpoint
app.get('/api/profile', async (req, res) => {
// In a real app, you would get the user ID from a session or a validated JWT
const userId = '[email protected]'; // Placeholder: replace with actual authenticated user ID
// Assume user is authenticated and userId is available
if (!userId) {
return res.status(401).json({ message: 'Unauthorized' });
}
// Fetch user data from your database based on userId
const userData = { id: userId, name: 'John Doe', plan: 'Premium' };
res.json(userData);
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
This example demonstrates the core flow: client-side initiation of the MojoAuth flow and submission of the resulting token to a backend endpoint. The backend then uses the MojoAuth SDK to verify the token's authenticity and validity, establishing the user's identity. Further details on using specific SDKs can be found in the MojoAuth developer documentation.
Security best practices
Implementing authentication with MojoAuth requires adherence to general security best practices to protect user data and maintain application integrity. While MojoAuth handles many security complexities of passwordless authentication, developers are responsible for their application's overall security posture.
- Protect Secret API Keys: Never expose your MojoAuth Secret API Key in client-side code, frontend repositories, or public-facing environments. Store it securely on your server and use environment variables for access.
- Validate Tokens Server-Side: Always validate authentication tokens received from the client on your backend. Client-side validation alone is insufficient and susceptible to tampering. Use MojoAuth's server-side SDKs or API endpoints for robust token verification.
- Configure Allowed Redirect URIs: Strictly configure the allowed redirect URIs in your MojoAuth dashboard. This prevents malicious actors from redirecting users to phishing sites after successful authentication.
- Implement Secure Session Management: After verifying a MojoAuth token on your backend, establish a secure session for the user. This might involve issuing your own HTTP-only, secure cookies or server-side JWTs. Ensure sessions have appropriate expiry times and are invalidated upon logout.
- Use HTTPS Everywhere: Ensure all communication between your application, MojoAuth, and users occurs over HTTPS to encrypt data in transit and prevent man-in-the-middle attacks. This is a fundamental web security practice, also recommended by organizations like the World Wide Web Consortium (W3C) for web security.
- Error Handling and Logging: Implement comprehensive error handling for authentication failures and log security-related events. This helps in detecting and responding to potential attacks or misconfigurations.
- Regularly Review Security: Periodically review your application's authentication implementation and MojoAuth configurations. Stay updated with MojoAuth's security advisories and documentation for any new recommendations or features.
- Rate Limiting: Implement rate limiting on your login and token verification endpoints to prevent brute-force attacks and denial-of-service attempts.
By following these best practices, developers can build secure and reliable applications leveraging MojoAuth's passwordless authentication capabilities.