我有以下代码来生成 JWT 令牌。
public TestTokenGenerator() {
try {
if (signer == null) {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] keySpecBytes = Base64.decodeBase64(getKey());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keySpecBytes);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
signer = new RsaSigner((RSAPrivateKey) privateKey, "SHA512withRSA");
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static void main(String[] args) {
TestTokenGenerator gen = new TestTokenGenerator();
gen.customerJwt("MYUSER");
}
public String customerJwt(String userCode) {
String token = jwt(userCode, "wd.idp.ext.abc.com");
return token;
}
private String jwt(String userCode, String iss) {
Map<String, Object> claims = new HashMap<>();
claims.put("user_name", userCode);
claims.put("sub", userCode);
claims.put("amr", "[aht]");
String jwt = JwtHelper.encode(OBJECT_MAPPER.formatMap(claims), signer).getEncoded();
log.info("User: {}, Token: {}, Claims: {}", userCode, jwt, claims);
return jwt;
}
private String getKey() {
return "WEQRwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCJ2sTFNuBVzhey"
}
如何将标题(例如“kid”:“b0ec688af03dd7875116bf6d36c3584256ieirir”)添加到上述标记中。
令牌头中缺少kid
的上述代码,如下所示
答案 0 :(得分:0)
设法添加了以下额外两行的令牌标头。
Map<String, String> headers = ImmutableMap.of("kid",
"b0ec688af03dd7875116bf6d36c3584256ieirir");
String jwt = JwtHelper.encode(OBJECT_MAPPER.formatMap(claims), signer,
headers).getEncoded();
完整代码:
public TestTokenGenerator() {
try {
if (signer == null) {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] keySpecBytes = Base64.decodeBase64(getKey());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keySpecBytes);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
signer = new RsaSigner((RSAPrivateKey) privateKey, "SHA512withRSA");
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static void main(String[] args) {
TestTokenGenerator gen = new TestTokenGenerator();
gen.customerJwt("MYUSER");
}
public String customerJwt(String userCode) {
String token = jwt(userCode, "wd.idp.ext.abc.com");
return token;
}
private String jwt(String userCode, String iss) {
Map<String, Object> claims = new HashMap<>();
Map<String, String> headers = ImmutableMap.of("kid",
"b0ec688af03dd7875116bf6d36c3584256ieirir"); >>>>>> New Line >>>>>>>
claims.put("user_name", userCode);
claims.put("sub", userCode);
claims.put("amr", "[aht]");
String jwt = JwtHelper.encode(OBJECT_MAPPER.formatMap(claims), signer,
headers).getEncoded(); >>>>>> New Line >>>>>>>>>>>>>>
log.info("User: {}, Token: {}, Claims: {}", userCode, jwt, claims);
return jwt;
}
private String getKey() {
return "WEQRwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCJ2sTFNuBVzhey"
}