Files
payloadcms/docs/authentication/jwt.mdx
2024-06-21 15:34:25 -04:00

55 lines
1.6 KiB
Plaintext

---
title: JWT Strategy
label: JWT Strategy
order: 40
desc: Enable JSON Web Token based authentication to interface with Payload.
keywords: authentication, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, nextjs
---
Payload offers the ability to authenticate via `JWT` (JSON web token). These can be read from the responses of `login`, `refresh`, and `me` auth operations.
<Banner type="success">
<strong>Tip:</strong>
<br />
You can access the logged-in user from access control functions and hooks from the `req.user` property.
<br />
[Learn more about token data](/docs/authentication/token-data).
</Banner>
### Identifying Users Via The Authorization Header
In addition to authenticating via an HTTP-only cookie, you can also identify users via the `Authorization` header on an HTTP request.
Example:
```ts
const user = await fetch('http://localhost:3000/api/users/login', {
method: 'POST',
body: JSON.stringify({
email: 'dev@payloadcms.com',
password: 'password',
})
}).then(req => await req.json())
const request = await fetch('http://localhost:3000', {
headers: {
Authorization: `JWT ${user.token}`,
},
})
```
### Omitting The Token
In some cases you may want to prevent the token from being returned from the auth operations. You can do that by setting `removeTokenFromResponse` to `true` like so:
```ts
import type { CollectionConfig } from 'payload'
export const UsersWithoutJWTs: CollectionConfig = {
slug: 'users-without-jwts',
auth: {
removeTokenFromRepsonse: true, // highlight-line
},
}
```