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 在 GUI 中使用的名称。

documentationUrl#

字符串。指向您的凭据文档的 URL。

properties#

每个对象包含:

  • displayName:n8n 在 GUI 中使用的名称。
  • 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:对象。用于基本身份验证。需要 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',
		},
	};