1
1
const axios = require ( 'axios' )
2
+ const jwt = require ( 'jsonwebtoken' )
2
3
const cache = require ( './cache' )
3
4
const token = require ( './token' )
4
5
const { error, fakeReply, verify } = require ( './utils' )
@@ -12,6 +13,40 @@ const pkg = require('../package.json')
12
13
*/
13
14
let options
14
15
16
+ /**
17
+ * @function
18
+ * @private
19
+ *
20
+ * Validate the token offline with help of
21
+ * the related public key. Resolve if the
22
+ * verification succeeded.
23
+ *
24
+ * @param {string } token The token to be validated
25
+ * @returns {Promise } The error-handled promise
26
+ */
27
+ function validateOffline ( token ) {
28
+ return new Promise ( ( resolve , reject ) => {
29
+ jwt . verify ( token , options . publicKey , options . verifyOpts , ( err , decoded ) => {
30
+ if ( err ) {
31
+ reject ( err )
32
+ }
33
+
34
+ resolve ( decoded )
35
+ } )
36
+ } )
37
+ }
38
+
39
+ /**
40
+ * @function
41
+ * @private
42
+ *
43
+ * Validate the token online with help of
44
+ * the related Keycloak server. Resolve if
45
+ * the request succeeded and token is valid.
46
+ *
47
+ * @param {string } token The token to be validated
48
+ * @returns {Promise } The error-handled promise
49
+ */
15
50
function validateOnline ( token ) {
16
51
return axios . post ( `${ options . realmUrl } /protocol/openid-connect/token/introspect` , {
17
52
token,
@@ -30,13 +65,17 @@ function validateOnline (token) {
30
65
* @function
31
66
* @public
32
67
*
33
- * Validate a token with help of Keycloak.
68
+ * Validate a token either with the help of Keycloak
69
+ * or a related public key. Store the user data in
70
+ * cache if enabled.
34
71
*
35
72
* @param {string } token The token to be validated
36
73
* @param {Function } reply The callback handler
37
74
*/
38
75
function handleKeycloakValidation ( tkn , reply ) {
39
- validateOnline ( tkn . get ( ) ) . then ( ( res ) => {
76
+ const validateFn = options . secret ? validateOnline : validateOffline
77
+
78
+ validateFn ( tkn . get ( ) ) . then ( ( ) => {
40
79
const { expiresIn, credentials } = tkn . getData ( options . userInfo )
41
80
const userData = { credentials }
42
81
0 commit comments