'How to get userId from token?
I'm coding a simple get endpoint, and I send from front-end header the token information. But in back-end I need to use userId. I think it is available on token, but how can I get userId from token?
// React Front End service
const response = await fetch(
`${process.env.REACT_APP_API_HOST}/export-data/pdf?${urlParams}`,
{
headers: {
...authService.authHeader(),
Authorization: `Bearer ${authService.getToken()}`,
},
}
);
// Nestjs Back End controller
@UseGuards(AuthGuard)
@Permissions('admin')
@Get('/pdf')
async exportDataPdf(@Query() query: GetOrdersFilterDto): Promise<any> {
// I need to use userId from token here.
return await this.exportDataService.exportDataPdf(query);
}
Solution 1:[1]
It depends on how you sign this.jwtService.sign() while signIn a user / while generating jwt token.
For example if you use
this.jwtService.sign({ userId: user._id });
Then you can simply do this on your controller
@Get('profile')
getUserId(@Request() req: any) {
return req.user.userId;
}
Note req.user object is used internally by nestjs to store jwt payload data.
In case you want any data you provide on jwt in a nestjs guard. You can also get access it from req object.
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const [req] = context.getArgs();
// console log user ID
console.log(req.user.userId);
// create your conditional logic here before return true
return true;
}
Solution 2:[2]
You can make a method called getUserIdFromToken and use it for that. If bcrypt was used to create the token out of the email, you can get the email back from it.
Here is how I did it in node:
- Encode the token
const hashData = { email: user.email }
const accessToken = jwt.sign(hashData, process.env.ACCESS_TOKEN_SECRET)
- Decode the token
const email = jwtDecode(token).email;
Then, you can retrieve the user with the email.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ikdemm |
