Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ yarn.lock
/index.js
validator.js
validator.min.js
.idea

32 changes: 26 additions & 6 deletions src/lib/isJWT.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,35 @@
import assertString from './util/assertString';
import isBase64 from './isBase64';

function decodeBase64Url(str) {
str = str.replace(/-/g, '+').replace(/_/g, '/');
const pad = str.length % 4;
if (pad) str += '='.repeat(4 - pad);

if (typeof Buffer !== 'undefined') {
// Node.js
return Buffer.from(str, 'base64').toString('utf8');
} else if (typeof atob !== 'undefined') {
// Browser
return atob(str);
}
throw new Error('No base64 decoder available');
}

export default function isJWT(str) {
assertString(str);

const dotSplit = str.split('.');
const len = dotSplit.length;
const parts = str.split('.');
if (parts.length !== 3) return false;
try {
const header = JSON.parse(decodeBase64Url(parts[0]));
const payload = JSON.parse(decodeBase64Url(parts[1]));

if (typeof header !== 'object' || header === null) return false;
if (typeof payload !== 'object' || payload === null) return false;
if (typeof header.alg !== 'string') return false;

if (len !== 3) {
return true;
} catch (e) {
return false;
}

return dotSplit.reduce((acc, currElem) => acc && isBase64(currElem, { urlSafe: true }), true);
}
Loading