loopback access_token not found - loopback

followed by the access documentation
both are not working by using
Authorization Header
Query Parameter
Using the latest version of loopback 2.1.X.
I turned off the email verification and successfully got the AccessToken object from the initial login. The header and the query request are not working now.
ACCESS_TOKEN=6Nb2ti5QEXIoDBS5FQGWIz4poRFiBCMMYJbYXSGHWuulOuy0GTEuGx2VCEVvbpBK
Authorization Header
curl -X GET -H "Authorization: $ACCESS_TOKEN" \
http://localhost:3000/api/widgets
Query Parameter
curl -X GET http://localhost:3000/api/widgets?access_token=$ACCESS_TOKEN

In header pass key as authorization not ACCESS_TOKEN
In query params pass key as accessToken not access_token

Here is what works for me in Angular 2 :
initRequestOptions(accessToken:any) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Authorization', accessToken);
return new RequestOptions({headers: headers});
}
makeRequest(accessToken:any){
let options = this.initRequestOptions(accessToken);
this.http.get('http://' + apiUrl + '/api/MyModel, options)
.subscribe(
//...
)
}
So basically you need to create a headers object , add an 'Authorization' item whoes value is the access token , and use the headers object to create a RequestOptions object to be inserted in the request.
Also loopback explorer passes the access token as a url encoded parameter so this should work too :
http://localhost:3000/api/MyModel?access_token=X3Ovz4G1PfmPiNGgU5YgORPwPGLaVt9r8kU7f4tu1bDMyA4zbqiUEgeDAC3qkZLR

Related

Consuming method auth Yodlee API

I am new to using this Yodlee tool, I created my developer account, and I am wanting to consume the sandbox APIs.
I am not being able to consume by rest with the Talend Api not even the initial method of "auth" (https://sandbox.api.yodlee.com/ysl/auth/token) to obtain the token; I'm passing the loginName, Api-version: 1.1, and content-type in the header as specified, then the clientId and the secret in the body.
The error message it returns is:
{
"errorCode": "Y303",
"errorMessage": "clientId or secret is missing",
"referenceCode": "rrt-8413800343306027303-c-gce-12663 ....."
}
Maybe the sandbox account doesn't allow me to do this, or am I forgetting something?
I just got the same issue. I am using RestSharp.
Finally found out that's a mismatched Content-Type.
It works after adding the header: Content-Type: application/x-www-form-urlencoded
For anyone having this issue with Google Apps Script, this is how I did it:
/************************************************************************************
*
* This function starts the app, replace variables as necessary
*
************************************************************************************/
function primaryFunction() {
// Declare variables
var yodleeToken = {};
var loginName = "ENTER_LOGIN_NAME";
var clientID = "ENTER_CLIENT-ID";
var clientSecret = "ENTER_CLIENT_SECRET";
var yodleeURL = "https://sandbox.api.yodlee.com/ysl/";
// Generate user token
yodleeToken = getUserToken(loginName, clientID, clientSecret, yodleeURL);
}
/************************************************************************************
*
* Creating function to get user token
*
* #params loginName {String} Login name provided by Yodlee API
* #params clientID {String} Client ID provided by Yodlee API
* #params clientSecret {String} Client Secret provided by Yodlee API
* #params yodleeURL {String} Yodlee API Endpoint
*
* References
* https://av.developer.yodlee.com/
*
************************************************************************************/
function getUserToken(loginName, clientID, clientSecret, yodleeURL) {
// Specify headers
var headers = {
'Api-Version': '1.1',
'Content-Type': 'application/x-www-form-urlencoded',
'loginName': encodeURIComponent(loginName)
};
// Build params
var parameters = {
'method': 'POST',
'headers': headers,
'payload': encodeURI("clientId=" + clientID + "&secret=" + clientSecret),
'redirect': 'follow',
'timeout': 0,
// 'muteHttpExceptions': true,
};
// Call API with params
var response = UrlFetchApp.fetch(yodleeURL + "auth/token", parameters);
var responseJSON = JSON.parse(response);
// return JSON response with Link Token
return responseJSON;
}
You need to pass clientId and secret key in data-urlencode and remaining keys in header then it will return token
curl --location --request POST 'https://sandbox.api.yodlee.com/ysl/auth/token' \
--header 'Api-Version: 1.1' \
--header 'loginName: From your dashboard (Sandbox only)' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'clientId=Your clientId' \
--data-urlencode 'secret=Your secret'

Trying to run code in IBM Cloud Functions

I have following code I am trying to run in IBM function to get billing data out:
iam_token = 'Bearer eyJraWQiOiIyMDE3MTAzMC0wM****'
def processResourceInstanceUsage(account_id, billMonth):
METERING_HOST = "https://metering-reporting.ng.bluemix.net"
USAGE_URL = "/v4/accounts/"+account_id + \
"/resource_instances/usage/"+billMonth+"?_limit=100&_names=true"
url = METERING_HOST+USAGE_URL
headers = {
"Authorization": "{}".format(iam_token),
"Accept": "application/json",
"Content-Type": "application/json"
}
response = requests.get(url, headers=headers)
print("\n\nResource instance usage for first 100 items")
return response.json()
processResourceInstanceUsage('*****', '11')
For some reason, I keep on getting 201 unauthorized error. I tried creating iam_token many times. It still gives the same error.
There are few things that should be taken care in the code you provided.
The month you are passing is wrong. It should be in YYYY-MM format.
account_id should be the id next to your Account name when you run ibmcloud target
For IAM token, run this command ibmcloud iam oauth_tokens. If you want to generate access token using your Platform API Key, refer to this link. The word Bearer is not required as this is not an authorization token.
Once you have all this in place, create an IBM Cloud function (Python 3), add the below code, pass the account_id and token and invoke the action to see the result . IBM Cloud function expects a dictionary as an input/parameter and JSON as response
import sys
import requests
def main(dict):
METERING_HOST="https://metering-reporting.ng.bluemix.net"
account_id="3d40d89730XXXXXXX"
billMonth="2018-10"
iam_token="<IAM_TOKEN> or <ACCESS_TOKEN>"
USAGE_URL="/v4/accounts/"+account_id+"/resource_instances/usage/"+billMonth+"?_limit=100&_names=true"
url=METERING_HOST+USAGE_URL
headers = {
"Authorization": "{}".format(iam_token),
"Accept": "application/json",
"Content-Type": "application/json"
}
response=requests.get(url, headers=headers)
print ("\n\nResource instance usage for first 100 items")
return { 'message': response.json() }
This worked for me and returned a JSON with region-wise billing data.
Reference: https://stackoverflow.com/a/52333233/1432067

Angular 6 - Add JWT bearer token to header not working

I'm trying to add the auth bearer token header while getting a comment from the asp.net core 2.2 backend in angular 6
getComment(postId: number): Observable<IComment[]>{
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
let authToken = localStorage.getItem('auth_token');
headers.append('Authorization', 'Bearer ' + authToken);
console.log(authToken);
return this.httpClient.get<IComment[]>('api/comment/post/' + postId, { headers });
}
This piece of code is not working. I am getting a value from console.log(authToken). When I copy the token in Postman, everything is working fine.
My login function in a service. This is working fine to, i'm getting the token from the backend.
login(login: ILogin) {
console.log(login);
return this.http
.post('api/auth/login', login)
.pipe(map((res: any) => {
localStorage.setItem('auth_token', res.auth_token);
this.loggedIn = true;
this._authNavStatusSource.next(true);
return true;
}));
}
When I remove authorization from the action in the backend, getting the comments is working fine. As you can see in the image below, the jwt token is just not being add to the header.
Postman:
Header information from chrome
You are not passing the headers in { headers } section.
Change return this.httpClient.get<IComment[]>('api/comment/post/' + postId, { headers }); to return this.httpClient.get<IComment[]>('api/comment/post/' + postId, { headers: headers });
When you say it's working fine via Postman, and that this is not a CORS issue (i.e., either CORS is enabled, or your JS is being served from the same origin as you API), I assume you're already subscribing to the returned Observable<IComment[]>.
The code above won't issue the request until there is a call somewhere that looks like this:
yourService.getComment(postId).subscribe(comments => { ... });
That will begin consuming the Observable and trigger the underlying HTTP request.

Setting authorization header in http client in ionic and angular 5

I am learning ionic for mobile development latest version. I used http client for calling REST API. But I am facing some issues -
1) I am using POST but it showing me as option.
2) How to set authorization header . I am using bearer token and my rest API is written in PHP.
Use HttpHeaders to set your token. token can be defined in a string
func() {
var headers = new HttpHeaders();
let body = new HttpParams();
body = body.set('key','value');
headers = headers.set("Authorization", "Bearer " + token)
return this.http.post('post-url.com', body,{
headers:headers
});
}
Hope that helps!

Uber API: Endpoint requests returns Not supported in sandbox environment

I have successfully completed the first three steps of the authentication process: step one(authorize), step two (receive redirect ) and step three (get an access token).
But, doing the following request gives me an error:
curl -H 'Authorization: Bearer xxxxoKnAKxxxxxndQNRZgRa0Dxxxxx' 'https://sandbox-api.uber.com/v1/requests'
Response:
{"message":"Not supported","code":"not_found"}
I have the same message with all required params:
curl -H 'Authorization: Bearer xxxxoKnAKxxxxxndQNRZgRa0Dxxxxx' 'https://sandbox-api.uber.com/v1/requests?product_id=5b451799-a7c3-480e-8720-891f2b51abb4&start_latitude=48.869576&start_longitude=2.30825&end_latitude=48.84839&end_longitude=2.395921'
Am I missing something?
Edit:
Ruby version with HTTParty:
def request(bearer, product_id="5b451799-a7c3-480e-8720-891f2b51abb4", start_latitude=48.869576, start_longitude=2.30825, end_latitude=48.84839, end_longitude=2.395921)
parameters = { product_id: product_id,
start_latitude: start_latitude,
start_longitude: start_longitude,
end_latitude: end_latitude,
end_longitude: end_longitude
}
self.class.post('/v1/requests', query: parameters, headers: { "Authorization" => "Bearer #{bearer}", 'Content-Type' => 'application/json' })
end
A GET to 'https://sandbox-api.uber.com/v1/requests' won't work since you need to include a such as https://sandbox-api.uber.com/v1/requests/request_id
A POST to 'https://sandbox-api.uber.com/v1/requests' requires you to post the parameters as part of the JSON body.
Once you have the request ID as part of the response, you will able poll for details using the first command.