클라이언트 측에서 JWT 인코딩 토큰 페이로드를 각도 있게 디코딩하는 방법은 무엇입니까?
저는 제 API에서 JWT로 인코딩된 액세스 토큰 하나를 응답으로 받고 있습니다.하지만 저는 그것을 디코딩하여 JSON 형식으로 가져올 수 없습니다.각진 2-jwt 라이브러리를 사용해 보았지만 작동하지 않았습니다.나는 아래에 내 코드를 쓰고 있습니다.
setXAuthorizationToken(client){
let requestHeader = new Headers();
requestHeader.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post(client.clientURL + "oauth/token", 'grant_type=password&client_id=toto&client_secret=sec&' + 'username=' + client.username
+ '&password=' + client.password, {
headers: requestHeader
}).map(res=>res.json())
.subscribe((token) =>{
if(!token.access_token){
return;
}
else{
var decompressToken = LZString.decompressFromEncodedURIComponent(token.access_token);
console.log(decompressToken);
}
});
}
이 문제를 해결하는 것을 도와줄 수 있는 사람이 있습니까?
저는 Angular에서 JWT 토큰을 디코딩하는 데 Auth0의 jwt-decode 패키지를 사용합니다. 이 패키지는 저에게 잘 맞습니다.
이 명령을 사용하여 패키지를 설치한 후:
npm install jwt-decode
다음 구문을 사용하여 이 패키지를 TypeScript 클래스로 가져옵니다.
import * as jwt_decode from "jwt-decode";
또는 최신 버전(3 이상)의 경우:
import jwt_decode from 'jwt-decode';
그런 다음 다음 액세스 토큰을 디코딩하는 데 다음 라이브러리 방법을 사용합니다.
getDecodedAccessToken(token: string): any {
try {
return jwt_decode(token);
} catch(Error) {
return null;
}
}
그token
매개 변수는 API에서 가져온 액세스 토큰을 정의합니다.
그jwt_decode
method는 디코딩된 토큰 정보를 개체로 반환합니다. 토큰의 모든 정보에 액세스할 수 있습니다.
예
const tokenInfo = this.getDecodedAccessToken(token); // decode token
const expireDate = tokenInfo.exp; // get token expiration dateTime
console.log(tokenInfo); // show decoded token object in console
jwt-decode는 Base64Url로 인코딩된 JWT 토큰을 디코딩하는 데 도움이 되는 작은 브라우저 라이브러리입니다.
중요: 이 라이브러리는 토큰의 유효성을 검사하지 않으므로 올바른 형식의 JWT를 디코딩할 수 있습니다.express-jwt, koa-jwt, Owin Bearer JWT 등을 사용하여 서버 측 논리에서 토큰의 유효성을 검사해야 합니다.
JavaScript 빌드인 기능을 사용해 보십시오.atob()
이런 식입니다.
atob(token.split('.')[1])
주의:
토큰은 실제로 문자열입니다.
내가 토큰을 분할한 이유를 알고 싶다면 이 웹사이트 jwt.io 를 확인해야 합니다.
단계 - 1: npm을 사용하여 설치
npm install @auth0/angular-jwt
2단계: 패키지 가져오기
import { JwtHelperService } from '@auth0/angular-jwt';
단계 - 3 : 인스턴스를 만들고 사용합니다.
const helper = new JwtHelperService();
const decodedToken = helper.decodeToken(myRawToken);
// Other functions
const expirationDate = helper.getTokenExpirationDate(myRawToken);
const isExpired = helper.isTokenExpired(myRawToken);
atob
함수가 키릴어나 히브리어를 올바르게 구문 분석하지 못하므로 사용해야 합니다.JwtHelperService().decodeToken(token)
대신.
JWT 서비스를 아래와 같이 정의했습니다!도움이 되길 바랍니다.TypeScript에 있지만 코드를 복사하는 것만으로 바닐라 자바스크립트에서 사용할 수 있습니다.
import { Injectable } from "@angular/core";
@Injectable()
export class JWTService {
private chars: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
private atob(input) {
var str = String(input).replace(/=+$/, '');
if (str.length % 4 == 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (
// initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = '';
// get next character
buffer = str.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = this.chars.indexOf(buffer);
}
return output;
};
parseJwt(token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(this.atob(base64).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
};
}
로그인 시 토큰을 다음과 같이 저장합니다.
localStorage.setItem("token")
그런 다음 다음 다음과 같은 변수를 선언합니다.
decodeToken:any
다음 코드를 사용하여 토큰을 디코딩합니다.
this.decodedToken = this.jwtHelper.decodeToken(localStorage.setItem("token"));
언급URL : https://stackoverflow.com/questions/48075688/how-to-decode-the-jwt-encoded-token-payload-on-client-side-in-angular
'programing' 카테고리의 다른 글
PowerShell 가져오기 모듈 대 도트 소싱 (0) | 2023.08.30 |
---|---|
모바일 장치에서 전화 번호로 하이퍼링크를 만드는 방법은 무엇입니까? (0) | 2023.08.30 |
자바스크립트에서 "|"(단일 파이프)는 무엇을 합니까? (0) | 2023.08.30 |
웹 페이지를 인쇄할 때 요소를 숨기려면 어떻게 해야 합니까? (0) | 2023.08.30 |
작성 및 편집에 동일한 양식을 사용하는 레이블 (0) | 2023.08.30 |