Skip to content

凭证文件#

凭证文件定义了节点的授权方法。该文件中的设置会影响 n8n 在凭证模态框中显示的内容,并且必须反映您所连接服务的认证要求。

在凭证文件中,您可以使用所有 n8n UI 元素。n8n 会使用加密密钥对凭证存储的数据进行加密。

凭证文件结构#

凭证文件遵循以下基本结构:

  1. 导入语句
  2. 创建凭证类
  3. 在类中定义控制节点认证的属性

概要结构#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import {
	IAuthenticateGeneric,
	ICredentialTestRequest,
	ICredentialType,
	INodeProperties,
} from 'n8n-workflow';

export class ExampleNode implements ICredentialType {
	name = 'exampleNodeApi';
	displayName = 'Example Node API';
	documentationUrl = '';
	properties: INodeProperties[] = [
		{
			displayName: 'API Key',
			name: 'apiKey',
			type: 'string',
			default: '',
		},
	];
	authenticate: IAuthenticateGeneric = {
		type: 'generic',
		properties: {
    		// 可以是 body、header、qs 或 auth
			qs: {
        		// 使用上面 `apiKey` 的值
				'api_key': '={{$credentials.apiKey}}'
			}

		},
	};
	test: ICredentialTestRequest = {
		request: {
			baseURL: '={{$credentials?.domain}}',
			url: '/bearer',
		},
	};
}

参数#

name#

字符串。对象的内部名称。用于从节点的其他位置引用它。

displayName#

字符串。n8n 在图形用户界面中使用的名称。

documentationUrl#

字符串。指向凭证文档的 URL。

properties 属性#

每个对象包含:

  • displayName: n8n 在图形界面中显示的名称
  • name: 对象的内部名称,用于从节点的其他位置引用
  • type: 预期的数据类型,例如 string
  • default: n8n 用于测试凭据的默认 URL

authenticate 认证配置#

  • authenticate: 对象。包含告诉 n8n 如何将认证数据注入 API 请求的对象

type 类型#

字符串。如果使用在请求头、请求体或查询字符串中发送数据的认证方法,请将其设置为 'generic'

properties 属性#

对象。定义认证方法。可选方案包括:

  • body: 对象。在请求体中发送认证数据。可以包含嵌套对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    authenticate: IAuthenticateGeneric = {
    	type: 'generic',
    	properties: {
    		body: {
    			username: '={{$credentials.username}}',
    			password: '={{$credentials.password}}',
    		},
    	},
    };
    

  • header: 对象。在请求头中发送认证数据

    1
    2
    3
    4
    5
    6
    7
    8
    authenticate: IAuthenticateGeneric = {
    	type: 'generic',
    	properties: {
    		header: {
    			Authorization: '=Bearer {{$credentials.authToken}}',
    		},
    	},
    };
    

  • qs: 对象。代表"查询字符串"。在请求查询字符串中发送认证数据

    1
    2
    3
    4
    5
    6
    7
    8
    authenticate: IAuthenticateGeneric = {
    	type: 'generic',
    	properties: {
    		qs: {
    			token: '={{$credentials.token}}',
    		},
    	},
    };
    

  • auth: 对象。用于基本认证(Basic Auth)。要求键名必须为 usernamepassword

    1
    2
    3
    4
    5
    6
    7
    8
    9
    authenticate: IAuthenticateGeneric = {
    	type: 'generic',
    	properties: {
    		auth: {
    			username: '={{$credentials.username}}',
    			password: '={{$credentials.password}}',
    		},
    	},
    };
    

test 测试配置#

提供一个包含 URL 和认证类型的 request 对象,n8n 可以用它来测试凭据

1
2
3
4
5
6
test: ICredentialTestRequest = {
		request: {
			baseURL: '={{$credentials?.domain}}',
			url: '/bearer',
		},
	};