Fetching data from nba.com/stats/transactions/ - nba-api

Is there a method in the nba-api package which allows querying the endpoint for data regarding transactions between teams (https://www.nba.com/stats/transactions/)?

I didn't look, but no need for that package. Just get that data directly:
import pandas as pd
import requests
url = 'https://www.nba.com/stats/js/data/playermovement/NBA_Player_Movement.json'
jsonData = requests.get(url).json()
df = pd.DataFrame(jsonData['NBA_Player_Movement']['rows'])
Output:
print(df)
Transaction_Type TRANSACTION_DATE ... Additional_Sort GroupSort
0 Signing 2021-04-21T00:00:00 ... 0.0 Signing 1039411
1 Signing 2021-04-21T00:00:00 ... 0.0 Signing 1039412
2 Signing 2021-04-21T00:00:00 ... 0.0 Signing 1039413
3 Signing 2021-04-21T00:00:00 ... 0.0 Signing 1039414
4 Signing 2021-04-20T00:00:00 ... 0.0 Signing 1039383
... ... ... ... ...
4581 Signing 2015-07-02T00:00:00 ... 0.0 Signing 944820
4582 Signing 2015-07-02T00:00:00 ... 0.0 Signing 944876
4583 Signing 2015-07-02T00:00:00 ... 0.0 Signing 944877
4584 Signing 2015-07-02T00:00:00 ... 0.0 Signing 944878
4585 Signing 2015-07-01T00:00:00 ... 0.0 Signing 944801
[4586 rows x 9 columns]

Related

How to generate a RS256 JWT Token in Karate API testing

How can I generate a sha256-RSA-signed JWT token in a Karate (https://github.com/karatelabs/karate) feature file?
https://github.com/karatelabs/karate/issues/1138#issuecomment-629453412 has a nice recipee for doing such for a HMAC-SHA256 (or "HmacSHA256" in Java lingo) token, i.e. using symmetric/shared secret crypto.
But we need asymmetric crypto and the RS256 algo (see RS256 vs HS256: What's the difference? for background)...
OK, think I figured it out :-).
Big thanks to the generous souls providing all the necessary info here:
JWT generation in Karate, but with HmacSHA256: https://github.com/karatelabs/karate/issues/1138#issuecomment-629453412
Signing with sha256 RSA signature in Java: https://www.quickprogrammingtips.com/java/how-to-create-sha256-rsa-signature-using-java.html
So the following is an example Karate feature file using
an RS256 JWT token (put in the x-jwt header)
mTLS (i.e. using a client certificate for mutual TLS)
To do this one needs to make use of Karate's JavaScript and Java-interop capabilities.
This is our setup to make it work:
0 $ tree
.
├── karate-config.js
├── karate.jar
├── secrets
│   ├── client-cert-keystore.p12
│   ├── client-cert.pem
│   ├── client-cert_private-key.pem
│   ├── rsa-4096-cert.pem
│   ├── rsa-4096-private.pem
│   └── rsa-4096-public.pem
└── test.feature
1 directory, 9 files
We'll use the private key rsa-4096-private.pem (keep it secret!) of our rsa-4096-* files to create the signed token.
So the essential files for the JWT parts are
rsa-4096-private.pem for creating the JWT
rsa-4096-public.pem for verifying the token/signature, that's what the api/service/server would do with your JWT token (i.e. this file's not needed/used in our feature file). You can try verifying a resulting token with e.g. https://jwt.io/.
Sidenote: public/private key pairs can be generated with e.g. openssl.
As a bonus this example contains using a client certificate and mTLS (which httpbin probably gracefully ignores). If you don't need this you can simply strip the configure ssl... line and the client_cert_keystore_pass stuff from the karate config file and the command line.
Karate feature file:
# test.feature
Feature: Simple test
Background:
# Several helper functions for creating a RS256 signed JWT token.
# Graciously adapted from:
# JWT generation in Karate, but with HmacSHA256:
# https://github.com/karatelabs/karate/issues/1138#issuecomment-629453412
# Signing with sha256 RSA signature in Java:
# https://www.quickprogrammingtips.com/java/how-to-create-sha256-rsa-signature-using-java.html
* def b64encode_bytes =
"""
function(bytes) {
// Base64-encode `bytes`.
// Returns bytes.
var encoder = Java.type('java.util.Base64')
.getUrlEncoder()
.withoutPadding()
return new java.lang.String(encoder.encode(bytes))
}
"""
# Base64-encode `str`, encodes str to UTF-8 and base64-encodes it.
# Returns bytes.
* def b64encode_str = function(str) {return b64encode_bytes(str.getBytes("UTF-8"))}
* def strip_key_header_footer_ws =
"""
function(key_text) {
// Strip -----BEGIN ... header + footer and all newline characters.
// Returns UTF-8-encoded bytes.
// Need string object for replaceAll method.
var key_text_str = new java.lang.String(key_text)
var key_str = key_text_str
.replaceAll("-----BEGIN PRIVATE KEY-----", "")
.replaceAll("-----END PRIVATE KEY-----", "")
.replaceAll("\r", "")
.replaceAll("\n", "")
return key_str.getBytes('UTF-8')
}
"""
* def sha256rsa_sign =
"""
function(bytes, privateKey) {
var decoder = Java.type('java.util.Base64')
.getDecoder()
var PKCS8EncodedKeySpec = Java.type(
'java.security.spec.PKCS8EncodedKeySpec')
var spec = new PKCS8EncodedKeySpec(decoder.decode(privateKey))
var kf = Java.type('java.security.KeyFactory').getInstance("RSA")
var signature = Java.type('java.security.Signature')
.getInstance("SHA256withRSA")
signature.initSign(kf.generatePrivate(spec))
signature.update(bytes)
var signed = signature.sign()
return signed
}
"""
* def generate_jwt_sha256rsa =
"""
function(payload) {
// Generate JWT from given `payload` object (dict).
// Returns SHA256withRSA-signed JWT token (bytes).
var header_encoded = b64encode_str(
JSON.stringify({alg: "RS256", typ: "JWT"}))
var payload_encoded = b64encode_str(JSON.stringify(payload))
var data_to_sign = header_encoded + '.' + payload_encoded
var signature = b64encode_bytes(
sha256rsa_sign(data_to_sign.getBytes("UTF-8"), privateKey)
)
var token = data_to_sign + '.' + signature
return token
}
"""
# enable X509 client certificate authentication with PKCS12 file
* configure ssl = { keyStore: 'secrets/client-cert-keystore.p12', keyStoreType: 'pkcs12', keyStorePassword: '#(client_cert_keystore_pass)' }
# get private key for JWT generation and API key
* def privateKeyContent = read('secrets/rsa-4096-private.pem')
* def privateKey = strip_key_header_footer_ws(privateKeyContent)
# generate JWT
* def jwt = generate_jwt_sha256rsa({iss: "ExampleApp", exp: "1924902000"})
# put all needed API access credential in the header
* headers { x-jwt: '#(jwt)'}
* url 'https://httpbin.org'
Scenario Outline: get anything
Given path '/anything/<anything_id>'
When method get
Then status 200
Examples:
| anything_id |
| 1 |
Karate config file:
// karate-config.js
function fn() {
//var http_proxy = java.lang.System.getenv('http_proxy');
var client_cert_keystore_pass = java.lang.System.getenv(
'CLIENT_CERT_KEYSTORE_PASS');
// setup connection
karate.configure('connectTimeout', 5000);
karate.configure('readTimeout', 5000);
//karate.configure('proxy', http_proxy);
var config = {
client_cert_keystore_pass: client_cert_keystore_pass
};
return config;
}
As noted you won't need the client_cert_keystore_pass stuff unless you want mTLS. Also, you probably won't need the timeout configurations. I've tested behind a proxy so this also contains some additional config support for http_proxy (commented, left in for educational purposes). Adapt to your tastes.
Run it:
0 $ CLIENT_CERT_KEYSTORE_PASS="$PASSWORD" java -jar karate.jar -o /tmp/karate-out test.feature
17:34:41.614 [main] INFO com.intuit.karate - Karate version: 1.2.1.RC1
17:34:42.076 [main] DEBUG com.intuit.karate.Suite - [config] karate-config.js
17:34:43.942 [main] DEBUG com.intuit.karate - key store key count for secrets/client-cert-keystore.p12: 1
17:34:44.535 [main] DEBUG com.intuit.karate - request:
1 > GET https://httpbin.org/anything/1
1 > x-jwt: eyJhbGciO...
1 > Host: httpbin.org
1 > Connection: Keep-Alive
...
---------------------------------------------------------
feature: test.feature
scenarios: 1 | passed: 1 | failed: 0 | time: 1.7300
---------------------------------------------------------
17:34:46.577 [main] INFO com.intuit.karate.Suite - <<pass>> feature 1 of 1 (0 remaining) test.feature
Karate version: 1.2.1.RC1
======================================================
elapsed: 4.74 | threads: 1 | thread time: 1.73
features: 1 | skipped: 0 | efficiency: 0.36
scenarios: 1 | passed: 1 | failed: 0
======================================================
HTML report: (paste into browser to view) | Karate version: 1.2.1.RC1
file:///tmp/karate-out/karate-reports/karate-summary.html
===================================================================
0 $
Note that I'm by no means a Karate expert nor a JavaScript or Java programmer. So this might well not be your idiomatic Karate/JS/Java code. ;-)

Client Authentication with Azure KeyVault Secret: PFX -> CERT

PFX is uploaded to AzureKeyVault and it is fetched with GetSecretAsync azure call successfully.
Import the cert from pfx. now this certificate is used for client authentication.
Question:
In this case, the private key is not available in the machine then how does the client authentication work ?
for reference Code to Fetch the pfx and import to certificate:
secretBundle = await kvClientProvider.GetSecretAsync(secretUri, timeoutCancellation.Token).ConfigureAwait(false);
if (0 == string.CompareOrdinal(secretBundle.ContentType,
CertificateContentType.Pfx))
{
var exportedCertCollection = new X509Certificate2Collection();
exportedCertCollection.Import(Convert.FromBase64String(secretBundle.Value));
var cert = exportedCertCollection.Cast<X509Certificate2>().Single(sc => sc.HasPrivateKey);
return cert;
}

PayPal Sandbox new certificate giving Timeout processing request error

PayPal Sandbox upgraded to provide more secured API certificate with SHA-256, 2048 bit. This was verified using the openssl command provided in
https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1915&viewlocale=en_US
Now when I tested using the existing old (SHA-1, 1024 bit) API certificate on sandbox, it worked properly.
But when a new API certificate (SHA-256, 2048 bit) was created and used for testing on sandbox then it started giving error response from sandbox,
ACK=Failure
L_ERRORCODE0=10001
L_SHORTMESSAGE0=Internal Error
L_LONGMESSAGE0=Timeout processing request
Please anyone can point out what might be the cause of this error?
For reference PayPal request (modified) sent to sandbox endpoint,
METHOD = SetExpressCheckout
RETURNURL = https://local/ReturnPage
CANCELURL = https://local/ProcessCancel
ALLOWNOTE = 0
LOGOIMG = https://local/img/logo.png
ADDROVERRIDE = 1
EMAIL = xxx#xxx.com
SOLUTIONTYPE = Mark
BUTTONSOURCE = BtnSrc
BRANDNAME = My Brand
PAYMENTREQUEST_0_SHIPTONAME = Mr Joshi
PAYMENTREQUEST_0_SHIPTOSTREET = 300 Oxford Street
PAYMENTREQUEST_0_SHIPTOCITY = London
PAYMENTREQUEST_0_SHIPTOZIP = TE45 6ST
PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE = GB
PAYMENTREQUEST_0_SHIPTOPHONENUM = 09824112345
NOSHIPPING = 1
PAYMENTREQUEST_0_PAYMENTACTION = Sale
PAYMENTREQUEST_0_CURRENCYCODE = GBP
L_PAYMENTREQUEST_0_NAME0 = 101-Jeans
L_PAYMENTREQUEST_0_DESC0 = Jeans
L_PAYMENTREQUEST_0_AMT0 = 59.0
L_PAYMENTREQUEST_0_QTY0 = 1
L_PAYMENTREQUEST_0_NAME1 = Other payments
L_PAYMENTREQUEST_0_DESC1 = Other payments
L_PAYMENTREQUEST_0_AMT1 = -8.02
L_PAYMENTREQUEST_0_QTY1 = 1
PAYMENTREQUEST_0_ITEMAMT = 50.98
PAYMENTREQUEST_0_AMT = 53.97
PAYMENTREQUEST_0_SHIPPINGAMT = 2.99
MAXAMT = 53.97
VERSION = 112.0
I have double verified the API username and API passowrd. As well as the API certificate. Even re-created the API certificate from cert_key_pem.txt obtained by downloading it from sandbox account.

phpseclib user cert for tls authetication

Update: I have rewritten the sample code and the CSR is very close to the actual openssl created CSR (only missing the CA:False extended attribute)
I have a CA already and would like to dynamically generate user certs for enrolling authorized devices with phpseclib.
I know the logic is a little cloudy, this code was pieced together from a variety of different examples:
<?php
$USERNAME = "tester";
$DEVICENAME = "command";
$PASSWORD = "test";
$ID = 123;
require_once("config.inc.php"); // Sets defined paths to CA cert and key
require_once("File/X509.php");
require_once("Crypt/RSA.php");
// Setup our CA
$CA = array(); // Store our certificate authority information
$CA["key" ] = new Crypt_RSA();
$CA["key" ]->loadKey( file_get_contents(CAKEY) ); // Load our CA key to sign with
$CA["asciicert" ] = file_get_contents(CACERT);
$CA["cert" ] = new File_X509();
$CA["cert" ]->loadX509( $CA["asciicert"] ); // Load our CA cert and public key
$CA["cert" ]->setPrivateKey($CA["key"]);
// Create a new keypair
$DEVICE = array();
$DEVICE["keys" ] = new Crypt_RSA();
$DEVICE["keypair" ] = $DEVICE["keys"]->createKey(2048);
// Save our private key
$DEVICE["privkey" ] = new Crypt_RSA();
$DEVICE["privkey" ]->loadKey($DEVICE["keypair"]["privatekey"]);
// Save our public key
$DEVICE["pubkey" ] = new Crypt_RSA();
$DEVICE["pubkey" ]->loadKey($DEVICE["keypair"]["publickey"]);
// Create a new CSR
$DEVICE["csr" ] = new File_X509();
$DEVICE["csr" ]->setPrivateKey($DEVICE["privkey"]);
$DEVICE["csr" ]->setPublicKey ($DEVICE["pubkey" ]);
$DEVICE["csr" ]->setDN("C=SS, ST=obscure, L=obscure, O=secure, OU=networksecurity, CN={$USERNAME}#{$DEVICENAME}/emailAddress={$USERNAME}#{$DEVICENAME}");
// Sign the CSR
$DEVICE["signedcsr" ] = $DEVICE["csr"]->signCSR("sha256WithRSAEncryption");
$DEVICE["asciicsr" ] = $DEVICE["csr"]->saveCSR($DEVICE["signedcsr"]);
// Update the CSR with attributes
$DEVICE["cert" ] = new File_X509();
$DEVICE["cert" ]->loadX509( $DEVICE["asciicsr"] ); // Now load it back up so we can set extended attributes
$DEVICE["cert" ]->setPublicKey ($DEVICE["pubkey" ]);
$DEVICE["cert" ]->setStartDate("-1 day"); // Make it valid from yesterday...
$DEVICE["cert" ]->setEndDate("+ 5 years"); // Set a 5 year expiration on all device certs
$DEVICE["cert" ]->setSerialNumber($ID, 10); // Use our ID number in the DB, base 10 (decimal) notation
// These wont work, ill fix this later...
$DEVICE["cert" ]->setExtension("id-ce-basicConstraints", array("cA" => false ), 1 );
$DEVICE["cert" ]->setExtension("id-ce-keyUsage" , array("keyEncipherment" ,"nonRepudiation" ,"digitalSignature" ), 1 );
$DEVICE["cert" ]->setExtension("id-ce-extKeyUsage" , array("id-kp-emailProtection" ,"id-kp-clientAuth" ), 1 );
$DEVICE["cert" ]->setExtension("netscape-cert-type" , array("Email" ,"SSLClient" ), 1 );
// Finally have the CA sign the updated CSR
$DEVICE["signedcert"] = $DEVICE["cert"]->sign($CA["cert"], $DEVICE["cert"], "sha256WithRSAEncryption"); // Sign the new certificate with our CA
$DEVICE["asciicert" ] = $DEVICE["cert"]->saveX509($DEVICE["signedcert"]); // Ascii our certificate for presentation
print <<<END
User Public key:\n{$DEVICE["keypair"]["publickey"]}\n
User Private key:\n{$DEVICE["keypair"]["privatekey"]}\n
User CSR:\n{$DEVICE["asciicsr"]}\n
CA Cert:\n{$CA["asciicert"]}\n
User Certificate:\n{$DEVICE["asciicert"]}\n
END;
?>
Below is some sample output from this program:
...
User CSR:
-----BEGIN CERTIFICATE REQUEST-----
MIIC1DCCAb4CAQAwgZQxCzAJBgNVBAYMAlNTMRAwDgYDVQQIDAdvYnNjdXJlMRAw
DgYDVQQHDAdvYnNjdXJlMQ8wDQYDVQQKDAZzZWN1cmUxGDAWBgNVBAsMD25ldHdv
cmtzZWN1cml0eTEXMBUGA1UEAwwOdGVzdGVyQGNvbW1hbmQxHTAbBgkqhkiG9w0B
CQEMDnRlc3RlckBjb21tYW5kMIIBIDALBgkqhkiG9w0BAQEDggEPADCCAQoCggEB
ANzsEUPULfmkbDK2DLTWUbHxpqbxiQ0WF5vuUOXutcdJADG9uExyllRtnPmUq3yV
GhfF/jbKKwXrDMTc9JLRoPRjbCesHQq9p+WU2pgzHWOGne3b2SNB6ISSVUbmZwRd
3Uu78u2EIPw2yB/YAdMaSipuLnA4jbGwWHtMXWSr9g0en+CkJ0cHN3P0GAnDR7BF
2pq88si5Who9Dvn/Mo3npMZiAmD5D7qwD88mVFMC1j4q1xnqHi2X19Xz9+xgWZ1h
IdedpWh+v0i2kHE73Csu0Jiczxb28zdm+MjBEYGZ6X6LzCYHI5kx2wDKsxuxraMf
sY0QS/kATiTzSJMcWzxR82UCAwEAATALBgkqhkiG9w0BAQsDggEBABuThxlknbCS
Fzd8B+eM98uFW6YQmfp5js/S2+Cor3+btGi2d/siXDGusW7ceOEv4WLRikrv+0tt
rHNzndhl77ukSikA0H0VMUqNFYIL1N//W2nDhphYKWwKWHGoQ+/ZH30aLgw43iNz
IzWAj2d39bGEqAvGPzU6BDpm8o1ucMoJaqUAHNov69Ro/n+rb0k3ouuTqjewF781
lQFHMPhUY4j2JbGKpah3qPGvAgc44JR6VmG6Rh9nVhcZz5szit8K1UTgvIlSl7EH
7ggBHQl67kON19JKlKneJVsD36tczkEhuDGU5Dv4TH7SLiKwIRYHulD3bmqg2/Nq
sGAxVviaKBA=
-----END CERTIFICATE REQUEST-----
CA Cert:
-----BEGIN CERTIFICATE-----
MIIDVTCCAj2gAwIBAgICEA8wDQYJKoZIhvcNAQELBQAwSTELMAkGA1UEBhMCU1Mx
EjAQBgNVBAgMCVNlY3VyZSBDQTESMBAGA1UEBwwJU2VjdXJlIENBMRIwEAYDVQQK
DAlTZWN1cmUgQ0EwHhcNMTUwMjAxMTkzNjA2WhcNMTYwMjAxMTkzNjA2WjBPMQsw
CQYDVQQGEwJTUzEPMA0GA1UECAwGU2VjdXJlMQ8wDQYDVQQKDAZTZWN1cmUxHjAc
BgNVBAMMFW5ldHdvcmtzZWN1cml0eS5uaW5qYTCCASIwDQYJKoZIhvcNAQEBBQAD
ggEPADCCAQoCggEBAN7PJWsyd3Hn7q5/Y4N9Dcpvtip/hiSEFwrkl4UWd+bD7CGz
wQjyZziVAj7mXjgTrPCmMzwV/aRtT2WM7l1vI8WV0swsTEidvZF+EDEAujnadMxr
8JWVC+ljYvhy7nIDRYpPwkKSBWpIF1UFaG8MduHxBtqlRlOJoIDQmJkLQO5fV/kv
cujct4myMhar6TPx52xWX0FLt0B3Rn04Rb0InstyDY0NtrTMsgSq32rj3sijTCAG
WDsnxNO+jsC7uFAjjldcWnqBs7of+sVb7TPiEsq/5adE6G50ctqW8H7JpY+SFZzG
Y+wPRUxJZsYq4qt/rkEv7ldtsbhHD6wO4I61eksCAwEAAaNBMD8wDAYDVR0TBAUw
AwEB/zALBgNVHQ8EBAMCBeAwIgYDVR0RBBswGYIXKi5uZXR3b3Jrc2VjdXJpdHku
bmluamEwDQYJKoZIhvcNAQELBQADggEBAMsXyUX95AkQKadbaZ1XEWoayElWtKUc
dRB15XDJ7xoWGQo/fDYebXOJMPffIQoOGtRZcYtPaVjr3PMUCaxIAUvdmO3UMfLh
M8kQhYBzyEKw+SRwcUHmKbU8Tz5AolL1qjoNm5SWBV9RbFj2TRcR27v/apmhIR+K
6KKbcIXklKhhBPacJL7NwAgibb8Ip4OtxSuzarydddPryAwTwUSJNlmozRAx7dFk
xLkLMQMqEtW7BmJqU+YUczddYvbsxmYqfaChM/TBo7VZd84RlWoXOqqfon6JGLWN
5lN86iVnfXeGLbhLt5GKWB6e4rUbiMAqmGYO6Cd2BMFRtlp9IYZIBSY=
-----END CERTIFICATE-----
User Certificate:
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
I find it really confusing that the signed certificate is blank. The error checking in place seems to make me think it would simply return FALSE if there was a problem, but getting blank output between the ----- lines makes me wonder what is going on.
From your code:
$DEVICE["cert" ]->loadX509( $DEVICE["asciicsr"] );
Try this:
$DEVICE["cert" ]->loadCSR( $DEVICE["asciicsr"] );

grails - RestClientBuilder

I am using the current version of rest client builder plugin. I tested out the uri via curl:
curl --user username:password https://localhost:8085/rest/api/latest/plan.json?os_authType=basic
I get the expected json in return. When I try to translate this to grails using the plugin like this:
RestBuilder rb = new RestBuilder()
def response = rb.get("https://localhost:8085/rest/api/latest/plan.json?os_authType=basic"){
auth 'username', 'password'
}
response.json instanceof JSONObject
I get this error:
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Why does it work in curl and not with the plugin? How do I get this to work?
Thanks!
You need to add the root certificate to the store of the trusted ones.
http://docs.oracle.com/javase/tutorial/security/toolsign/rstep2.html
Import the Certificate as a Trusted Certificate
Before you can grant the signed code permission to read a specified file, you need to import Susan's certificate as a trusted certificate in your keystore.
Suppose that you have received from Susan
the signed JAR file sCount.jar, which contains the Count.class file, and
the file Example.cer, which contains the public key certificate for the public key corresponding to the private key used to sign the JAR file.
Even though you created these files and they haven't actually been transported anywhere, you can simulate being someone other than the creater and sender, Susan. Pretend that you are now Ray. Acting as Ray, you will create a keystore named exampleraystore and will use it to import the certificate into an entry with an alias of susan.
A keystore is created whenever you use a keytool command specifying a keystore that doesn't yet exist. Thus we can create the exampleraystore and import the certificate via a single keytool command. Do the following in your command window.
Go to the directory containing the public key certificate file Example.cer. (You should actually already be there, since this lesson assumes that you stay in a single directory throughout.)
Type the following command on one line:
keytool -import -alias susan
-file Example.cer -keystore exampleraystore
Since the keystore doesn't yet exist, it will be created, and you will be prompted for a keystore password; type whatever password you want.
The keytool command will print out the certificate information and ask you to verify it, for example, by comparing the displayed certificate fingerprints with those obtained from another (trusted) source of information. (Each fingerprint is a relatively short number that uniquely and reliably identifies the certificate.) For example, in the real world you might call up Susan and ask her what the fingerprints should be. She can get the fingerprints of the Example.cer file she created by executing the command
keytool -printcert -file Example.cer
If the fingerprints she sees are the same as the ones reported to you by keytool, the certificate has not been modified in transit. In that case you let keytool proceed with placing a trusted certificate entry in the keystore. The entry contains the public key certificate data from the file Example.cer and is assigned the alias susan.
You can just disable SSL check for RestBuilder.
See an example of code:
static Scheme disableSSLCheck() {
def sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, [new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
#Override
X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0]
}
}] as TrustManager[], new SecureRandom())
def sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
def httpsScheme = new Scheme("https", sf, 443)
httpsScheme
}
And register this Scheme to the RestClient:
Scheme httpsScheme = disableSSLCheck()
restClient.client.connectionManager.schemeRegistry.register(httpsScheme)
Mb too late but have a look here.
https://gist.github.com/thomastaylor312/80fcb016020e4115aa64320b98fb0017
I do have it as separate method in my Integration test
def static disableSSLCheck() {
def nullTrustManager = [
checkClientTrusted: { chain, authType -> },
checkServerTrusted: { chain, authType -> },
getAcceptedIssuers: { null }
]
def nullHostnameVerifier = [
verify: { hostname, session -> true }
]
SSLContext sc = SSLContext.getInstance("SSL")
sc.init(null, [nullTrustManager as X509TrustManager] as TrustManager[], null)
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())
HttpsURLConnection.setDefaultHostnameVerifier(nullHostnameVerifier as HostnameVerifier)
}
And then just
void "test authentication"(){
given:
String url = "j_spring_security_check"
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
form.add("grant_type", "password")
form.add("j_username", "vadim#ondeviceresearch.com")
form.add("j_password", "notSecure")
form.add("_spring_security_remember_me", "true")
//TODO SET username and pass
//todo get token back
disableSSLCheck()
when:
RestResponse response = rest.post(host + url){
accept("application/json")
contentType("application/x-www-form-urlencoded")
body(form)
}
response
then:
response.status == 200
}