Readme

assertBearerToken

This val can be used to assert that a valid bearer token exists and has been signed by the secret provided.

Example

const handler = (req, res) => { const authorization = req.get('authorization'); // throws if invalid const token = @neverstew.assertBearerToken(@me.secrets.superSecret, authorization); res.json(token); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
export const assertBearerToken = async (
secret: string,
authHeader: string | null | undefined,
) => {
if (!authHeader)
throw new Error("No header provided");
const jwt = await import("npm:jsonwebtoken");
const token = authHeader.replace(/^Bearer\s+/, "");
if (!token)
throw new Error("No token provided");
return new Promise((resolve, reject) => {
jwt.verify(token, secret, (err, decoded) => {
if (err) {
reject("Invalid token");
}
else {
resolve(decoded);
}
});
});
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023