I'm looking to log in to a site through Python.
I do not know how to do it since it is through its API, I leave here the information provided by the API to log me in. It is really necessary that you do it through python. I have logged through other APIs but with this it is impossible since I do not know where to start. If I am logged in through the Browser, in the terminal I place:
curl 'https://onevideo.aol.com/sessions/session_info?oauth=fb7f6a10-df16-418e-846b-4a00c2618e'
and he returns me
// https://onevideo.aol.com/sessions/session_info?oauth=fb7f6a10-df16-418e-846b-4a00c2618e
{
"result": {
"code": "OK",
"msg": ""
},
"id": 34736,
"first_name": "juan",
"last_name": "perez",
"email": "juan@perez",
"user_name": "juanoperez",
"org_id": 11776,
"one_source": "",
"is_super": 0,
"duplicate_email_status": "",
"session_id": "fb7f6a10-df16-418e-846b-4a00c2618e"
It should be noted that this url that I enter in the terminal was obtained through inspect once logged!
Obtain an access token
In order to make API calls, an access token is required. Obtaining the token is a two step process:
Generate JsonWebToken (JWT).
Use the generated JWT to get the OAuth2 token.
Note: Both tokens above have an expiration time and will need to be regenerated periodically (or upon a rejection because of inactive token from any of the API calls).
How do I generate a JWT ?
A JWT consists of three parts, separated by dots (.), which are:
Header
Payload
Signature
A typical JWT looks like this:
<base64url-encoded header>.<base64url-encoded payload>.<base64url-encoded signature>
Header
The header typically consists of two parts: the type of the token, which is JWT, and the hashing algorithm such as HMAC SHA256 or RSA.
Example:
1
{ "alg": "HS256", "typ": "JWT”}
Base64Url encoded of this JSON forms the first part of the JWT.
Payload
The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional metadata.
Example:
1
{
2
"aud": "https://{b2b.host}/identity/oauth2/access_token?realm=aolcorporate/aolexternals",
3
"iss": "{client_id}",
4
"sub": "{client_id}",
5
"exp": {expiry time in seconds},
6
"iat": {issued time in seconds},
7
"jti": "{UUID}"
8
}
client_id = OAuth2 Client ID
UUID: Unique Id
issued time in seconds: Current time in seconds.
expiry time in seconds: Future time (ex: +10 mins) in seconds. Make sure this not too far into the future. More than 24 hours would be rejected. 10 mins in the future is a typical value.
UAT B2B host: id-uat2.corp.aol.com
Prod B2B host: id.corp.aol.com
Note: exp/iat are Date objects, not strings.
Base64Url encoded of this JSON forms the second part of the JWT.
Signature
To create the signature part, you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.
For example if you want to use the HMAC SHA256 algorithm, the signature will be created as follows:
HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload),secret)
secret = OAuth2 Client Secret
The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed in the request flow.
Putting it all together
The output is three Base64Url encoded strings separated by dots that can be easily passed in HTML and HTTP environments. A sample JWT token looks something like this (dots highlighted in red):
ew0KICAiYWxnIjogIkhTMjU2IiwNCiAgICJ0eXAiOiAiSldUIg0KfQ.ew0KICAiYXVkIjogIntwcm90b2NvbH06Ly97YjJiLmhvc3R9L2lkZW50aXR5L29hdX
RoMi9hY2Nlc3NfdG9rZW4/cmVhbG09PHlvdXItcmVhbG0+IiwNCiAgImlzcyI6ICJ7Y2xpZW50X2lkfSIsDQogICJzdWIiOiAie2NsaWVudF9pZH0iLA0KICA
iZXhwIjog4oCce2V4cGlyeSB0aW1lIGluIHNlY29uZHN94oCdLA0KICAiaWF0Ijog4oCce2lzc3VlZCB0aW1lIGluIHNlY29uZHN94oCdDQp9DQo.uKqU9dTB
6gKwG6jQCuXYAiMNdfNRw98Hw_IWuA5MaMo
There are many libraries for different development languages and environments that can be used to create the JWT. Below is a Java example, using jose4j:
01
public static String generateJsonWebToken(final String clientId, final String secret,
02
final String audience) throws OCAuthException {
03
04
JwtClaims claims = new JwtClaims();
05
claims.setIssuedAt(NumericDate.now());
06
claims.setExpirationTimeMinutesInTheFuture(1); -- Expiration time of the JWT
07
claims.setSubject(clientId);
08
claims.setIssuer(clientId);
09
claims.setAudience(audience);
10
claims.setGeneratedJwtId();
11
12
try {
13
Key key = new HmacKey(secret.getBytes("UTF-8"));
14
15
JsonWebSignature jws = new JsonWebSignature();
16
jws.setPayload(claims.toJson());
17
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
18
jws.setKey(key);
19
jws.setDoKeyValidation(false);
20
21
return jws.getCompactSerialization();
22
23
} catch (Exception e) {
24
throw new OCAuthException("JWT Generation failed", e);
25
}
26
}
For JWT generation in other programming languages, see the Generating the JWT Using Different Languages.
Generating an OAuth2 Token
Once a valid JWT is obtained, an OAuth2 token can be generated by issuing the following request:
Endpoint
POST https://<b2b.host>/identity/oauth2/access_token
Request body
Request body should include the arguments listed below and should be application/x-www-form-urlencoded:
Field Name Required/Optional Value
grant_type Required MUST be 'client_credentials'
client_assertion_type Required MUST be 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'
client_assertion Required JWT Token value (varies for each client request)
scope Required one
realm Required aolcorporate/aolexternals
Sample request
POST /identity/oauth2/access_token HTTP/1.1
Host: https://id.corp.aol.com
Content-Type: application/x-www-form-urlencoded
Accept: application/json
grant_type=client_credentials&scope=one&realm=aolcorporate/aolexternals&client_assertion_type=urn:ietf:params:oauth:
client-assertion-type:jwt-bearer&client_assertion=<JWT Token>
Sample response
Format: json Status: 200 Headers: Content-Type: application/json
{
"access_token": "3f94eb47-a295-4977-a375-e27bea5c828b",
"scope": "one",
"token_type": "Bearer",
"expires_in": 599
}
Using the OAuth2 token
Use the generated OAuth2 token in the Authorization HTTP header (Bearer <OAuth2 Token>) while communicating with AOL API’s.
For example: “Authorization: Bearer 3f94eb47-a295-4977-a375-e27bea5c828b”
Returning the OAuth2 token
Finally, you'll need to send the token back when you make the API call. Here is an example of how you do it in PHP:
<?php
$token = '';
$orgId = '';
if ($token & $orgId) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
// This is the same API call as before I've left this here as a place holder.
CURLOPT_URL => 'https://onevideo.aol.com/reporting/run_report?org_id='.$orgId.'&keys=date&metrics=ad_impressions&start_date=1486972800&end_date=1487059200¤cy_id=150&timezone=228&report_type=0&is_date_international_format=0',
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Authorization: Bearer '.$token
) ));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
echo $resp;
}else{
echo 'Need To Send Token';
}
?>
Refreshing the OAuth2 token
The OAuth2 token expires after a specified number of seconds (expires_in attribute of the access token response) from the time the response was generated. The API consumer needs to refresh the token after the expiration time is elapsed or upon rejection because of an inactive hostoken from any API call.
Security considerations
If using a shared secret (HS256) to sign the JWT, it is critical that:
The secret is protected and NEVER exposed to the browser.
All interactions MUST be protected by TLS.
If the credentials are compromised at any point, it is very important to notify AOL immediately so that the compromised credentials are revoked and new credentials are issued.
It is crucial to share the client credentials securely with the external parties. Options include using PGP to encrypt the credentials or using encrypted mails.