-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
sampleocitokenauth.js
225 lines (205 loc) · 8.07 KB
/
sampleocitokenauth.js
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/* Copyright (c) 2023, Oracle and/or its affiliates. */
/******************************************************************************
*
* You may not use the identified files except in compliance with the Apache
* License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
* NAME
* sampleocitokenauth.js
*
* DESCRIPTION
* Shows connection pooling with OAuth 2.0 token based authentication to
* Oracle Autonomous Database from OCI-SDK. It shows how to create a
* connection pool.
*
* For more information refer to
* https://node-oracledb.readthedocs.io/en/latest/user_guide/connection_handling.html
* #iam-token-based-authentication
*
* PREREQUISITES
* - node-oracledb 6.3 or later.
*
* - While using Thick mode,
* Oracle Client libraries 19.14 (or later), or 21.5 (or later).
*
* - Package OCI-SDK. See, https://www.npmjs.com/package/oci-sdk
*
* - Set these environment variables (see the code explanation):
* NODE_ORACLEDB_PROFILE
* NODE_ORACLEDB_CONNECTIONSTRING
* NODE_ORACLEDB_CONFIG_FILE_LOCATION
* NODE_ORACLEDB_DRIVER_MODE
* NODE_ORACLEDB_CLIENT_LIB_DIR
*
*****************************************************************************/
const identitydataplane = require("oci-identitydataplane");
const common = require("oci-common");
const { generateKeyPair } = require('crypto');
const oracledb = require('oracledb');
let accessTokenData;
// This example runs in both node-oracledb Thin and Thick modes.
//
// Optionally run in node-oracledb Thick mode
if (process.env.NODE_ORACLEDB_DRIVER_MODE === 'thick') {
// Thick mode requires Oracle Client or Oracle Instant Client libraries.
// On Windows and macOS Intel you can specify the directory containing the
// libraries at runtime or before Node.js starts. On other platforms (where
// Oracle libraries are available) the system library search path must always
// include the Oracle library path before Node.js starts. If the search path
// is not correct, you will get a DPI-1047 error. See the node-oracledb
// installation documentation.
let clientOpts = {};
// On Windows and macOS Intel platforms, set the environment
// variable NODE_ORACLEDB_CLIENT_LIB_DIR to the Oracle Client library path
if (process.platform === 'win32' ||
(process.platform === 'darwin' && process.arch === 'x64')) {
clientOpts = { libDir: process.env.NODE_ORACLEDB_CLIENT_LIB_DIR };
}
oracledb.initOracleClient(clientOpts); // enable node-oracledb Thick mode
}
console.log(oracledb.thin ? 'Running in thin mode' : 'Running in thick mode');
//---------------------------------------------------------------------------
// Generates a public-private key pair for proof of possession when token
// requested by this provider is presented for validation.
//---------------------------------------------------------------------------
async function _getKeyPair() {
return await new Promise((resolve, reject) => {
generateKeyPair('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
}
}, (err, publicKey, privateKey) => {
if (err) return reject(err);
resolve({publicKey, privateKey});
});
});
}
//---------------------------------------------------------------------------
// User defined function for reading token and private key values
// generated by the OCI SDK.
// Returns the OCI SDK's token request details object for the given
// config parameters, where a scope parameter specifies the
// scope of requested access. The request will specify a public key
// as being paired with a private key that the presenter of the token must
// prove to be in possession of.
//---------------------------------------------------------------------------
async function getToken(accessTokenConfig) {
const provider =
new common.ConfigFileAuthenticationDetailsProvider(accessTokenConfig.configFileLocation, accessTokenConfig.profile);
const client = new identitydataplane.DataplaneClient({authenticationDetailsProvider: provider});
const keyPair = await _getKeyPair();
const generateScopedAccessTokenDetails = {
scope: "urn:oracle:db::id::*",
publicKey: keyPair.publicKey
};
const generateScopedAccessTokenRequest = {
generateScopedAccessTokenDetails: generateScopedAccessTokenDetails
};
const generateScopedAccessTokenResponse =
await client.generateScopedAccessToken(generateScopedAccessTokenRequest);
const obj = {
token: generateScopedAccessTokenResponse.securityToken.token,
privateKey: keyPair.privateKey
};
return obj;
}
async function callbackfn(refresh, accessTokenConfig) {
// When refresh is true, then the token is invalid or expired.
// So the application must get a new token and store it in cache.
// When refresh is false, then the token is valid and not expired
// but the cache is empty. So the application must get a new token
// and store it in cache.
if (refresh || !accessTokenData) {
accessTokenData = await getToken(accessTokenConfig);
}
// return token from cache
return accessTokenData;
}
async function run() {
// Configuration for token based authentication:
// accessToken: The initial token values
// externalAuth: Must be set to true for token based authentication
// homogeneous: Must be set to true for token based authentication
// connectString: The NODE_ORACLEDB_CONNECTIONSTRING environment
// variable set to the Oracle Net alias or connect
// descriptor of your Oracle Autonomous Database
// accessTokenConfig: Parameter values needed for token generation
// through OCI SDK.
// Configuration for accessTokenConfig:
// profile: optional parameter for config profile name
// default value is 'DEFAULT'
// configFileLocation: optional parameter for config file location
// default value is ~/.oci/config
const config = {
accessToken: callbackfn,
accessTokenConfig: {
profile: process.env.NODE_ORACLEDB_PROFILE,
configFileLocation: process.env.NODE_ORACLEDB_CONFIG_FILE_LOCATION
},
externalAuth: true,
homogeneous: true,
connectString: process.env.NODE_ORACLEDB_CONNECTIONSTRING,
};
try {
// Create pool using token based authentication
await oracledb.createPool(config);
// A real app would call createConnection() multiple times over a long
// period of time. During this time the pool may grow. If the initial
// token has expired, node-oracledb will automatically call the
// accessTokenCallback function allowing you to update the token.
await createConnection();
} catch (err) {
console.error(err);
} finally {
await closePoolAndExit();
}
}
async function createConnection() {
let connection;
try {
// Get a connection from the default pool
connection = await oracledb.getConnection();
const sql = `SELECT TO_CHAR(current_date, 'DD-Mon-YYYY HH24:MI') AS D
FROM DUAL`;
const result = await connection.execute(sql);
console.log("Result is:\n", result);
} catch (err) {
console.error(err);
} finally {
if (connection) {
// Put the connection back in the pool
await connection.close();
}
}
}
async function closePoolAndExit() {
console.log('\nTerminating');
try {
// Get the pool from the pool cache and close it
await oracledb.getPool().close(0);
process.exit(0);
} catch (err) {
console.error(err.message);
process.exit(1);
}
}
process
.once('SIGTERM', closePoolAndExit)
.once('SIGINT', closePoolAndExit);
run();