如何在不使用库的情况下在 javascript 中解码 jwt 令牌?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38552003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to decode jwt token in javascript without using a library?
提问by Chrisk8er
How can I decode the payload of JWT using JavaScript? Without a library. So the token just returns a payload object that can consumed by my front-end app.
如何使用 JavaScript 解码 JWT 的有效负载?没有图书馆。所以令牌只返回一个负载对象,我的前端应用程序可以使用它。
Example token: xxxxxxxxx.XXXXXXXX.xxxxxxxx
示例令牌: xxxxxxxxx.XXXXXXXX.xxxxxxxx
And the result is the payload:
结果是有效载荷:
{exp: 10012016 name: john doe, scope:['admin']}
回答by Peheje
Working unicode text JWT parser function:
工作 unicode 文本 JWT 解析器功能:
function parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
};
回答by Rajan Maharjan
Simple function with try - catch
带有 try-catch 的简单功能
const parseJwt = (token) => {
try {
return JSON.parse(atob(token.split('.')[1]));
} catch (e) {
return null;
}
};
Thanks!
谢谢!
回答by Guy
You can use jwt-decode, so then you could write:
您可以使用jwt-decode,然后您可以编写:
import jwt_decode from 'jwt-decode';
var token = 'eyJ0eXAiO.../// jwt token';
var decoded = jwt_decode(token);
console.log(decoded);
/*{exp: 10012016 name: john doe, scope:['admin']}*/
回答by Muhammed Moussa
you can use pure javascript atob()
function to decode token into a string:
您可以使用纯 javascriptatob()
函数将令牌解码为字符串:
atob(token.split('.')[1]);
or parse directly it into a json object:
或者直接解析成json对象:
JSON.parse(atob(token.split('.')[1]));
read about atob()
and btoa()
built-in javascript functions Base64 encoding and decoding - Web APIs | MDN.
阅读atob()
和btoa()
内置javascript 函数Base64 编码和解码- Web APIs | MDN。
回答by Avik
As "window" object is not present in nodejs environment, we could use the following lines of code :
由于 nodejs 环境中不存在“window”对象,我们可以使用以下代码行:
let base64Url = token.split('.')[1]; // token you get
let base64 = base64Url.replace('-', '+').replace('_', '/');
let decodedData = JSON.parse(Buffer.from(base64, 'base64').toString('binary'));
It's working for me perfectly. Hope it helps.
它非常适合我。希望能帮助到你。
回答by Rafael Quintela
@Peheje will work, but you will have problem with unicode. To fix it I use the code on https://stackoverflow.com/a/30106551/5277071;
@Peheje 会工作,但你会遇到 unicode 问题。为了修复它,我使用https://stackoverflow.com/a/30106551/5277071上的代码;
let b64DecodeUnicode = str =>
decodeURIComponent(
Array.prototype.map.call(atob(str), c =>
'%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
).join(''))
let parseJwt = token =>
JSON.parse(
b64DecodeUnicode(
token.split('.')[1].replace('-', '+').replace('_', '/')
)
)
let form = document.getElementById("form")
form.addEventListener("submit", (e) => {
form.out.value = JSON.stringify(
parseJwt(form.jwt.value)
)
e.preventDefault();
})
textarea{width:300px; height:60px; display:block}
<form id="form" action="parse">
<textarea name="jwt">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkrDtGhuIETDs8OoIiwiYWRtaW4iOnRydWV9.469tBeJmYLERjlKi9u6gylb-2NsjHLC_6kZNdtoOGsA</textarea>
<textarea name="out"></textarea>
<input type="submit" value="parse" />
</form>
回答by Softmixt
I use this function to get payload , header , exp(Expiration Time), iat (Issued At) based on thisanswer
我使用此函数根据此答案获取有效负载、标头、exp(到期时间)、iat(发布于)
function parseJwt(token) {
try {
// Get Token Header
const base64HeaderUrl = token.split('.')[0];
const base64Header = base64HeaderUrl.replace('-', '+').replace('_', '/');
const headerData = JSON.parse(window.atob(base64Header));
// Get Token payload and date's
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
const dataJWT = JSON.parse(window.atob(base64));
dataJWT.header = headerData;
// TODO: add expiration at check ...
return dataJWT;
} catch (err) {
return false;
}
}
const jwtDecoded = parseJwt('YOUR_TOKEN') ;
if(jwtDecoded)
{
console.log(jwtDecoded)
}
回答by SHUBHAM JASWAL
function parseJwt(token) {
var base64Payload = token.split('.')[1];
var payload = Buffer.from(base64Payload, 'base64');
return JSON.parse(payload);
}
let payload= parseJwt("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c");
console.log("payload:- ", payload);
If using node, you might have to use buffer package:
如果使用节点,您可能必须使用缓冲包:
npm install buffer
var Buffer = require('buffer/').Buffer
回答by Nao Ito
I found this code at jwt.ioand it works well.
我在jwt.io 上找到了这段代码,它运行良好。
//this is used to parse base64
function url_base64_decode(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!';
}
var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
try{
return decodeURIComponent(escape(result));
} catch (err) {
return result;
}
}
In some cases(certain development platforms),
the best answer(for now)faces a problem of invalid base64 length.
So, I needed a more stable way.
在某些情况下(某些开发平台),
最佳答案(目前)面临 base64 长度无效的问题。
所以,我需要一种更稳定的方式。
I hope it would help you.
我希望它会帮助你。
回答by Jithin Vijayan
all features of jwt.io doesn't support all languages. In NodeJs you can use
jwt.io 的所有功能并不支持所有语言。在 NodeJs 中,您可以使用
var decoded = jwt.decode(token);