SalesForceのSSOを開始しようとする3日間の苦労と実りのない試みの後、将来の世代が頭を壁にぶつけて貴重な時間を突破しないように、問題を解決する正しい方法をコミュニティと共有することを急いでいます。 興味があれば、猫をお願いします。
私は高音節の達人ではないので、
SSO(シングルサインオン)とは何かをwikiに伝える方
が良いです。
一般に、プロジェクトでは
SalesForceなどのサービスのSSOサポートを編成する必要がありました。
SAMLはサーバー間の通信に使用されるため、既成の実装の検索でGoogleを苦しめることにしました。 永続的な検索の後、OpenSAMLライブラリがSAMLを生成することがわかりました。これにより、別の自転車の誕生から宇宙が救われました。
まず、証明書を生成します。 JDKのキーツールを使用しましたが、OpenSSLを使用することもできます。
keytool -genkey -keyalg RSA -alias SSO -keystore keystore keytool -export -alias SSO -keystore keystore -file certificate.crt
キーが生成された後、SSOを使用したログインを許可するようにSalesForceを構成する必要があります。 最良の指示は、Wikiの
Force.comでのSAMLによるシングルサインオンです。 この記事は優れていますが、必要な項目は「Force.comをSSO用に設定する」だけです。 はい、それは小さな変更です:私の実装はNameIdentifier要素でユーザー名を渡すので、スイッチをデフォルト状態のままにします:「Assertion contains User's salesforce.com username」と「User ID is the NameIdentifier element in the Subject statement」
OpenSAMLライブラリを操作するためのいくつかの例が見つかったため、テストのニーズに適した簡単なジェネレーターがすぐに作成されました。 1日の作業でコードをなめると、有効なSAMLを生成するジェネレーターが受信されました(SalesForceバリデーターによる)。 以下は、なめられたコードです。
SalesForce以外の他のサービスのサポートを強化する予定であるため、ジェネレーターはいくつかのクラスに分けられます:共通部分(SAMLResponseGenerator)、SalesForceの実装(SalesforceSAMLResponseGenerator)、およびこの混乱をすべて実行するプログラム:
SAMLResponseGenerator.java: public abstract class SAMLResponseGenerator { private static XMLObjectBuilderFactory builderFactory = null; private String issuerId; private X509Certificate certificate; private PublicKey publicKey; private PrivateKey privateKey; protected abstract Assertion buildAssertion(); public SAMLResponseGenerator(X509Certificate certificate, PublicKey publicKey, PrivateKey privateKey, String issuerId) { this.certificate = certificate; this.publicKey = publicKey; this.privateKey = privateKey; this.issuerId = issuerId; } public String generateSAMLAssertionString() throws UnrecoverableKeyException, InvalidKeyException, NoSuchAlgorithmException, CertificateException, KeyStoreException, NoSuchProviderException, SignatureException, MarshallingException, ConfigurationException, IOException, org.opensaml.xml.signature.SignatureException, UnmarshallingException { Response response = buildDefaultResponse(issuerId); Assertion assertion = buildAssertion(); response.getAssertions().add(assertion); assertion = signObject(assertion, certificate, publicKey, privateKey); response = signObject(response, certificate, publicKey, privateKey); Element plaintextElement = marshall(response); return XMLHelper.nodeToString(plaintextElement); } @SuppressWarnings("unchecked") protected <T extends XMLObject> XMLObjectBuilder<T> getXMLObjectBuilder(QName qname) throws ConfigurationException { if (builderFactory == null) {
SalesforceSAMLResponseGenerator.java: public class SalesforceSAMLResponseGenerator extends SAMLResponseGenerator { private static final String SALESFORCE_LOGIN_URL = "https://login.salesforce.com"; private static final String SALESFORCE_AUDIENCE_URI = "https://saml.salesforce.com"; private static final Logger logger = Logger.getLogger(SalesforceSAMLResponseGenerator.class); private static final int maxSessionTimeoutInMinutes = 10; private String nameId; public SalesforceSAMLResponseGenerator(X509Certificate certificate, PublicKey publicKey, PrivateKey privateKey, String issuerId, String nameId) { super(certificate, publicKey, privateKey, issuerId); this.nameId = nameId; } @Override protected Assertion buildAssertion() { try {
TestSSO.java: public class TestSSO { private PrivateKey privateKey; private X509Certificate certificate; public void readCertificate(InputStream inputStream, String alias, String password) throws NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyStoreException { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(inputStream, password.toCharArray()); Key key = keyStore.getKey(alias, password.toCharArray()); if (key == null) { throw new RuntimeException("Got null key from keystore!"); } privateKey = (PrivateKey) key; certificate = (X509Certificate) keyStore.getCertificate(alias); if (certificate == null) { throw new RuntimeException("Got null cert from keystore!"); } } public void run() throws ConfigurationException, UnrecoverableKeyException, InvalidKeyException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, KeyStoreException, NoSuchProviderException, SignatureException, IOException, org.opensaml.xml.signature.SignatureException, URISyntaxException, UnmarshallingException, MarshallingException { String strIssuer = "Eugene Burtsev"; String strNameID = "user@test.com"; InputStream inputStream = TestSSO.class.getResourceAsStream("/keystore"); readCertificate(inputStream, "SSO", "12345678"); SAMLResponseGenerator responseGenerator = new SalesforceSAMLResponseGenerator(certificate, certificate.getPublicKey(), privateKey, strIssuer, strNameID); String samlAssertion = responseGenerator.generateSAMLAssertionString(); System.out.println(); System.out.println("Assertion String: " + samlAssertion); } public static void main(String[] args) throws ConfigurationException, UnrecoverableKeyException, InvalidKeyException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, KeyStoreException, NoSuchProviderException, SignatureException, IOException, org.opensaml.xml.signature.SignatureException, URISyntaxException, UnmarshallingException, MarshallingException { new TestSSO().run(); } }
コードが有効であるというバリデーターのすべての保証にもかかわらず、SSOを使用してSalesForceを許可することは簡単な作業ではありませんでした。 約12のサンプルがwikiでテストされ、どれも「無効なアサーション」と言ってもうまく動作しませんでした...それで3日が経過しました...そして、SAMLが必要とするものについて神聖な知識が得られ
たOASIS仕様を読みまし
た 「SAMLResponse」パラメータでPOSTリクエストを送信します...成功を望んでいないため、この知識が実践され、奇跡が起こりました-Salesforceはログイン用のトークンを含むリンクを発行しました。 以下は、SalesForceにSSOを実装するための正しいアプローチを示す完全なサンプルプログラムです。
public class TestSSO { private static final Logger logger = Logger.getLogger(TestSSO.class); public static DefaultHttpClient getThreadSafeClient() { DefaultHttpClient client = new DefaultHttpClient(); ClientConnectionManager mgr = client.getConnectionManager(); HttpParams params = client.getParams(); client = new DefaultHttpClient(new ThreadSafeClientConnManager( mgr.getSchemeRegistry()), params); return client; } private static HttpClient createHttpClient() { HttpClient httpclient = getThreadSafeClient(); httpclient.getParams().setParameter( CoreProtocolPNames.PROTOCOL_VERSION, new ProtocolVersion("HTTP", 1, 1)); return httpclient; } private static void sendSamlRequest(String samlAssertion) { HttpClient httpClient = createHttpClient(); try { System.out.println(samlAssertion); HttpPost httpPost = new HttpPost("https://login.salesforce.com/"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); entity.addPart("SAMLResponse", new StringBody(samlAssertion)); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost); Header location = httpResponse.getFirstHeader("Location"); if (null != location) { System.out.println(location.getValue()); } } catch (Exception e) { logger.error(e, e); } finally { httpClient.getConnectionManager().shutdown(); } } private PrivateKey privateKey; private X509Certificate certificate; public void readCertificate(InputStream inputStream, String alias, String password) throws NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyStoreException { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(inputStream, password.toCharArray()); Key key = keyStore.getKey(alias, password.toCharArray()); if (key == null) { throw new RuntimeException("Got null key from keystore!"); } privateKey = (PrivateKey) key; certificate = (X509Certificate) keyStore.getCertificate(alias); if (certificate == null) { throw new RuntimeException("Got null cert from keystore!"); } } public void run() throws ConfigurationException, UnrecoverableKeyException, InvalidKeyException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, KeyStoreException, NoSuchProviderException, SignatureException, IOException, org.opensaml.xml.signature.SignatureException, URISyntaxException, UnmarshallingException, MarshallingException { String strIssuer = "Eugene Burtsev"; String strNameID = "user@test.com"; InputStream inputStream = TestSSO.class.getResourceAsStream("/keystore"); readCertificate(inputStream, "SSO", "12345678"); SAMLResponseGenerator responseGenerator = new SalesforceSAMLResponseGenerator(certificate, certificate.getPublicKey(), privateKey, strIssuer, strNameID); String samlAssertion = responseGenerator.generateSAMLAssertionString(); System.out.println(); System.out.println("Assertion String: " + samlAssertion); sendSamlRequest(Base64.encodeBase64String(samlAssertion.getBytes("UTF-8"))); } public static void main(String[] args) throws ConfigurationException, UnrecoverableKeyException, InvalidKeyException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, KeyStoreException, NoSuchProviderException, SignatureException, IOException, org.opensaml.xml.signature.SignatureException, URISyntaxException, UnmarshallingException, MarshallingException { new TestSSO().run(); } }
ソースを含むアーカイブは
ここで取得でき
ますそして最後に、道徳:誰も信用せず、仕様だけが真実を伝える!
有用なリソースのリスト:
- Force.comでのSAMLを使用したシングルサインオン
- docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf
- www.sslshopper.com/article-most-common-java-keytool-keystore-commands.html