JWT token script:
import com.sap.gateway.ip.core.customdev.util.Message;
import io.jsonwebtoken.Claims
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.Header
import io.jsonwebtoken.JwtBuilder
import io.jsonwebtoken.SignatureAlgorithm
import io.jsonwebtoken.impl.DefaultClaims
import java.security.KeyFactory
import java.security.PrivateKey
import java.security.spec.EncodedKeySpec
import java.security.spec.PKCS8EncodedKeySpec
import java.time.LocalDateTime;
import java.time.ZoneId
def Message processData(Message message) {
def mProp = message.getProperties();
String keyString = mProp.get("privateKey"); // Provided by the receiver.
LocalDateTime now = LocalDateTime.now();
Date nowDate = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
Date expDate = Date.from(now.plusMinutes(60).atZone(ZoneId.systemDefault()).toInstant());
Map<String, Object> header = new HashMap<String, Object>();
header.put("alg", "PS256");
header.put("typ", "JWT");
String kid = mProp.get("kid");
header.put("kid", kid);
message.setProperty("JWT Token Header",header)
Claims claims = new DefaultClaims();
String iss = mProp.get("clientID");
claims.put("iss", iss);
claims.put("scope", "restlets,rest_webservices");
String aud = mProp.get("Audience");
claims.put("aud", aud);
//claims.put("region","dummy");
message.setProperty("JWT Token Payload",claims);
/* Create JWT json with JwtBuilder */
JwtBuilder jwtBuilder = Jwts.builder()
.setClaims(claims)
.setIssuedAt(nowDate)
.setExpiration(expDate)
.setHeader((Map<String, Object>) header);
byte[] keyBytes = Base64.getDecoder().decode(keyString);
KeyFactory kf = KeyFactory.getInstance("RSA");
EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
PrivateKey privateKey = kf.generatePrivate(keySpec);
String jwtToken = (jwtBuilder.signWith(SignatureAlgorithm.PS256, kf.generatePrivate(keySpec)).compact());
message.setBody(jwtToken)
return message;
}
After that need to get the assertion and set signed jwt with below script.
Set Signed JWT:
import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
def Message processData(Message message) {
def assertion = message.getBody(java.lang.String) as String;
body = "grant_type=client_credentials" + "&client_assertion_type="+"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"+"&client_assertion="+assertion;
message.setHeader("Content-Type", "application/x-www-form-urlencoded");
message.setBody(body);
return message;
}
No comments:
Post a Comment