mirror of
https://github.com/stack-auth/stack.git
synced 2026-06-16 21:08:38 +08:00
Some checks failed
all-good: Did all the other checks pass? / all-good (push) Has been cancelled
Ensure Prisma migrations are in sync with the schema / check_prisma_migrations (22.x) (push) Has been cancelled
DB migration compat / Check if migrations changed (push) Has been cancelled
Docker Server Build and Push / Docker Build and Push Server (push) Has been cancelled
Docker Server Build and Run / docker (push) Has been cancelled
Runs E2E API Tests (Local Emulator) / E2E Tests (Local Emulator, Node ${{ matrix.node-version }}) (22.x) (push) Has been cancelled
Runs E2E API Tests / E2E Tests (Node ${{ matrix.node-version }}, Freestyle ${{ matrix.freestyle-mode }}) (mock, 22.x) (push) Has been cancelled
Runs E2E API Tests / E2E Tests (Node ${{ matrix.node-version }}, Freestyle ${{ matrix.freestyle-mode }}) (prod, 22.x) (push) Has been cancelled
Runs E2E API Tests with custom port prefix / build (22.x) (push) Has been cancelled
Lint & build / lint_and_build (latest) (push) Has been cancelled
Dev Environment Test With Custom Base Port / restart-dev-and-test-with-custom-base-port (push) Has been cancelled
Dev Environment Test / restart-dev-and-test (push) Has been cancelled
Run setup tests with custom base port / setup-tests-with-custom-base-port (push) Has been cancelled
Run setup tests / setup-tests (push) Has been cancelled
TOC Generator / TOC Generator (push) Has been cancelled
DB migration compat / Back-compat — Current branch migrations with ${{ needs.check-migrations-changed.outputs.base_branch }} branch code (push) Has been cancelled
DB migration compat / Forward-compat — Current branch code with ${{ needs.check-migrations-changed.outputs.base_branch }} branch migrations (push) Has been cancelled
DB migration compat / No migration changes (skipped) (push) Has been cancelled
127 lines
4.4 KiB
Plaintext
127 lines
4.4 KiB
Plaintext
---
|
|
title: "Backend Integration"
|
|
description: "Integrate Stack Auth with your own server with the REST APIs"
|
|
---
|
|
|
|
To authenticate your endpoints, you need to send the user's access token in the headers of the request to your server, and then make a request to Stack's server API to verify the user's identity.
|
|
|
|
## Sending requests to your server endpoints
|
|
|
|
To authenticate your own server endpoints using Stack's server API, you need to protect your endpoints by sending the user's access token in the headers of the request.
|
|
|
|
On the client side, you can retrieve the access token from the `user` object by calling `user.getAuthJson()`. This will return an object containing `accessToken`.
|
|
|
|
Then, you can call your server endpoint with these two tokens in the headers, like this:
|
|
|
|
```typescript
|
|
const { accessToken } = await user.getAuthJson();
|
|
const response = await fetch('/api/users/me', {
|
|
headers: {
|
|
'x-stack-access-token': accessToken,
|
|
},
|
|
// your other options and parameters
|
|
});
|
|
```
|
|
|
|
## Authenticating the user on the server endpoints
|
|
|
|
Stack Auth provides two methods for authenticating users on your server endpoints:
|
|
|
|
1. **JWT Verification**: A fast, lightweight approach that validates the user's token locally without making external requests. While efficient, it provides only essential user information encoded in the JWT.
|
|
2. **REST API Verification**: Makes a request to Stack Auth's servers to validate the token and retrieve comprehensive user information. This method provides access to the complete, up-to-date user profile.
|
|
|
|
### Using JWT
|
|
|
|
<Tabs>
|
|
<Tab title="Node.js">
|
|
```javascript
|
|
// you need to install the jose library if it's not already installed
|
|
import * as jose from 'jose';
|
|
|
|
// you can cache this and refresh it with a low frequency
|
|
const jwks = jose.createRemoteJWKSet(new URL("https://api.stack-auth.com/api/v1/projects/<your-project-id>/.well-known/jwks.json"));
|
|
|
|
const accessToken = 'access token from the headers';
|
|
|
|
try {
|
|
const { payload } = await jose.jwtVerify(accessToken, jwks);
|
|
console.log('Authenticated user with ID:', payload.sub);
|
|
} catch (error) {
|
|
console.error(error);
|
|
console.log('Invalid user');
|
|
}
|
|
```
|
|
</Tab>
|
|
<Tab title="Python">
|
|
```python
|
|
# you need to install PyJWT and cryptography libraries if they're not already installed
|
|
# pip install PyJWT[crypto] requests
|
|
|
|
import jwt
|
|
import requests
|
|
from jwt import PyJWKClient
|
|
from jwt.exceptions import InvalidTokenError
|
|
|
|
# you can cache this and refresh it with a low frequency
|
|
jwks_client = PyJWKClient("https://api.stack-auth.com/api/v1/projects/<your-project-id>/.well-known/jwks.json")
|
|
|
|
access_token = 'access token from the headers'
|
|
|
|
try:
|
|
signing_key = jwks_client.get_signing_key_from_jwt(access_token)
|
|
payload = jwt.decode(
|
|
access_token,
|
|
signing_key.key,
|
|
algorithms=["ES256"],
|
|
audience="<your-project-id>"
|
|
)
|
|
print('Authenticated user with ID:', payload['sub'])
|
|
except Exception as error:
|
|
print(error)
|
|
print('Invalid user')
|
|
```
|
|
</Tab>
|
|
</Tabs>
|
|
|
|
### Using the REST API
|
|
|
|
<Tabs>
|
|
<Tab title="Node.js">
|
|
```javascript
|
|
const url = 'https://api.stack-auth.com/api/v1/users/me';
|
|
const headers = {
|
|
'x-stack-access-type': 'server',
|
|
'x-stack-project-id': 'generated on the Stack Auth dashboard',
|
|
'x-stack-secret-server-key': 'generated on the Stack Auth dashboard',
|
|
'x-stack-access-token': 'access token from the headers',
|
|
};
|
|
|
|
const response = await fetch(url, { headers });
|
|
if (response.status === 200) {
|
|
console.log('User is authenticated', await response.json());
|
|
} else {
|
|
console.log('User is not authenticated', response.status, await response.text());
|
|
}
|
|
```
|
|
</Tab>
|
|
<Tab title="Python">
|
|
```python
|
|
import requests
|
|
|
|
url = 'https://api.stack-auth.com/api/v1/users/me'
|
|
headers = {
|
|
'x-stack-access-type': 'server',
|
|
'x-stack-project-id': 'generated on the Stack Auth dashboard',
|
|
'x-stack-secret-server-key': 'generated on the Stack Auth dashboard',
|
|
'x-stack-access-token': 'access token from the headers',
|
|
}
|
|
|
|
response = requests.get(url, headers=headers)
|
|
if response.status_code == 200:
|
|
print('User is authenticated', response.json())
|
|
else:
|
|
print('User is not authenticated', response.status_code, response.text)
|
|
```
|
|
</Tab>
|
|
</Tabs>
|