this my method
public function postOrUpdateProductRd($payload)
{
$payload = json_encode($payload);
$access_token = $this->authenticate->result->access_token;
$this->header = [
'content-type' => 'application/json',
'Authorization' => ' Bearer ' . $access_token,
];
$response = Http::withHeaders($this->header)->post($this->urlBase . $this->endPoint, $payload);
}
How could I save the token I get there to use it until it expires. And how to check if it is expired?
it comes like this when I run the request:
^ {#46
+"token_type": "bearer"
+"access_token": "zurUe8QF386NSyljiTbkXCdcUAZ8rIal"
+"expires_in": 7200
}
I need to store the token somehow to use until it requests a new one as it has expired.
I'm a beginner at this sorry if I was reductive.
Related
I'm using Postman and can generate a new token with the "Get new access token" button. How to create a function that updates my token current?
This is my current function:
def access_token():
url = "my_url"
token = "my_current_token"
payload = ""
headers = {
'Authorization': f'Bearer {token}',
'Cookie': 'my_cookie'
}
response = requests.request("GET", url, headers=headers, data=payload)
return response.json()
var user = pm.globals.get("clientId");
var pw = pm.environment.get("clientSecret");
var grantTypeAndScope = "grant_type=client_credentials&scope=scopes"
pm.sendRequest({
url: "https://"+pm.environment.get("host")+"/as/token.oauth2",
method: 'POST',
body: grantTypeAndScope,
header: {
'Authorization': "Basic " + Buffer.from(user+':'+pw).toString("base64"),
"Content-Type": "application/x-www-form-urlencoded",
}
}, function (err, res) {
if (err === null) {
console.info(res);
pm.environment.set('auth_token', res.json().access_token)
} else {
console.error(err);
}
});
Then in the auth tab of my api requests I set the auth type to bearer and use the variable {{auth_token}}
I actually have the javascript to refresh my token in my pre-request tab at the collection level, so it grabs a new token with each request. Not optimal, but I never have to worry about an expired token.
I'm trying to build a program which can control my Sonos Speaker. I'm following the instructions over at https://developer.sonos.com/build/direct-control/authorize/.
The first step - getting the authorization code - is working as intended but the problem I'm facing arises when I try to send the authorization code per POST request with the following code:
const redirect_uri = "https%3A%2F%2Fsonoscontrol-c4af4.web.app%2F";
const redirect_url = "https://sonoscontrol-c4af4.web.app/";
const client_id = // API Key (deleted value for safety)
const secret = // Secret (deleted value for safety)
const auth_url = `https://api.sonos.com/login/v3/oauth?client_id=${client_id}&response_type=code&state=testState&scope=playback-control-all&redirect_uri=${redirect_uri}`;
function GetAccessToken() {
var target_url = "https://api.sonos.com/login/v3/oauth/access/";
var authCode = GetAuthCode();
var encoded_msg = btoa(client_id + ":" + secret); // base64-encodes client_id and secret using semicolon as delimiter
var params = "grant_type=authorization_code" + `&code=${authCode}` + `&redirect_uri=${redirect_uri}` + `&client_id=${client_id}`;
var myHeaders = new Headers({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Authentication': `Basic {${encoded_msg}}`,
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
});
fetch(target_url, {
method: "POST",
mode: "no-cors",
credentials: "include",
redirect: "follow",
headers: myHeaders,
body: params
}).then((res) => {
console.log(res.responseText);
}).catch(function(error) {
console.log(error);
});
}
function GetAuthCode() {
return (new URLSearchParams(location.search)).get('code'); // returns authorization code from URL
}
Now I get the following error when trying to send the POST request: POST https://api.sonos.com/login/v3/oauth/access/ net::ERR_ABORTED 403 (Forbidden)
I am using a Cloud Firebase app as webserver and added the correct redirect URL in the credentials.
What could be the problem for this error message?
I noticed a couple of things in your code that may be causing your 403 Forbidden issue.
Your "Authentication" header should be "Authorization", eg: "Authorization: Basic {YourBase64EncodedClientId:SecretGoesHere}"
Your "target_url" has a trailing slash, it should be "https://api.sonos.com/login/v3/oauth/access"
Your query parameters "params" are including the client_id on the token request, which isn't necessary, though I don't believe it will cause an error.
Addressing the above should hopefully resolve your issue!
Thanks,
-Mark
I want to send a JWT token to express server with axios POST method.
What I have tried is:
let data = data
let head = {header: { Token: localStorage.getItem("token") }}
axios
.post("http://localhost:3003/api/v/helllo", data, head)
.then((result) => {
console.table(result);
})
.catch((err) => {
console.error(err);
});
Usually, when working with JWT - Authorization header is used. Also pay attention that instead of header - headers field should be used:
let head = {
headers: {
Authorization: 'Bearer ' + localStorage.getItem("token")
}
};
Beware, that storing tokens in local storage is not secure.
I'm using Xero OAuth2.0 APIs, I am refreshing token once token is expired.
Xero Documentation
I'm storing token in JSON file so i can retrive next time.
Erorr Response:
{
"error": "invalid_grant"
}
Please refer below code i've used
public function getAccessToken($code = null) {
if(file_exists($this->tokenPath) && isset($code)) {
$accessToken = $this->getAccessTokenFromAuthCode($code);
} else if (file_exists($this->tokenPath)) {
$accessToken = $this->getAccessTokenFromJSON();
try {
if (time() > $accessToken->expires) {
$accessToken = $this->provider->getAccessToken('refresh_token', [
'refresh_token' => $accessToken->refresh_token
]);
}
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
//header('Location: ' . $this->getAuthorizationUrl());
}
} else if(isset($code)){
$accessToken = $this->getAccessTokenFromAuthCode($code);
} else {
header('Location: ' . $this->getAuthorizationUrl());
}
return $accessToken;
}
public function getAccessTokenFromAuthCode($code) {
return $this->storeAccessTokenToJSON($this->provider->getAccessToken('authorization_code', ['code' => $code]));
}
public function getAccessTokenFromJSON(){
return json_decode(file_get_contents($this->tokenPath));
}
public function storeAccessTokenToJSON($accessToken){
file_put_contents($this->tokenPath, json_encode($accessToken));
return json_decode(file_get_contents($this->tokenPath));
}
The expiration for an access token is 30 minutes. And Unused refresh tokens expire after 60 days. If you don’t refresh your access token within 60 days the user will need to reauthorize your app.
If you perform a token refresh successfully you get a new refresh token with the new access token
If for whatever reason, you don't receive the response after performing the token refresh you can retry refreshing the old token for a grace period of 30 minutes
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://identity.xero.com/connect/token?=",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array(
'XXXXXXXXXXXXX','client_secret' =>
'YYYYYYYYYYYYYYYYYYYYYYYYYYYYY'),
CURLOPT_HTTPHEADER => array(
"grant_type: refresh_token",
"Content-Type: application/json",
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Did you specify the 'offline_access' scope when you got your initial token?
https://developer.xero.com/documentation/guides/oauth2/scopes#offline-access
Invalid_grant is the standard error response code when a refresh token has expired.
Common token lifetimes are something like:
* Access token = 60 minutes
* Refresh token = 8 hours
When the refresh token expired you have to get the user to log in again.
My EdX API access request has been approved. As per the documentation, I have generated the client id and client secret on the admin website. Using fetch, I have got the token from the https://api.edx.org/oauth2/v1/access_token URL by passing the client id and client secret. The token is a valid one I can see in my console. But when I pass this token as below, I get a 403 (Forbidden) error:
fetch("https://api.edx.org/catalog/v1/catalogs", {
method:"GET",
headers: {
"Authorization": "JWT " + token,
"Access-Control-Allow-Origin": "http://localhost:3000"
}
})
.then( r => r.json() )
.then( res => console.log("SUCCESS " + res.count) )
.catch( err => console.log("ERROR " + err) );
I have tried all the variations of the request like credentials:true, all the "Allow-control" headers etc, but this error persists. Upon using the dev tools on chrome, the "Network" tab shows a completely different Fetch is used which is:
fetch("https://api.edx.org/catalog/v1/catalogs", {
"credentials":"omit",
"referrer":"http://localhost:3000/",
"referrerPolicy":"no-referrer-when-downgrade",
"body":null,
"method":"GET",
"mode":"cors"
});
The equivalent curl works at the command line and through Insomnia, and gets the data perfectly.
Without knowing the ins and outs of the specific system to which you are connecting, I cannot be authoritative, but most systems seem to use not JWT but Bearer as the prefix to the authorization bearer token in the Authorization header:
const res = await fetch("https://api.edx.org/catalog/v1/catalogs", {
headers: {
"Authorization": "JWT " + token
}
});
const json = await res.json();