Authentication overview
Sanity's authentication mechanisms are designed to secure access to its Content Lake and associated APIs, differentiating between user authentication for the Sanity Studio and programmatic access for applications. For users interacting with the Sanity Studio, authentication typically involves standard identity providers or email/password combinations. For applications and services that need to read from or write to the Content Lake, Sanity primarily relies on API tokens Sanity API tokens documentation.
These API tokens provide granular control over permissions, allowing developers to define specific access levels such as read-only or read/write. This approach supports a variety of use cases, from public-facing websites fetching content to backend services submitting data. Sanity's real-time content updates, a core feature, also leverage these authentication methods to ensure secure data synchronization across all connected clients Sanity real-time features.
The authentication architecture aims to balance developer flexibility with security requirements, enabling integration into diverse application environments while adhering to data protection standards like GDPR and CCPA Sanity security overview.
Supported authentication methods
Sanity supports several authentication methods to accommodate different user roles and application needs. These methods vary based on whether the access is for a human user interacting with the Sanity Studio or an automated process accessing the Content Lake via APIs.
API Tokens
API tokens are the primary method for programmatic access to the Sanity Content Lake. These tokens are generated within the Sanity Management Console and can be assigned specific permissions (scopes) such as read, write, create, delete, and deploy. A token's scope determines what operations an application can perform. For example, a token used by a public-facing frontend might only require read access, while a content import script would need write or create permissions Sanity token scopes.
OAuth
For user authentication within the Sanity Studio, OAuth is utilized through common identity providers. Users can log in using their Google or GitHub accounts Sanity login methods. This simplifies the login process and leverages existing identity management systems.
Email and Password
Users also have the option to authenticate directly with Sanity using an email address and password. This method provides an alternative for users who prefer not to use third-party identity providers or for specific organizational setups.
SAML (Security Assertion Markup Language)
Enterprise-level Sanity accounts can integrate with SAML for Single Sign-On (SSO). SAML enables organizations to manage user access centrally through an Identity Provider (IdP), enhancing security and streamlining user management for larger teams Sanity SAML SSO documentation. This is critical for compliance and enterprise-grade security policies.
Table of Authentication Methods
| Method | When to Use | Security Level |
|---|---|---|
| API Token | Programmatic access (APIs, SDKs), headless frontends, backend services, integrations | High (scoped permissions, revokable) |
| OAuth (Google, GitHub) | Sanity Studio user login, leverages existing identity providers | High (provider-managed security) |
| Email & Password | Sanity Studio user login, direct Sanity account access | Medium-High (Sanity-managed, strong password practices recommended) |
| SAML SSO | Enterprise user login, centralized identity management, compliance requirements | Very High (IdP-managed, enterprise-grade) |
Getting your credentials
To obtain credentials for authenticating with Sanity, you will primarily use the Sanity Management Console. The process differs slightly depending on whether you need an API token for programmatic access or are setting up user authentication.
For API Tokens:
- Log in to Sanity Management Console: Access your project dashboard at Sanity Management Console.
- Navigate to API Tokens: Select your project, then go to the 'Settings' tab, and choose 'API Tokens'.
- Create New Token: Click 'Add new token'. You will be prompted to name the token and select its permissions (scopes).
- Select Scopes: Carefully choose the minimum necessary permissions (e.g.,
readfor public content,writefor content submission). - Generate Token: After selecting scopes, the token will be generated. Copy it immediately, as it will only be shown once for security reasons. Store this token securely.
For User Login:
If you are setting up user access to the Sanity Studio, users will typically authenticate themselves through one of the supported methods:
- OAuth: Users can log in using their existing Google or GitHub accounts directly from the Sanity Studio login page Sanity user login methods.
- Email and Password: Users can sign up or log in using an email address and a password directly managed by Sanity.
- SAML SSO: For enterprise accounts, SAML SSO is configured at the organization level. Users will be redirected to their organization's Identity Provider for authentication Sanity SAML SSO setup.
It is important to manage API tokens and user accounts diligently, regularly reviewing permissions and revoking access when no longer needed.
Authenticated request example
Authenticating a request to the Sanity Content Lake typically involves including the API token in the request headers or as part of the client configuration. The following example demonstrates how to make an authenticated request using JavaScript, fetching content from a Sanity project.
Using the Sanity JavaScript Client
Sanity provides official client libraries for various languages, simplifying authenticated requests. Here's an example using the @sanity/client library in JavaScript/TypeScript:
import { createClient } from '@sanity/client'
const client = createClient({
projectId: 'your-project-id',
dataset: 'your-dataset-name',
apiVersion: '2023-05-03', // use current date (YYYY-MM-DD) to prevent breaking changes
token: 'YOUR_SANITY_API_TOKEN', // This is your API token with appropriate permissions
useCdn: false, // Set to true for read-only tokens in production for performance
})
async function fetchAuthenticatedContent() {
try {
const query = `*[_type == "post"]{_id, title, "slug": slug.current}`
const posts = await client.fetch(query)
console.log('Authenticated posts:', posts)
} catch (error) {
console.error('Error fetching authenticated content:', error.message)
}
}
fetchAuthenticatedContent()
In this example, YOUR_SANITY_API_TOKEN should be replaced with the actual token obtained from the Sanity Management Console. For read-only operations in a production environment, setting useCdn: true can improve performance by leveraging Sanity's CDN, provided the token has read access Sanity API CDN usage.
Direct HTTP Request (cURL example)
For direct HTTP requests without a client library, the API token is typically sent in the Authorization header. This is less common for client-side applications due to security risks but useful for server-side scripts or testing.
curl -X GET \
"https://your-project-id.api.sanity.io/v1/data/query/your-dataset-name?query=*[_type==%22post%22]%7B_id%2Ctitle%7D" \
-H "Authorization: Bearer YOUR_SANITY_API_TOKEN"
Replace your-project-id, your-dataset-name, and YOUR_SANITY_API_TOKEN with your actual project details and token. The query string needs to be URL-encoded.
Security best practices
Adhering to security best practices is crucial when managing authentication for Sanity projects to protect your content and user data. These practices apply to both API token management and user access.
API Token Management:
- Least Privilege: Always grant API tokens the minimum necessary permissions (scopes). For instance, a public frontend fetching content should only have
readaccess, notwriteordeleteSanity token scope best practices. - Environment Variables: Never hardcode API tokens directly into your application's source code. Instead, use environment variables (e.g.,
process.env.SANITY_API_TOKEN) that are loaded at runtime. This prevents tokens from being exposed in version control systems. - Server-Side Operations: For operations requiring
write,create, ordeletepermissions, perform these actions from a secure backend server. Avoid exposing tokens with sensitive permissions in client-side code where they could be intercepted. - Token Rotation: Regularly rotate your API tokens. This limits the window of exposure if a token is compromised. Revoke old tokens once new ones are in place.
- Revoke Unused Tokens: Promptly revoke any API tokens that are no longer in use or associated with deprecated applications or services Sanity token revocation guide.
- Access Control: Restrict who has access to generate and manage API tokens within your Sanity project settings.
User Authentication and Studio Access:
- Strong Passwords/Multi-Factor Authentication (MFA): Encourage or enforce strong password policies for users logging in with email and password. For enterprise users, leverage SAML SSO with MFA capabilities provided by your Identity Provider. The FIDO Alliance provides standards for strong, phishing-resistant authentication methods that include MFA FIDO Alliance authentication technologies.
- Role-Based Access Control (RBAC): Sanity Studio allows you to define roles for users, granting specific access levels to parts of your content or studio features. Assign roles based on the principle of least privilege.
- Audit Logs: Regularly review activity logs within your Sanity project to monitor for unusual or unauthorized access attempts.
- Secure Communication: Ensure all communication with Sanity APIs and the Studio uses HTTPS to encrypt data in transit. Sanity enforces HTTPS by default.
- Session Management: Understand and configure session timeouts for Sanity Studio users to minimize the risk of unauthorized access to unattended sessions.
By implementing these security measures, developers can significantly reduce the risk of unauthorized access to their Sanity Content Lake and maintain the integrity and confidentiality of their content.