1.先生成一个客户端的私钥
keytool -genkeypair -keystore mykeystore.jks -alias myPcsClient -storepass welcome1 -keypass welcome1 -keyalg RSA -sigalg SHA1WithRSA -dname "CN=myPcsClient"
2.list一下确保没问题
keytool -list -keystore mykeystore.jks -storepass welcome1 -v [[email protected] ~]$ keytool -list -keystore mykeystore.jks -storepass welcome1 -v Keystore type: JKS Keystore provider: SUN Your keystore contains 2 entries Alias name: mypcsclient Creation date: Aug 22, 2017 Entry type: PrivateKeyEntry Certificate chain length: 1 Certificate[1]: Owner: CN=myPcsClient Issuer: CN=myPcsClient Serial number: 57b1c3b1 Valid from: Tue Aug 22 11:48:19 CST 2017 until: Mon Nov 20 11:48:19 CST 2017 Certificate fingerprints: MD5: 17:0D:1F:8A:97:7A:B6:C9:C8:7B:36:F4:15:0A:2D:1B SHA1: EE:06:83:DF:F9:7F:85:71:1F:7B:A6:CD:CF:54:CC:EC:7D:E0:04:43 SHA256: FA:33:2B:21:CC:4F:42:07:53:F2:FF:07:F7:6E:94:77:C8:06:D9:6B:38:D5:F8:AA:F1:52:55:D6:3C:B3:99:10 Signature algorithm name: SHA1withRSA Version: 3 Extensions: #1: ObjectId: 2.5.29.14 Criticality=false SubjectKeyIdentifier [ KeyIdentifier [ 0000: 4D 67 E4 CD 96 2E 87 AF 1C E5 AF 4E 16 76 B9 6C Mg.........N.v.l 0010: 5F 7A D1 3B _z.; ] ] ******************************************* ******************************************* Alias name: mykey Creation date: Aug 22, 2017 Entry type: PrivateKeyEntry Certificate chain length: 1 Certificate[1]: Owner: CN=myPcsClient Issuer: CN=myPcsClient Serial number: 2f0e108c Valid from: Tue Aug 22 10:45:24 CST 2017 until: Fri Aug 20 10:45:24 CST 2027 Certificate fingerprints: MD5: A4:BE:28:54:FB:8F:7D:E5:A9:28:4F:85:3F:B2:B4:C7 SHA1: B1:4B:65:AB:EA:F9:BC:70:99:5B:76:4B:7C:1A:10:AD:79:33:B0:90 SHA256: DD:3A:C2:0A:8E:C4:E7:D9:8F:62:4A:04:9F:82:9A:FC:99:B7:C4:97:2C:1A:B1:39:20:EF:D9:55:77:71:80:96 Signature algorithm name: SHA256withRSA Version: 3 Extensions: #1: ObjectId: 2.5.29.14 Criticality=false SubjectKeyIdentifier [ KeyIdentifier [ 0000: A6 8A 05 76 9E EC F3 A1 B6 88 50 2E B6 DE 22 8D ...v......P...". 0010: A3 4C C3 8E .L.. ] ] ******************************************* *******************************************
3.导出一个oauth的cer文件
keytool -exportcert -alias myPcsClient -keystore mykeystore.jks -file mykeyoauthclient.cer
4.在PCS的Oauth Administration界面上注册一个trust client
注册的时候选择trust,然后输入cer文件
5.将生成的jks,cer放入jdeveloper中,进行调用就可
package test.oracle.oauth; import com.sun.xml.internal.bind.v2.model.core.ID; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.MessageDigest; import java.security.PrivateKey; import java.security.Signature; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.codec.binary.Base64; import org.json.simple.JSONValue; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URL; import java.security.GeneralSecurityException; import java.security.KeyStore; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import java.net.HttpURLConnection; @SuppressWarnings("unchecked") public class OauthUserAssertionGenerator { // Make sure the following settings are correct private static String keystoreFile = "mykeystore.jks"; private static String keystorePassword = "welcome1"; // private static String alias = "TestOAuthClient"; private static String alias = "myPcsClient"; private static String keyPassword = "welcome1"; private static String identityDomainName = "a508150"; private static String clientID = "368e9de3-f662-4d4a-91fe-742615a1559f"; // client id of the trusted client private static String clientSecret = "pkwovUWMUlTfMpLTNeM2"; // client secret of the registered client private static String pcsUsername = "[email protected]"; // username of the user trying to access PCS private static String curlCommand = "curl -i -H ‘Content-Type: application/x-www-form-urlencoded;charset=UTF-8‘ -H ‘X-USER-IDENTITY-DOMAIN-NAME: #IDENTITY_DOMAIN_NAME‘ -H ‘Authorization: Basic #AUTHENTICATION_STRING‘ --request POST https://a508150.identity.europe.oraclecloud.com/oauth2/tokens -d ‘grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer&assertion=#USER_ASSERTION‘"; private static X509Certificate cert = null; private static PrivateKey privateKey = null; public OauthUserAssertionGenerator() { super(); } public static void main(String[] args) { String aa = returnuserAssertion("[email protected]"); System.out.println("============"+aa); } // end main public static void getClientKeyPair() { InputStream input = null; try { // Keystore type ex: jks KeyStore keystore = KeyStore.getInstance("jks"); // Path where the keystore file is placed input = new FileInputStream(keystoreFile); // Keystore password given during key generation keystore.load(input, keystorePassword.toCharArray()); // keyAlias is the name given for the key during key generation privateKey = (PrivateKey) keystore.getKey(alias, keyPassword.toCharArray()); cert = (X509Certificate) keystore.getCertificate(alias); } catch (Exception ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } } // end getClientCert() public static String returnuserAssertion(String username) { try { // The goal of this program is to generate a working curl command // to retrieve an OAuth access token. // Replace the identity domain first curlCommand = curlCommand.replaceAll("#IDENTITY_DOMAIN_NAME", identityDomainName); // Generate an authentication string String authenticationString = Base64.encodeBase64URLSafeString((clientID+":"+clientSecret).getBytes("utf8")); curlCommand = curlCommand.replaceAll("#AUTHENTICATION_STRING", authenticationString); // Now working on user assertion string getClientKeyPair(); // Prepare header Map<Object, Object> headerMap = new HashMap<Object, Object>(); MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); // SHA-256 // Get the client certificate sha1.update(cert.getEncoded()); byte[] sha1thumbPrint = sha1.digest(); headerMap.put("x5t", Base64.encodeBase64URLSafeString(sha1thumbPrint)); headerMap.put("typ", "JWT"); headerMap.put("alg", "RS256"); String headerAsString = JSONValue.toJSONString(headerMap); String encodedHeader = Base64.encodeBase64URLSafeString(headerAsString.getBytes("utf8")); // Prepare body long currentTime = System.currentTimeMillis(); Map<Object, Object> payloadMap = new HashMap<Object, Object>(10); payloadMap.put("iss", clientID ); payloadMap.put("jti", UUID.randomUUID().toString()); //changed to parameter by ericnie payloadMap.put("prn", username); payloadMap.put("sub", username); payloadMap.put("iat", currentTime); payloadMap.put("exp", currentTime + 360000000L); List l = new ArrayList(); l.add("oauth.idm.oracle.com"); payloadMap.put("aud", l); payloadMap.put("oracle.oauth.prn.id_type", "LDAP_UID"); payloadMap.put("oracle.oauth.sub.id_type", "LDAP_UID"); payloadMap.put("user.tenant.name", identityDomainName); String payloadAsString = JSONValue.toJSONString(payloadMap); String encodedPayload = Base64.encodeBase64URLSafeString(payloadAsString.getBytes("utf8")); // Sign the user assertion String toSign = encodedHeader + "." + encodedPayload; byte[] inputBytes = toSign.getBytes("utf8"); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(privateKey); signature.update(inputBytes); byte[] signatureBytes = signature.sign(); String encodedSignature = Base64.encodeBase64URLSafeString(signatureBytes); String userAssertion = toSign + "." + encodedSignature; curlCommand = curlCommand.replaceAll("#USER_ASSERTION", userAssertion); // added by ericnie //System.out.println(userAssertion); HttpsURLConnection urlCon = null; String httpsUrl="https://a508150.identity.europe.oraclecloud.com/oauth2/tokens"; String xmlStr = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer&assertion="+userAssertion; SslUtils.ignoreSsl(); HttpsURLConnection httpUrlConn = null; try { httpUrlConn = (HttpsURLConnection) (new URL(httpsUrl)).openConnection(); httpUrlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); httpUrlConn.addRequestProperty("X-USER-IDENTITY-DOMAIN-NAME", "a508150"); //httpUrlConn.addRequestProperty("Authorization", "Basic ZjM5ZTdlYjEtNWFjNC00ZDhhLTgwYmEtOGUzZDA5NmY3ZjYyOnN0dktNUXNhelBKZXhWRXhNVXcy"); httpUrlConn.addRequestProperty("Authorization", "Basic "+authenticationString); httpUrlConn.setDoInput(true); httpUrlConn.setDoOutput(true); httpUrlConn.setConnectTimeout(10000); httpUrlConn.setReadTimeout(10000); httpUrlConn.setRequestMethod("POST"); httpUrlConn.setRequestProperty("Content-Length", String.valueOf(xmlStr.getBytes().length)); httpUrlConn.setUseCaches(false); httpUrlConn.connect(); httpUrlConn.getOutputStream().write(xmlStr.getBytes()); httpUrlConn.getOutputStream().flush(); httpUrlConn.getOutputStream().close(); BufferedReader in = new BufferedReader(new InputStreamReader( httpUrlConn.getInputStream())); String line; String serverreturn=""; while ((line = in.readLine()) != null) { serverreturn = serverreturn + line; // System.out.println(line); } int index = serverreturn.indexOf("access_token"); String returnassert = serverreturn.substring(index+15, serverreturn.length()-2); return returnassert; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); } return "error"; } }
时间: 2024-10-14 18:54:09