How to manage session in supertokens? - nestjs

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.

Related

remove headers authorization in next.handle().pipe() if no header is sent

I set up a request interceptor for calls from external APIs.
Everything is going well with a few exceptions..
export class HttpServiceExternalInterceptor implements NestInterceptor {
constructor(private httpService: HttpService) {}
async intercept(
context: ExecutionContext,
next: CallHandler,
): Promise<Observable<any>> {
const ctx = context.switchToHttp();
const token = ctx.getRequest().headers[AUTHORIZATION];
this.httpService.axiosRef.interceptors.request.use(req => {
if (
token &&
req.url.includes(API_XXX_EXTERNAL_URL) &&
!req?.headers?.common[AUTHORIZATION]
) {
req.headers.common[AUTHORIZATION] = token;
}
return req;
});
if(!token){
//clear headers here before send request to external api????
}
return next.handle().pipe();
}
}
Only I have a small problem, when I send the curl with authorization, the external api receives well the authorization but if I send a curl again without authorization, the external api still receives the previous authorization.
I don't understand the second case?
and I don't know how I can clear the headers when the authorisdddd is not defined
Thank you for your help.

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.

Basic authentication and passing token to next endpoint

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.

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));

curl req into firebase functions req

Hello I am following the instructions to implement an encryption payment from from Adyen. I am using Firebase as my backend. Now the Dokumentation want that I make a backend req like this:
curl -u "ws#Company.SomeCompany":"SomePassword" \
-H "Content-Type: application/json" \
-X POST \
--data \
'{
"additionalData": {
"card.encrypted.json":"adyenjs_0_1_4p1$..."
},
"amount" : {
"value" : 10000,
"currency" : "EUR"
},
"reference" : "Your Reference Here",
"merchantAccount" : "TestMerchant" }'\
https://pal-test.adyen.com/pal/servlet/Payment/v30/authorise
Can someone please help me to convert this curl request into an firebase functions request? For example:
exports.helloWorld = (req, res) => {
if (req.body.message === undefined) {
// This is an error case, as "message" is required
res.status(400).send('No message defined!');
} else {
// Everything is ok
console.log(req.body.message);
res.status(200).end();
}
};
You need to pass your Adyen credentials as data in http post request. Add firebase user token as Bearer token in Authroization token. So now your function will be:
exports.helloWorld = (req, res) => {
// check authorization of firebase.
if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) {
res.status(403).send('Unauthorized');
return;
}
const idToken = req.headers.authorization.split('Bearer ')[1];
this.admin.auth().verifyIdToken(idToken).then(decodedIdToken => {
// new read the data like below
// req.body.username , req.body.additionalData
})
};

Resources