PCS 配置Oauth记录

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

PCS 配置Oauth记录的相关文章

【转】android 最新 NDK r8 在window下开发环境搭建 安装配置与使用 详细图文讲解,完整实际配置过程记录(原创)

原文网址:http://www.cnblogs.com/zdz8207/archive/2012/11/27/android-ndk-install.html android 最新 NDK r8 在window下开发环境搭建 安装配置与使用 详细图文讲解,完整实际配置过程记录(原创) 一直想搞NDK开发却一直给其他事情耽搁了,参考了些网上的资料今天终于把环境搭建起来了,把过程记录下来分享给大家. 内容目录: 1.默认基础环境 2.NDK下载与配置 3.安装Cygwin 4.用NDK编译 5.安装

VS2010/2012配置优化记录笔记

VS2010/2012配置优化记录笔记 在某些情况下VS2010/2012运行真的实在是太卡了,有什么办法可以提高速度吗?下面介绍几个优化策略,感兴趣的朋友可以参考下,希望可以帮助到你 ? 有的时候VS2010/2012运行真的实在是太卡了,奇卡无比,下面几个技巧可以稍微让你觉得它没那么卡~下面以VS2010来讲 ? VS2010选项视觉体验设置 工具->选项->环境 视觉体验的勾选都去掉.不解释,你懂得.(不过还是建议打开硬件加速) ? 禁用Intellisense 工具->选项-&g

Nginx+Php中限制站点目录防止跨站的配置方案记录

Nginx+Php中限制站点目录防止跨站的配置方案记录(使用open_basedir)-------------------方法1)在Nginx配置文件中加入: 1 fastcgi_param  PHP_VALUE  "open_basedir=$document_root:/tmp/:/proc/"; 通常nginx的站点配置文件里用了include fastcgi.conf;,这样的,把这行加在fastcgi.conf里就OK了.如果某个站点需要单独设置额外的目录,把上面的代码写在

RFC4862 IPV6无状态地址自动配置 阅读记录

RFC4862 IPV6无状态地址自动配置 阅读记录 最近接触IPV6.首次接触RFC文档.之前总是以为,rfc标准都是已经实现好的,不需要自己实现,直接用就好了.现在才知道,rfc只是说明了实现的流程.具体实现还是要自己实现的.颠覆了自己的认知.下面就学习RFC 4862 关于ipv6无状态地址自动配置的学习记录如下. 第一章 引言在IPV6中,主机在决定如何自动配置它的接口时采取步骤如下.自动配置处理包括利用无状态自动配置生成链路本地地址(linklocal地址),生成全球地址,以及启动验证

filebeat配置日志记录(等级)

配置日志 配置文件filebeat.yml中的logging部分包含用于配置日志记录输出的选项.日志记录系统可用将日志写入syslog,如果未明确配置日志记录,则使用文件输出. logging.level: info logging.to_files: true logging.files: path: /var/log/filebeat name: filebeat keepfiles: 7 permissions: 0644 tip:除了在配置文件汇总设置日志记录选项外,还可以从命令行修改日

corosync+pacemaker+nfs+pcs配置web服务的高可用

测试环境: OS:rhel6.4 web1: 192.168.1.121  httpd heartbeat pacemaker  crmsh pcs web2: 192.168.1.122  httpd heartbeat pacemaker web3: 192.168.1.125  httpd nfs VIP:192.168.1.160 PS:注意这里的测试环境是干净的,啥也没安装...go on !! 一.安装corosync和pacemaker之前的准备工作 1.节点名称(各个节点通过节点

为VMware esxi主机配置系统日志记录

我们来配置下vmware esxi主机配置系统日志的方法 在vsphere client中,选择主机192.168.166.144,选择"配置->存储器" 选项,右键该服务器的本地存储名称,在弹出的对话框中选择"浏览本地存储"如图: 2.新建一个目录用于存储系统日志如图所示: 3.记录下新建文件夹路径,注意存储名称和文件夹名称是区分大小写的,如图所示: 4.在"配置-->软件" 选项组选择"高级设置"选项如图: 5

Spring配置错误记录

更多Spring问题由于发生时未记录而遗忘了~~~~~~~ 现在动动手 解决方案由于不是源头分析因而仅供参考!!! 严重: Exception sending context destroyed event to listener instance of class org.springframework.web.context.ContextLoaderListener java.lang.IllegalStateException: BeanFactory not initialized o

IIS/IIS Express/Asp.net配置片段记录

事情的起因是,我们在项目中使用了URLRewriter.dll作为实现伪静态的工具,在VS2010及之前的开发环境中,该功能运行正常,但在VS Express 2012 for Web中就不起作用了,追究原因,找到是IIS Express配置的问题,因为IIS Express与IIS的配置很相似,并且在这个过程中对以前Asp.net配置中的未有甚解的配置项重新看过了一遍,所以记录下来,以免以后遇到这样的问题还要再将原始文档翻看一遍. 这个追究原因的过程是: IIS和IIS Express的配置