Custom Strategies

Creating a strategy

At the core, a strategy is a way to authenticate a user making a request. As of 3.0 we moved away from Passport in favor of pulling back the curtain and putting you in full control.

A strategy is made up of the following:

ParameterDescription
name *The name of your strategy
authenticate *A function that takes in the parameters below and returns a user or null.

The authenticate function is passed the following arguments:

ArgumentDescription
headers *The headers on the incoming request. Useful for retrieving identifiable information on a request.
payload *The Payload class. Useful for authenticating the identifiable information against Payload.
isGraphQLWhether or not the request was made from a GraphQL endpoint. Default is false.

Example Strategy

At its core a strategy simply takes information from the incoming request and returns a user. This is exactly how Payload's built-in strategies function.

Your authenticate method should return an object containing a Payload user document and any optional headers that you'd like Payload to set for you when we return a response.

1
import { CollectionConfig } from 'payload'
2
3
export const Users: CollectionConfig = {
4
slug: 'users',
5
auth: {
6
disableLocalStrategy: true,
7
strategies: [
8
{
9
name: 'custom-strategy',
10
authenticate: ({ payload, headers }) => {
11
const usersQuery = await payload.find({
12
collection: 'users',
13
where: {
14
code: {
15
equals: headers.get('code'),
16
},
17
secret: {
18
equals: headers.get('secret'),
19
},
20
},
21
})
22
23
return {
24
// Send the user back to authenticate,
25
// or send null if no user should be authenticated
26
user: usersQuery.docs[0] || null,
27
28
// Optionally, you can return headers
29
// that you'd like Payload to set here when
30
// it returns the response
31
responseHeaders: new Headers({
32
'some-header': 'my header value'
33
})
34
}
35
}
36
}
37
]
38
},
39
fields: [
40
{
41
name: 'code',
42
type: 'text',
43
index: true,
44
unique: true,
45
},
46
{
47
name: 'secret',
48
type: 'text',
49
},
50
]
51
}
Next

Token Data