...
...
...
appanvil-karma- |
---|
...
designer |
---|
...
location | top |
---|
The non-interactive login method for the Betfair API requires that you create and upload a self-signed certificate which will be used, alongside your username and password to authenticate your credentials and generate a session token.
For the purposes of this guide, we have used openssl to generate this client, details of which can be found at http://www.openssl.org/
Tip | ||
---|---|---|
| ||
Using 2 Step Authentication to secure your account for website logins will have no impact on your use of the non-interactive login method and vice versa. |
Getting Started
There are a couple of steps required before we can actually log in:
- Create a self-signed certificate
- Link the certificate to your Betfair account
Creating a Self Signed Certificate
API-NG requires that a 1024-bit or 2048-bit RSA certificate be used. There are various tutorials available on the Internet but be aware that the certificate needs to be for client authentication (most tutorials only cover server authentication).
Create a public/private RSA key pair using openssl
Code Block | ||
---|---|---|
| ||
openssl genrsa -out client-2048.key 2048 |
Update or Create the openssl configuration file (openssl.cnf) for OpenSSL to override some of the default settings:
Code Block |
---|
[ ssl_client ]
basicConstraints = CA:FALSE
nsCertType = client
keyUsage = digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth
|
Note |
---|
In Windows, the config file is located in the installation directory of OpenSSL In Linux distributions, the config file is located at /usr/lib/ssl/openssl.cnf or /etc/ssl/openssl.cnf |
Create a certificate signing request (CSR).
Code Block | ||
---|---|---|
| ||
openssl req -new -config openssl.cnf -key client-2048.key -out client-2048.csr
Country Name (2 letter code) [AU]:GB
State or Province Name (full name) [Some-State]:London
Locality Name (eg, city) []:London
Organization Name (eg, company) [Internet Widgits Pty Ltd]:yourcompany.com
Organizational Unit Name (eg, section) []:Security Team
Common Name (e.g. server FQDN or YOUR name) []:Test API-NG Certificate
Email Address []:my.name@mydomain.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
|
Self-sign the certificate request to create a certificate
Code Block | ||
---|---|---|
| ||
openssl x509 -req -days 365 -in client-2048.csr -signkey client-2048.key -out client-2048.crt -extfile openssl.cnf -extensions ssl_client |
Note |
---|
In Windows, using any text editor, copy the contents of the .crt file and the .key file into a new file. Save this new file as client-2048.pem. |
Linking the Certificate to Your Betfair Account
The previous steps should have created the following files:
...
File name
...
Description
...
client-2048.key
...
The private key. This file is needed in order to use the certificate and should be protected and shouldn’t be shared with anyone.
...
client-2048.csr
...
A certificate signing request. This file is no longer needed and can be deleted.
...
client-2048.crt
...
The certificate. This file is not sensitive in security terms and can be shared with anyone.
Before you login using the certificate, it must be attached to your Betfair account, as follows:
- Log in to your Betfair account through betfair.comPaste the following URL into the address bar of your browser
- Navigate to https://myaccount.betfair.com/accountdetails/mysecurity?showAPI=1 - Note: Please use https://myaccount.betfair.it/accountdetails/mysecurity?showAPI=1 for the Italian Exchange or the endpoint relevant to your own jusristiction. See the URL Definition section for more details
- Scroll to the section titled “Automated Betting Program Access” and click 'Edit'
- Click on “Browse” and then locate and select the file client-2048.crt created above.
- Click on the “Upload Certificate” button.
Scroll down to the “Automated Betting Program Access” section if required and the certificate details should be shown. You should now be able to log in to your Betfair account using the API-NG endpoint.
Note on File Formats
Some systems require that client certificates are in a different format to the ones we’ve created. The two most common formats are (a) PEM format key and certificate in a single file and (b) PKCS#12 format file. .NET applications require a PKCS#12 format file.
To create a PEM format file that contains both the private key and the certificate you can use the following command:
Code Block | ||||
---|---|---|---|---|
| ||||
cat client-2048.crt client-2048.key > client-2048.pem |
Create the PKCS#12 format using crt and key
Code Block | ||
---|---|---|
| ||
openssl pkcs12 -export -in client-2048.crt -inkey client-2048.key -out client-2048.p12 |
Note |
---|
Don't circulate the key, PEM file or PCKS#12 format files as these files are security sensitive |
Details of a Login Request
A login request can now be made as follows:
- Submit a HTTP “POST” request to: https://identitysso-cert.betfair.com/api/certlogin
- As part of the SSL connection, the certificate created previously must be supplied.
- Include a custom Header called “X-Application” with a value that identifies your application. The value is not validated and is only used to help with troubleshooting and diagnosing any problems.
- Ensure the POST’s Content-Type is “application/x-www-form-urlencoded” rather than MIME attachment encoded.
- As part of the POST body include two parameters “username” and “password” which should have the relevant username/password for your account.
...
URL Definition
Code Block | ||
---|---|---|
| ||
https://identitysso-cert.betfair.com/api/certlogin |
This endpoint is also available under the following jurisdictions
Please use the below if your country of residence is in one of the list jurisdictions.
...
Jurisdiction
...
Endpoint
...
https:
//
identitysso-cert.betfair.it
...
https:
identitysso-cert.betfair.se//
Info |
---|
Please note: Danish residents cannot use the Non-Interactive (bot) login method due to the NEMID requirement which is only supported by the Interactive Login - Desktop Application method |
Request headers
- X-Application - You must set the X-Application header to your application key.
Request Parameters
...
Note |
---|
Please note: The username and password values should be encoded when making the login request. All method names are case sensitive, this includes login, keepAlive and logout. |
Response
The response returned is a json string. If the response is successful then the loginStatus key will contain SUCCESS, for example:
Code Block | ||
---|---|---|
| ||
{
sessionToken: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;
loginStatus: SUCCESS;
} |
Should a failure or exception be returned, the response will be structured as below and loginStatus will contain a failure reason:
Code Block | ||
---|---|---|
| ||
{
loginStatus: INVALID_USERNAME_OR_PASSWORD;
} |
The possible failure and exceptional return codes are:
...
There is more than one account with the same credential
...
Sample curl command to quickly check the certificate-based login
...
|
Table of Content Zone | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Getting StartedThe non-interactive login method for the Betfair Exchange API requires that you create and upload a self-signed certificate which will be used, alongside your username and password to authenticate your credentials and generate a session token. For the purposes of this guide, we have used OpenSSL to generate this client, details of which can be found at http://www.openssl.org/
There are a couple of steps required before we can actually log in:
Creating a Self Signed CertificateThe Betfair Exchange API requires that a 1024-bit or 2048-bit RSA certificate be used. We are using OpenSSL in the below example but there are other ways of doing this, including using a UI-based interface such as XCA as covered in the Certificate Generation With XCA tutorial. Create a public/private RSA key pair using openssl
Update or Create the openssl configuration file (openssl.cnf) for OpenSSL to override some of the default settings:
Create a certificate signing request (CSR).
Self-sign the certificate request to create a certificate
Linking the Certificate to Your Betfair AccountThe previous steps should have created the following files:
Before you login using the certificate, it must be attached to your Betfair account, as follows:
Scroll down to the “Automated Betting Program Access” section if required and the certificate details should be shown. You should now be able to log in to your Betfair account using the Betfair API endpoint. Note on File FormatsSome systems require that client certificates are in a different format to the ones we’ve created. The two most common formats are (a) PEM format key and certificate in a single file and (b) PKCS#12 format file. .NET applications require a PKCS#12 format file. To create a PEM format file that contains both the private key and the certificate you can use the following command: Linux
Create the PKCS#12 format using crt and key
Details of a Login RequestA login request can now be made as follows:
Certificate Login Interface Details
URL DefinitionCertificate Endpoint
This endpoint is also available under the following jurisdictions Please use the below if your country of residence is in one of the list jurisdictions.
Request headers
Request Parameters
ResponseThe response returned is a json string. If the response is successful then the loginStatus key will contain SUCCESS, for example:
Should a failure or exception be returned, the response will be structured as below and loginStatus will contain a failure reason:
The possible failure and exceptional return codes are:
Sample curl command to test the non-interactive loginUsing the below curl command, you should insert your own Betfair username and password. Please note: You must also specify the full file path that contains your client certificate and key.
Powershell Request
Postman Example - Non-Interactive Login ExampleYou need to
Postman request to test the Non-Interactive loginTo test the non-interactive login using Postman, you must first download Postman via https://www.postman.com/ The following instructions show you add to add the certificate and key file before making the login request: 1.Add certificate: Settings -> Certificates tab -> insert Host, upload .crt and .key file and clickclick the Add button .2. Insert the non-interactive endpoint URL (e.g. https://identitysso-cert.betfair.com/api/certlogin) and the request headers (X-Application, Content_Type) 3. Insert the request body (Your username and password)as shown below: 4. Perform the call by clicking Send button. Sample Code for Non-Interactive Login
Sample C# code using PKCS#12 key storePlease see code sample via https://github.com/betfair/API-NG-sample-code/tree/master/loginCode/Non-interactive-cSharp Sample Java code using Apache http client library and PKCS#12 key store Code Block | | java | title |
Code Block | ||
---|---|---|
| ||
package com.test.aping.client; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.StrictHostnameVerifier; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.security.KeyStore; import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; public class HttpClientSSO { private static int port = 443; public static void main(String[] args) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); try { SSLContext ctx = SSLContext.getInstance("TLS"); KeyManager[] keyManagers = getKeyManagers("pkcs12", new FileInputStream(new File("C:\\sslcerts\\client-2048.p12")), "password"); ctx.init(keyManagers, null, new SecureRandom()); SSLSocketFactory factory = new SSLSocketFactory(ctx, new StrictHostnameVerifier()); ClientConnectionManager manager = httpClient.getConnectionManager(); manager.getSchemeRegistry().register(new Scheme("https", port, factory)); HttpPost httpPost = new HttpPost("https://identitysso-cert.betfair.com/api/certlogin"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", "testuser")); nvps.add(new BasicNameValuePair("password", "testpassword")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); httpPost.setHeader("X-Application","appkey"); System.out.println("executing request" + httpPost.getRequestLine()); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { String responseString = EntityUtils.toString(entity); //extract the session token from responsestring System.out.println("responseString" + responseString); } } finally { httpClient.getConnectionManager().shutdown(); } } private static KeyManager[] getKeyManagers(String keyStoreType, InputStream keyStoreFile, String keyStorePassword) throws Exception { KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(keyStoreFile, keyStorePassword.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, keyStorePassword.toCharArray()); return kmf.getKeyManagers(); } } |
Sample Python code
Code Block | ||
---|---|---|
| ||
#!/usr/bin/env python import requests #openssl x509 -x509toreq -in certificate.crt -out CSR.csr -signkey privateKey.key payload = 'username=myusername&password=password' headers = {'X-Application': 'SomeKey', 'Content-Type': 'application/x-www-form-urlencoded'} resp = requests.post('https://identitysso-cert.betfair.com/api/certlogin', data=payload, cert=('client-2048.crt', 'client-2048.key'), headers=headers) if resp.status_code == 200: resp_json = resp.json() print resp_json['loginStatus'] print resp_json['sessionToken'] else: print "Request failed." |
...