Created
December 11, 2022 21:16
-
-
Save ranfysvalle02/6c4f274e886e813e4b78a3721f90e6f6 to your computer and use it in GitHub Desktop.
Implement "Bearer token style auth" workaround
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Implement "Bearer token style auth" workaround | |
----------------------------------------------------- | |
situation where my login code is as follows: | |
curl --location --request POST 'https://realm.mongodb.com/api/client/v2.0/app/aeonxp-dev-zeqxr/auth/providers/custom-function/login' \ | |
--header 'Content-Type: application/json' \ | |
--data-raw '{ | |
"username":"[email protected]", | |
"password":"[email protected]", | |
"meta":{} | |
}' | |
If I want to call a function such as: | |
https://data.mongodb-api.com/app/myapp-abcde/endpoint/test | |
I can do this: | |
-H 'email: <Email Address>' \ | |
-H 'password: <Password>' \ | |
OR | |
-H 'api-key: <API Key>' | |
OR | |
-H 'jwtTokenString: <Custom JSON Web Token>' | |
But there is not an option for a 'custom-function' auth provider | |
I solved it by implementing 'Bearer token' authentication at the function level, and making the function 'system permission level'. | |
I run a 'verify_token' query, pull the custom_data, and verify the person is who they say they are. | |
// This function is the endpoint's request handler. | |
exports = async function({ query, headers, body}, response) { | |
// Data can be extracted from the request as follows: | |
const payload = EJSON.parse(body.text()); | |
var axios = require('axios'); | |
let getBearerToken = async function(){ | |
var data = JSON.stringify({ | |
"username": "<username>", | |
"apiKey": "<apikey>" | |
}); | |
var config = { | |
method: 'post', | |
url: 'https://realm.mongodb.com/api/admin/v3.0/auth/providers/mongodb-cloud/login', | |
headers: { | |
'Content-Type': 'application/json' | |
}, | |
data : data | |
}; | |
let r = await axios(config); | |
return r.data.access_token; | |
}; | |
let bToken = await getBearerToken(); | |
let getActiveUser = async function(){ | |
var data = JSON.stringify({ | |
"token": String(payload.token) | |
}); | |
var config = { | |
method: 'post', | |
url: 'https://realm.mongodb.com/api/admin/v3.0/groups/<groupId>/apps/<appId>/users/verify_token', | |
headers: { | |
'Authorization': 'Bearer '+bToken, | |
'Content-Type': 'application/json' | |
}, | |
data : data | |
}; | |
let r = await axios(config); | |
return r.data; | |
} | |
let au = await getActiveUser(); | |
//au contains active user info | |
//do X if valid user, Y if invalid | |
return au; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment