JSON 웹 토큰(JWT) 생성
마지막 업데이트: 2025년 3월 24일
- 적용 대상:
- Experience Manager as a Cloud Service
- 주제:
- 응용 양식
작성 대상:
- 초급
- 중간
- 개발자
JSON 웹 토큰은 두 당사자 간의 클레임을 안전하게 표현하기 위한 개방형 업계 표준 RFC 7519 메서드입니다. 이 샘플에서는 JWT.io 라이브러리를 사용하여 JWT를 생성했습니다.
이전 단계에서 다운로드한 서비스 자격 증명에는 PKCS#1 형식의 개인 키가 포함되어 있습니다.이 문자열에서 개인 키를 추출하려면 BouncyCastle 라이브러리를 사용했습니다. Java의 일부인 암호화 라이브러리는 PKCS#1 형식을 지원하지 않습니다.
다음 코드는 JWT를 생성하는 데 사용되었습니다.
public String getJWTToken()
{
Security.addProvider(new BouncyCastleProvider());
RSAPrivateKey privateKey = null;
GetServiceCredentials getCredentials = new GetServiceCredentials();
try
{
long now = System.currentTimeMillis();
Long expirationTime = now + TimeUnit.MINUTES.toMillis(5);
// get the private key string from the service credentials
String privateKeyString = getCredentials.getPRIVATE_KEY();
//The JWT signature algorithm we use to sign the token
SignatureAlgorithm sa = SignatureAlgorithm.RS256;
Reader targetReader = new StringReader(privateKeyString);
// PEMParser removes the unnecessary headers and decodes the underlying Base64 PEM data into a binary format.
PEMParser pemParser = new PEMParser(targetReader);
// tores the result generated by the pEMParser
Object object = pemParser.readObject();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
KeyPair kp = converter.getKeyPair((PEMKeyPair) object);
privateKey = (RSAPrivateKey) kp.getPrivate();
//Let's set the JWT Claims
Map < String, Object > jwtClaims = new HashMap < String, Object > ();
jwtClaims.put("iss", getCredentials.getORG_ID());
jwtClaims.put("sub", getCredentials.getTECH_ACCT());
jwtClaims.put("exp", expirationTime);
jwtClaims.put("aud", "https://" + getCredentials.getIMS_ENDPOINT() + "/c/" + getCredentials.getCLIENT_ID());
String metascopes[] = new String[] { getCredentials.getMETASCOPE_ID() };
for (String metascope: metascopes)
{
jwtClaims.put("https://" + getCredentials.getIMS_ENDPOINT() + "/s/" + metascope, java.lang.Boolean.TRUE);
}
// Create the final JWT token
String jwtToken = Jwts.builder().setClaims(jwtClaims).signWith(sa, privateKey).compact();
System.out.println("Got JWT Token " + jwtToken);
pemParser.close();
return jwtToken;
} catch (IOException e) {
System.out.println("The error is " + e.getMessage());
}
return null;
}