建立JSON Web令牌(JWT)

JSON Web令牌是一種開放的行業標準RFC 7519方法,用於在雙方之間安全地表示聲明。 本示例使用JWT.io庫生成JWT。
您在上一步中下載的服務憑據包含PKCS#1格式的私鑰。要從此字串中提取私鑰,我們已使用 邦西城堡 庫。 屬於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 will be using 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;

	}

本頁內容