OAuth signature generation using HMAC-SHA1? - oauth

I apologize for asking so many questions but none of them seem to be getting answered and I really need help on this. I'm using LTI to integrate my program into a learning management system, and I need to authenticate using OAuth. I have no trouble generating a signature following the guidelines here but the signature I generate never matches the one passed to me by the LMS, and I can't figure out for the life of me why they never match. I'm hoping that it's something I'm oblivious to, but I really need some assistance on this.
When I launch my program from the LMS, I am sent this array via POST in what is called the LTI launch:
array(
'launch_presentation_locale' => 'EN-US__',
'tool_consumer_instance_guid' => 'key',
'tool_consumer_instance_name' => 'MyProgram',
'tool_consumer_instance_description' => 'MyProgram',
'tool_consumer_instance_contact_email' => 'johndoe#email.com',
'tool_consumer_info_version' => '10.3.0 SP5',
'tool_consumer_info_product_family_code' => 'desire2learn',
'context_id' => '2440554',
'context_title' => 'ContextTitle',
'context_label' => 'ContextTitle',
'context_type' => '',
'user_id' => 'USER_ID',
'roles' => 'None',
'lis_person_name_given' => 'John',
'lis_person_name_family' => 'Doe',
'lis_person_name_full' => 'John Doe',
'lis_person_contact_email_primary' => 'johndoe#email.com',
'ext_tc_profile_url' => 'https://profileurl.com',
'ext_d2l_token_id' => '123456789',
'ext_d2l_link_id' => '1234',
'ext_d2l_token_digest' => 'AbCdEfGhIjKlMnOpQrStUvWxYzi=',
'resource_link_id' => '',
'resource_link_title' => 'MyProgram',
'resource_link_description' => 'MyProgram',
'lis_result_sourcedid' => 'abcdefgh-ijkl-mnop-qrst-uvwxyz012345',
'lis_outcome_service_url' => 'https://outcomeserviceurl.com',
'lti_version' => 'LTI-1p0',
'lti_message_type' => 'basic-lti-launch-request',
'oauth_version' => '1.0',
'oauth_nonce' => '123456789',
'oauth_timestamp' => '1234567890',
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_consumer_key' => 'key',
'oauth_callback' => 'about:blank',
'oauth_signature' => 'eFUR8O5xVydLrj4PDj37nF4cq6A=',
'basiclti_submit' => 'Launch Endpoint with BasicLTI Data'
);
Here is what I'm trying. I've added comments to clarify the steps:
// Set variables that are required for the signature to be generated.
$OAUTH_KEY = 'key';
$OAUTH_SECRET = 'secret';
$httpMethod = 'POST';
$SITE_URL = 'https://localhost/test.php';
// make array copy of entire POST data, remove the 'oauth_signature' field as specified in the oauth spec from the copy array, then sort alphabetically. After that, url encode the key/value of each item in the copy array and store into a string for later use.
$request_parameter_array = $_POST;
unset($request_parameter_array['oauth_signature']);
ksort($request_parameter_array);
$request_parameter_str = '';
foreach($request_parameter_array as $key => $value) {
$request_parameter_str .= rawurlencode($key) . '=' . rawurlencode($value) . '&';
}
// create the signature base string (string variable that the actual signature is created from) by following these steps from the OAuth documentation:
// 1. The HTTP request method in uppercase. For example: "HEAD",
// "GET", "POST", etc. If the request uses a custom HTTP method, it
// MUST be encoded (Section 3.6).
// 2. An "&" character (ASCII code 38).
// 3. The base string URI from Section 3.4.1.2, after being encoded
// (Section 3.6).
// 4. An "&" character (ASCII code 38).
// 5. The request parameters as normalized in Section 3.4.1.3.2, after
// being encoded (Section 3.6).
$key = rawurlencode($OAUTH_SECRET) . '&';
$signature_base = strtoupper($httpMethod) . '&' . rawurlencode($SITE_URL) . '&';
$signature_base .= rawurlencode($request_parameter_str);
$signature = base64_encode(hash_hmac("sha1", $signature_base, $key, true));
echo $signature;

I guess my own stupidity was the issue, here. The issue was arising from D2L itself because I misunderstood what the difference was between using a tool link vs. a tool provider for my integrations. I literally deleted my tool provider and went with a tool link and now I'm able to authenticate every time.
Turns out there wasn't a problem with the code at all here.

Related

Yahoo DSP API Authentication Error: Access Token

I have been following the guide to obtain an Access Token for Yahoo DSP API through:
https://developer.yahooinc.com/dsp/api/docs/authentication/vmdn-auth-overview.html
I get to the part Generate a JWT Access Token, and request an access token (with all the headers and paramenters).
When posting a request, I get an error: 'Internal Server error', which in the error codes in the documents says: Try Again Later (without further explanations). I am assuming the request went through and there is something wrong on their side.
Yahoo has no user help suppport. If anyone could please shine some light other than "Try Again Later".
Thank you
#flurry
Unfortunately, Yahoo DSP API docs isn't the most intuitive and straightforward docs there is and it requires a little effort to find and do the right thing.
Although, this collection helped me out when trying to obtain an Access Token from Yahoo DSP API (check the pre-request script):
https://www.postman.com/postman/workspace/postman-team-collections/request/4630964-df7c0fff-babc-420d-ad45-e9e731d5c50f
Not sure in which programming language are you doing the integration for Yahoo DSP API, but if you need a PHP code sample, here's what I used:
$response = $this->httpClient->request(
'POST',
'https://id.b2b.yahooinc.com/identity/oauth2/access_token',
[
'form_params' => [
'grant_type' => 'client_credentials',
'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
'client_assertion' => $this->prepareSignedJWT(),
'scope' => 'dsp-api-access',
'realm' => 'dsp'
],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded',
]
]
);
Where prepareSignedJWT being:
private function prepareSignedJWT()
{
$header = [
'typ' => 'JWT',
'alg' => 'HS256'
];
$body = [
'aud' => 'https://id.b2b.yahooinc.com/identity/oauth2/access_token?realm=dsp',
'iss' => $this->config->getClientId(),
'sub' => $this->config->getClientId(),
'iat' => time(),
'exp' => time() + 600, // 10 min from time of creation
];
$encodedHeader = base64_encode(json_encode($header));
$encodedBody = base64_encode(str_replace('\/', "/", json_encode($body)));
$token = $encodedHeader . '.' . $encodedBody;
$signature = hash_hmac('sha256', $token, $this->config->getClientSecret(), true);
$encodedSignature = base64_encode($signature);
return $token . '.' . $encodedSignature;
}
And $this->config is just an config object I use in the code.
Hope you find this answer useful, Cheers.

How to fix getFederationToken returns 403 not authorized error after upgrading from SDK version 1 to 3

We have existing code that uses AWS PHP SDK version 1 AmazonSTS()->get_federation_token(). After upgrading to SDK version 3, the same call using the same credentials, resource and policy returns a 403 not authorized error.
Version and region appear to be the same. The policy json is the same. The user credentials used to make the call are the same (and if I switch back to the SDK v1 they still work). I have the debug option set but it doesn't appear to provide any additional information as to why the same user it not authorized to perform the same function getFederationToken on the same federated user.
Old code that works:
$client = new AmazonSTS();
$policy = new stdClass();
$policy->Statement = [
'Sid' => 'randomstatementid' . time(),
'Action' => ['s3:*'],
'Effect' => 'Allow',
'Resource' => 'aws:s3:::' . $AWS_BUCKET . '*'
];
// Fetch the session credentials.
$response = $client->get_federation_token('User1',array(
'Policy' => json_encode($policy),
'DurationSeconds' => $NUMSECS
));
New code that returns 403 error:
$client = new Aws\Sts\StsClient([
'region' => 'us-east-1',
'version' => '2011-06-15',
]);
$policy = new stdClass();
$policy->Statement = [
'Sid' => 'randomstatementid' . time(),
'Action' => ['s3:*'],
'Effect' => 'Allow',
'Resource' => 'aws:s3:::' . $AWS_BUCKET . '*'
];
try {
$response = $client->getFederationToken([
'Name' => 'User1',
'Policy' => json_encode($policy),
'DurationSeconds' => $NUMSECS,
]);
} catch (Exception $e) {
var_dump($e);
die();
}
The first example returns temporary credentials for the federated user User1.
The second example returns 403 forbidden error (I'm hiding the actual account id):
<Error>
<Type>Sender</Type>
<Code>AccessDenied</Code>
<Message>User: arn:aws:iam::[account id]:user/portal is not authorized to perform: sts:GetFederationToken on resource: arn:aws:sts::[account id]:federated-user/User1</Message>
</Error>
Turns out I was looking at the wrong credentials. I found the correct credentials hard-coded in the script :(

Yii2 UrlManager + wrong generate route

I have some problem - urlrules is correct but generated url from yii\bootstrap\Nav not correctly ->:
{domain}/armory/search?server=Lorem+ipsum
but this url working too -> {domain}/armory/search/Lorem+ipsum
'search/<server>' => 'search/index'
url rule ^
protected function addUrlManagerRules($app)
{
$app->urlManager->addRules([new GroupUrlRule([
'prefix' => $this->id,
'rules' => require __DIR__ . '/url-rules.php',
])],true);
}
why this not generate url like {domain}/armory/search/Lorem+ipsum
'url' => ['/armory/search', 'server' => 'Lorem+ipsum'],
You need to use pattern in the format <ParamName:RegExp>
Read here
try something like this in your urlManager section rules.
'site/search/<server:\w+>' => 'site/search'
Url::to(['site/search', 'server' => 'lorem_ipsum']) could be display site/search/lorem_ipsum

How to make a Guzzle post using query string parameters

In a Google Oauth2 implementation I'm trying to exchange an authorization code for tokens using a guzzle call.
The following guzzle call works fine and returns the expected values:
$result = $this->client->post(
'https://www.googleapis.com/oauth2/v3/token?code=<authorization_code>&redirect_uri=<redirect_uri>&client_id=<client_id>&client_secret=<client_secret>&grant_type=authorization_code')
->getBody()->getContents();
However this seems a dirty way to mount the post request.
I've tried the following way in order make it cleaner:
$result = $this->client->post(
'https://www.googleapis.com/oauth2/v3/token',
[
'query' =>
[
'code' => <authorization_code>,
'redirect_uri' => <redirect_uri>,
'client_id' => <client_id>,
'client_secret' => <client_secret>
'grant_type' => 'authorization_code',
]
]
)->getBody()->getContents();
However this second call generates a Malformed Json error message.
Any idea what I might be doing wrong or how can I debug what final url is being generated in the example above?
I tried without code parameter and it worked.
$client = new \GuzzleHttp\Client();
$response = $client->post('https://www.googleapis.com/oauth2/v3/token', [
'query' => [
'client_id' => '...apps.googleusercontent.com',
'client_secret' => 'secret',
'refresh_token' => 'token',
'grant_type' => 'refresh_token'
]
]);
$token = $response->getBody()->getContents()
Have you tried using arrays and http://php.net/json_encode

updating a column Parse Rest API

i am trying to update a Users information for ex. Phone, email etc.
i looked at this: https://parse.com/docs/rest/guide#users-updating-users
so i wrote this in my controller:
#response = HTTParty.put('https://api.parse.com/1/users/',
:headers => {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" => "APIKEY",
"X-Parse-Session-Token" => session[:session_token],
"Content-Type" => "application/json"},
:data => {"phoneNumber" => "9994432"})
I return #response in a view and get back this:
{"error"=>"requested resource was not found"}
I was thinking maybe its because im not passing the user's objectid in the url?
Well, now that you have played with creating HTTP requests to API manually, it's time to switch to some library/gem for interactions with Parse. Hopefully, people who built the library that you will find, already have dealt with many routine tasks (like formatting your JSON properly – the error you are investigating right now), and have good documentation for many cases.
I suggest parse-ruby-client.
Add gem 'parse-ruby-client', github: 'adelevie/parse-ruby-client' to Gemfile (it's better to use master version, not the current Rubygems version, because they are saying that there are some useful changes which are not yet pushed to Rubygems), then run bundle install as usual, and you are good to go.
Object saving is as easy as
game_score = client.object("GameScore")
game_score["score"] = 1337
game_score["playerName"] = "Sean Plott"
game_score["cheatMode"] = false
result = game_score.save
puts result
according to their documentation.
UPD. Answering original question. You can use a function to provide object id dynamically:
def update_user(object_id)
#response = HTTParty.put("https://api.parse.com/1/users/#{object_id}",
:headers => {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" => "APIKEY",
"X-Parse-Session-Token" => session[:session_token],
"Content-Type" => "application/json"},
:data => {"phoneNumber" => "9994432"})
end
My solution is force the variables to int and string
response = HTTParty.put("https://api.parse.com/1/users/#{object_id}",
:headers => {
"X-Parse-Application-Id" => ENV['PARSE_APP_ID'].to_s,
"X-Parse-REST-API-Key" => ENV['PARSE_API_KEY'].to_s,
"X-Parse-Session-Token" => token.to_s,
"Content-Type" => "application/json"},
:body => {"h_optimum" => optimum.to_i,
"h_moderate" => moderate.to_i,
"h_appalling" => appalling.to_i}
)

Resources