mirror of
https://github.com/directus/directus.git
synced 2026-01-29 14:07:57 -05:00
Add is-jwt util
This commit is contained in:
31
src/utils/is-jwt.ts
Normal file
31
src/utils/is-jwt.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import atob from 'atob';
|
||||
|
||||
/**
|
||||
* Check if a given string conforms to the structure of a JWT.
|
||||
*/
|
||||
export default function isJWT(string: string) {
|
||||
const parts = string.split('.');
|
||||
|
||||
// JWTs have the structure header.payload.signature
|
||||
if (parts.length !== 3) return false;
|
||||
|
||||
// Check if all segments are base64 encoded
|
||||
try {
|
||||
atob(parts[0]);
|
||||
atob(parts[1]);
|
||||
atob(parts[2]);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if the header and payload are valid JSON
|
||||
try {
|
||||
JSON.parse(atob(parts[0]));
|
||||
JSON.parse(atob(parts[1]));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
Reference in New Issue
Block a user