Basic authentication and passing token to next endpoint - node.js

I am new to basic authentication and tokens.
I have been playing around with postman in order to get a token using basic authentication and then passing the token as a bearer token to access another endpoint. I wanted to know how I would code this into api calls using node and express.
I know that for Basic auth I need to encode the client id and secret into base64
curl --request POST \
--url http://localhost:8080/token/ \
--header 'authorization: Basic ***' \
--header 'content-type: application/x-www-form-urlencoded' \
--data
grant_type=credentials
The token I get from the above call I want to pass onto the below call
curl --request POST \
--url http://localhost:8080/login \
--header 'authorization: Bearer ***' \
--header 'content-type: application/x-www-form-urlencoded' \
--data
user=1
How would this like as code in a node application

I would recommend json web token aka jwt for this purpose.
Right now I code REST API in express, mongodb, and I am using jwt for auth.
Since I dont use any frontend framework or lib, I use cookie for jwt token storage.
const jwt = require('jsonwebtoken');
const generateToken = (res, id, auth_level) => {
const token = jwt.sign({id,
auth_level
}, process.env.JWT_KEY, {
expiresIn: '7d'
});
return res.cookie('token', token, {
expires: new Date(Date.now() + 1000 * 60 * 15),
secure: false,
httpOnly: true,
});
};
module.exports = generateToken
In this example I call this function on sucessful login try. And after that on every route access, using middleware I try to resolve if user have this token and try to resolve token.
const jwt = require('jsonwebtoken');
// Verify user token from cookie
const verifyToken = async (req, res, next) => {
// Get token from cookie named token
const token = req.cookies.token || '';
try {
// Check if cookie exists, maybe expired maybe user didnt have one - no login
if (!token) {
return next();
}
// Decrypt users jwt token and get information
const decrypt = await jwt.verify(token, process.env.JWT_KEY);
// Pass that infomation to request user object
req.user = {
id: decrypt.id,
auth_level: decrypt.auth_level,
test: 'test'
};
// Continue with exectution of app
return next();
} catch (err) {
return res.status(500).json(err.toString());
}
};
module.exports = verifyToken;
If this token is valid, I pass custom user object to req object.
After this I protect routes with custom middlewares. Code is inspired by this tutorial, would recommend it.

Related

How to manage session in supertokens?

I am using the supertokens-node library to manage users in my nest.js app.
I want to protect some of the routes and for that I am using the verifySession method of the supertokens. I am using the postman to test the routes but I am getting unauthorised in the response.
This is the AuthGaurd function as per the docs:
#Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly verifyOptions?: VerifySessionOptions) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const ctx = context.switchToHttp();
let err = undefined;
const resp = ctx.getResponse();
// You can create an optional version of this by passing {sessionRequired: false} to verifySession
await verifySession(this.verifyOptions)(ctx.getRequest(), resp, (res) => {
err = res;
});
if (resp.headersSent) {
throw new STError({
message: 'RESPONSE_SENT',
type: 'RESPONSE_SENT',
});
}
if (err) {
throw err;
}
return true;
}
}
This is the endpoint that is I have applied the AuthGuard
#Post('/bulkAddUpdate')
#UseGuards(new AuthGuard())
async builkAddUpdate(
#Body() bulkData: any,
#Session() session: SessionContainer
) {
console.log(session.getUserId());
const user = await this.applicationService.bulkAction(bulkData.data);
if (user) {
return utils.sendSuccess(SUCCESS.S200.DEFAULT, user);
} else {
throw new NotFoundException();
}
}
As per the docs when I sign-in I have to set the headers rid(key) : session(value) in the signin method but when I hit the request I am getting 404 route not found error. But when I remove rid from the headers then it works perfectly fine.
And I am also setting headers as rid : session to my protected route but I am getting unauthorised in the response.
This is the cURL request:
curl --location --request POST 'http://localhost:9000/applications' \
--header 'rid: thirdpartyemailpassword' \
--header 'Content-Type: application/json' \
--header 'Cookie: pga4_session=887a38e7-589c-4faa-9bbe-139e9145b535!iTseBPH6uzAlV9Mbaap/agtBJ6GymXNDEp+4cgySEdA=; sFrontToken=eyJ1aWQiOiJkMzU0ZTJlOS1hNGVlLTQwOGYtYTQ5My0yYjQ1NjBhYWFiYzkiLCJhdGUiOjE2NzU0MjMzODc4NDAsInVwIjp7ImlzUGFzc3dvcmRsZXNzIjpmYWxzZX19; sIRTFrontend=d131494f-dbd8-4a21-a5a8-3959bb2d4fd1' \
--data-raw '{
"userID": 2,
"applicationContent": "<html><body>Anything...</body></html>",
"applicationType": 200
}'
The sign in API should not have the rid as session. The rid should be set to the recipe you are using that exposes the signin API. For example, if you are using the EmailPassword recipe, you want to set the rid to emailpassword when querying the sign in API.
Once you call the sign in API successfully, you should get back session tokens in cookies which are managed by Postman.
Then when you query your protected API, Postman should automatically add the sAccessToken cookie in the request which is verified by the supertokens-node SDK.

Send message with Google Business Messages using access token

Currently I can send a message with Google Business Messages API from an agent to a user from NodeJS code.
const bmApi = new businessmessages.businessmessages_v1.Businessmessages({});
This requires an auth client for a given service account key/secret.
const auth = new GoogleAuth({
keyFilename: '/home/my-keyfile.json',
scopes: 'https://www.googleapis.com/auth/businessmessages',
});
const authClient = await auth.getClient();
// and logic to send message
However the key/secret is hard-coded at the moment.
But at this point in the flow I have the access token.
And want to use that instead of the .json file.
But it will not accept the access token.
Another approach is to directly call the REST interface.
https://developers.google.com/business-communications/business-messages/guides/how-to/message/send
curl -X POST https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-messages" \
-H "$(oauth2l header --json ./service_account_key.json businessmessages)" \
-d "{
'messageId': '$(uuidgen)',
'text': 'Hello world!',
'representative': {
'avatarImage': 'https://developers.google.com/identity/images/g-logo.png',
'displayName': 'Chatbot',
'representativeType': 'BOT'
}
}"
Added a header with token.
access_token: <access-token>
But again no joy.
{
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
I know this should work as we do it for calls to Google Play Store:
try {
let response = await this.httpClient.post({
url: `${process.env.PLAYSTORE_URL}/${packageName}/reviews/${reviewId}:reply`,
body : {
"replyText" : replyText
},
query: {
access_token: access_token <----
}
});
Any help would be much appreciated.
i think you need to use the variable that match the current CONVERSATION_ID in the url path, with the currently one of each agent message received.
Example:
curl -X POST https://businessmessages.googleapis.com/v1/conversations/$(uuidgen)/messages \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-messages" \
-H "$(oauth2l header --json ./service_account_key.json businessmessages)" \
-d "{
'messageId': '$(uuidgen)',
'text': 'Hello world!',
'representative': {
'avatarImage': 'https://developers.google.com/identity/images/g-logo.png',
'displayName': 'Chatbot',
'representativeType': 'BOT'
}
}"

getting 404, firebase + node.js, using "projects.locations.instances.create"

I'm trying to make an instance of a database with node.js in firebase realtime database.
My node.js route looks like this:
const axios = require('axios');
var {google} = require("googleapis");
var serviceAccount = require("paht/to/json");
router.post('/createnewdatabase', function (req, res) {
//scopes used for the create
var scopes = [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/firebase"
];
// Authenticate a JWT client with the service account.
var jwtClient = new google.auth.JWT(
serviceAccount.client_email,
null,
serviceAccount.private_key,
scopes
);
// Use the JWT client to generate an access token.
jwtClient.authorize(function(error, tokens) {
if (error) {
console.log("Error making request to generate access token:", error);
} else if (tokens.access_token === null) {
console.log("Provided service account does not have permission to generate access tokens");
} else {
var accessToken = tokens.access_token;
let apiKey = req.body.apiKey;
const config = {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken
},
};
axios({
method: 'post',
url: 'https://firebasedatabase.googleapis.com/v1beta/projects/{project-id}/locations/europe-west1',
data: {
key: apiKey,
databaseId: 'segesggseg-656-sdgsdgs',
},
config
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
res.send('POST request to the homepage')
}
});
})
I'm getting a 404 when trying to call the route. I'm guessing it's something with the tokens. The documentation is here: https://firebase.google.com/docs/reference/rest/database/database-management/rest/v1beta/projects.locations.instances/create
I can't figure it out :-)
Please consider that according to the official documetation link:
"name field - Currently the only supported location is 'us-central1'."
I was able to create an instance using the api only with empty data parameter.
'https://firebasedatabase.googleapis.com/v1beta/projects/111111111111/locations/us-central1/instances?databaseId=myinstanceiddd&validateOnly=true&key=[YOUR_API_KEY]' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{}' \
--compressed
200
{
"name": "projects/111111111111/locations/us-central1/instances/myinstanceiddd",
"project": "projects/111111111111",
"databaseUrl": "https://myinstanceiddd.firebaseio.com",
"type": "USER_DATABASE",
"state": "ACTIVE"
}
After answer above did not work for me... I was forced to read docs (https://firebase.google.com/docs/reference/rest/database/database-management/rest/v1beta/projects.locations.instances/create) word by word...
Second paragraph says that ur project needs to be on the Blaze plan in order to be able to create instance... After this doing this, it now works for me.

NodeJS / Express: Get Username and Password from Request

I am using NodeJS and Express, and I want to get the Username and Password parameters from a request. I've searched for a while now, and I can't find my answer.
I want to accept a user parameter from a cURL command:
curl --request --POST -u USERNAME:PASSWORD -H "Content-Type:application/json" -d "{\"key":\"value\"}" --url https://api.example.com/my_endpoint
In my application:
app.post('/my_endpoint', async (req, res, next) => {
const kwargs =. req.body;
const userName = req['?'];
const password = req['?'];
});
You are sending the credentials as a basic-auth header (since you're using curl's -u option). So in order to get the credentials from your request, you need to access this header and decode it. Here's one way to do this:
app.post('/my_endpoint', async (req, res, next) => {
if(req.headers.authorization) {
const base64Credentials = req.headers.authorization.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('utf8');
const [username, password] = credentials.split(':');
console.log(username, password);
}
});
How do I consume the JSON POST data in an Express application
I would do it this way
Assuming your call includes json content like this :
Remove -u USERNAME:PASSWORD
Edit -d "{ "username": "user", "password": "test" }"
curl --request --POST -H "Content-Type:application/json" -d "{ "username": "user", "password": "test" }" --url https://api.example.com/my_endpoint
Then you can access those variables with :
const userName = req.body.username;
const password = req.body.password;
Be careful, you need to use bodyParser middleware in express in order to be able to access the body variables.

Axios Basic Auth with API key Example in Node

There is a curl request like this:
curl -X GET --header 'Accept: application/json' --header 'Authorization: Basic [==APIKEYHERE==]' 'https://apipath.com/path?verbose=true'
I removed the APIKEY and the API path for privacy.
The curl request is working fine, I can't figure out how to convert this into an Axios request since it only needs an API key and not a username and password.
Here is the example I found:
axios.get('https://apipath.com/path?verbose=true', {}, {auth: {username: 'username', password: 'password'}})
.then(function(response) {
console.log(response.data, 'api response');
})
I'm not sure how to get this to work for my case?
The short answer to adding an X-Api-Key to an http request with axios can be summed up with the following example:
const url =
"https://someweirdawssubdomain.execute-api.us-east-9.amazonaws.com/prod/custom-endpoint";
const config = {
headers: {
"Content-Type": "application/json",
},
};
// Add Your Key Here!!!
axios.defaults.headers.common = {
"X-API-Key": "******this_is_a_secret_api_key**********",
};
const smsD = await axios({
method: "post",
url: url,
data: {
message: "Some message to a lonely_server",
},
config,
});
I was stuck for 8 hours trying to figure this out as the errors lined up in the queue, adding the key to the default headers was the only way I could get this to work.
Given the cURL command including --header 'Authorization: Basic [==APIKEYHERE==]', you know that the server wants a header sent using the Basic authentication scheme. That means that your API key is both the username and password joined by a : and encoded with Base64. So, you can decode what the username and password should be by decoding your API key with Base64 and seeing the values joined by the colon.
Consider the spec detailed on MDN: Authorization Header
So if your API key is Ym9iOnBhc3N3b3JkMQ==, and you decode it with Buffer.from("API_KEY", "base64").toString(), you would get the value bob:password1 meaning your username is bob and your password is password1 making your request:
const [username, password] = Buffer.from("YOUR_API_KEY", "base64").toString().split(":");
axios.get('https://apipath.com/path?verbose=true', {}, {
auth: {
username,
password
}
})
.then(function(response) {
console.log(response.data, 'api response');
})
You can define a function like this, then you can pass the token to header after login success.
import axios from "axios";
const setAuthToken = token => {
if (token) {
// Apply to every request
axios.defaults.headers.common["Authorization"] = token;
} else {
// Delete auth header
delete axios.defaults.headers.common["Authorization"];
}
};
axios.get('https://apipath.com/path?verbose=true', {}, {auth: {username: 'username', password: 'password'}})
.then(() => setAuthToken(response.token));

Resources