I'm working with a C++ application in embarcadero RAD Studio.
I'm trying to access my swagger api https://camur3.treffo.se/api/swagger/index.html to fetch information using the RESTClient, RESTRequest and RESTResponse components.
Now the API is authorized with bearer + token. Right now i can get out the token:
So i've trying to do a new call to the api from another button
void __fastcall TForm7::B_NewRequestClick(TObject *Sender)
{
RESTClient1->BaseURL = "https://camur3.treffo.se/api/users/authenticate/access";
//Request header + token??
RESTRequest1->Execute();
}
But don't know how to send the token in next request..
Anyone who knows how to do this?
You need to put the token in an Authorization request header, eg:
RESTRequest1->Params->AddHeader(_D("Authorization"), _D("Bearer ") + token);
Or
RESTRequest1->AddParameter(_D("Authorization"), _D("Bearer ") + token, TRESTRequestParameterKind::pkHTTPHEADER);
Or
RESTRequest1->AddAuthParameter(_D("Authorization"), _D("Bearer ") + token, TRESTRequestParameterKind::pkHTTPHEADER);
Related
I am attempting to create my first PowerBI Custom Connecter to connect to the Vimeo API. I am stuck on the final step of the authorization flow - getting back an access token. When trying out the Connecter in PowerBI, it seems to authenticate properly when I hit the access token endpoint, but I get back a warning "[unsupported_grant_type] Unsupported grant type"
It appears I am not sending the grant_type properly in the request. Here are Vimeo's requirements of what is sent along in the header and body of the request:
Header
Set value to
Authorization
basic base64_encode(x:y), where x is the client identifier and y is the client secret
Content-Type
application/json
Accept
application/vnd.vimeo.*+json;version=3.4
"In the request body, send the grant_type field with the value authorization_code. You must also set code to the authorization code string that you just received and redirect_uri to the redirect URI that you specified previously — don't use a different redirect URI."
{
"grant_type": "authorization_code",
"code": "{code}",
"redirect_uri": "{redirect_uri}"
}
Here is a snippet of code from the Customer Connector I am building. It is within this TokenMethod function that I am trying to fulfill the requirements of the table above. I am getting the sense I am not correctly placing the JSON in the body of the request, but I am stuck on what to try next:
TokenMethod = (grantType, tokenField, code) =>
let
queryString = [
grant_type = "authorization_code",
redirect_uri = redirect_uri,
client_id = client_id,
client_secret = client_secret
],
queryWithCode = Record.AddField(queryString, tokenField, code),
authKey = "Basic " & Binary.ToText(Text.ToBinary("client_id:client_secret"),BinaryEncoding.Base64),
tokenResponse = Web.Contents(token_uri, [
Content = Text.ToBinary(Uri.BuildQueryString(queryWithCode)),
Headers = [
#"Authorization" = authKey,
#"Content-type" = "application/json",
#"Accept" = "application/vnd.vimeo.*+json;version=3.4"
],
ManualStatusHandling = {400}
]),
body = Json.Document(tokenResponse),
result = if (Record.HasFields(body, {"error", "error_description"})) then
error Error.Record(body[error], body[error_description], body)
else
body
in
result;
I'm wondering if someone could please point out where I might be going astray in the code and why I am receiving the [unsupported_grant_type] error.
Many thanks for your time!
I changed Content-Type to "application/x-www-form-urlencoded" and it worked!
I am working on customizing my spring boot authorization server. After login using username and password from the html page I have created I need to redirect back to /oauth/token endpoint ,in order to get the access token .
It is working fine while using postman. But when I give defaultsuccessurl as /ouath/token it shows me a default login page to enter username and password which the basic auth username and password from postman.
so, in order to get the access token from front end I need to add basic auth details as http header. I don't know where to add HTTP header and how to use that to get the access token after successful login using front end.
Any help appreciated
There are multiple ways to do it. One way is: along with html, you can use Javascript to set HttpHeaders and send the request. Below a sample code snippet (not complete though)
var user = "user1"; //ideally this should come from Input field in html page
var password = "MySecret";//ideally this should come from password field in html page
// var authorizationBasic = $.base64.btoa(user + ':' + password);
var authorizationBasic = window.btoa(user + ':' + password);
var request = new XMLHttpRequest();
request.open('POST', oAuth.AuthorizationServer, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'application/json');
request.send("<requestURL>");
I am working in google script API trying to get a schema of a table from BiqQuery... not sure why it is so troublesome.
I am sending a request like this :
let url = 'https://bigquery.googleapis.com/bigquery/v2/projects/'+ projectId +'/datasets/'+ datasetId +'/tables/' +tableId;
var response = UrlFetchApp.fetch(url)
I am getting this response:
Exception: Request failed for https://bigquery.googleapis.com returned code 401. Truncated server response: { "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie ... (use muteHttpExceptions option to examine full response) (line 68, file "bigQuery")
I have been able to load data to bigQuery alright... not sure why this does not work. I have looked at the OAuth fields in manifest and the script does have access to bigQuery...
no success also when adding this to the options field of the UrlFetch request
var authHeader = 'Basic ' + Utilities.base64Encode(USERNAME + ':' + PASSWORD);
var options = {
headers: {Authorization: authHeader}
}
Use bearer tokens
The reason why the BigQuery API rejects your requests is that the endpoint requires one of the following scopes to be provided with the access token to work, and it is missing from the request:
https://www.googleapis.com/auth/bigquery
https://www.googleapis.com/auth/cloud-platform
https://www.googleapis.com/auth/bigquery.readonly
https://www.googleapis.com/auth/cloud-platform.read-only
The actual issue here is that the basic authorization scheme lacks info about any claims, only sending over correct credentials. Since you are requesting the endpoint directly with UrlFetch service, despite correctly specifying the scopes in the manifest, they will not be sent over.
ScriptApp service now provides an easy method to get a valid bearer token without using an OAuth 2.0 library or building the flow from scratch: getOAuthToken. Pass it to an Authorization header as bearer token, and you should be all set:
const token = ScriptApp.getOAuthToken();
const options = {
headers : {
Authorization : `Bearer ${token}`
}
};
Use Advanced Service
As an alternative, there is an official advanced service as a wrapper around BigQuery REST API that will manage authentication and response parsing for you.
You must enable the BigQuery advanced service before using it
Also, note that the advanced service identifier is configurable, so you have to reference the identifier you chose.
In your case, the service can be used as follows (assuming you used the default BigQuery identifier). There is also the 4th argument of type object that contains optional arguments (not shown here):
Bigquery.Tables.get("projectId","datasetId", "tableId");
The method chain above corresponds to tables.get method of the BigQuery API.
Hi I want to use Apache HTTP Client Fluent to create a request to download a file. I need to add Autorization Basic Auth to the request to pass in a username and password which I can't find a good example of how to do.
I can see a addHeader method but can't find good examples of how to construct it. Thanks!
So far the code i have is:
String auth = username + ":"+ token
byte[] encodedBytes = Base64.encodeBase64(auth.getBytes());
String encodedAuth = new String(encodedBytes)
URL downloadFileURL = new URL (urlbuild)
Executor executor = Executor.newInstance();
executor.execute(Request.Get(downloadFileURL.toURI())
.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth )
.connectTimeout(1000))
.saveContent(new File(mobileAppPath + System.getProperty("file.separator") + mobileApp.name));
the problem was due to Java trying to validate the SSL certificate i used Java code below to trust all hosts before executing the request.
https://www.javatips.net/api/java.security.cert.x509certificate
We have built a Xamarin.Forms application that uses REST API calls.
The initial load of the application is fast however the first API call is slow (extra 3-4 secs comparing to the second request against the same URL).
The behavior is similar on both iOS and Andorid platforms.
Is there any option to eliminate this waiting time?
Here is a sample code we use to do the API call (by using unirest package):
HttpResponse authRes = Unirest.post(App.TenantConfig.response.idmUrl + "/api/v1/authn")
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.header("Cache-Control", "no-cache")
.header("Postman-Token", "672008d5-52f7-8997-3e04-57ac24b6dab6")
.body("{\n \"username\": \"" + Username + "\",\n \"password\": \"" + Password + "\",\n \"options\": {\n \"multiOptionalFactorEnroll\": true,\n \"warnBeforePasswordExpired\": true\n } \n}")
.asString();