I am using the tymondesigns/jwt-auth package for my app. I use customClaims to make my token.
Here is the code for login :
$token_data = [
'iss' => new Issuer('AreteHCM'),
'iat' => new IssuedAt(Carbon::now()) ,
'exp' => new Expiration(Carbon::now()->addDays(1)),
'nbf' => new NotBefore(Carbon::now()),
'sub' => new Subject('AreteHCMS'),
'jti' => new JwtId('AreteHCM'),
'user_data' => $user->user,
'menu_access' => $menu_access,
'login_time' => Carbon::now(),
];
$customClaims = JWTFactory::customClaims($token_data);
$payload = JWTFactory::make($customClaims);
$token = JWTAuth::encode($payload)->get();
For Logout, I invalidate the token, so the token can not be used anymore after the user logout.
JWTAuth::invalidate(JWTAuth::getToken());
I'm creating API (Backend) and the front end team using Angular. Eveythings went smooth, until the user logout and try to login again. After login, the user get the new account, but when he/she wants to access my middleware always rejects the token, it says that the token is blacklisted.
Here is my middleware :
$token = JWTAuth::getToken();
$data = JWTAuth::getPayload($token)->toArray();
It always shows error :
The token has been blacklisted in file C:\xampp\htdocs\aretehcm\vendor\tymon\jwt-auth\src\Manager.php on line 109
What I want to approach is :
User login get new token to access the API (every API request requires header auth Bearer token)
User logout will invalidate the token, so the token can not be used anymore to access the API
User login will get a new token so he/she can access the API
Is there any misconception from me about the JWT-API architecture ?
Thank you in advance for your replies and answers.
A quick google search pointed me towards this solution:
https://github.com/tymondesigns/jwt-auth/issues/983#issuecomment-275884324
Related
I'm using y0lk package to help me with OAuth1 and ETSY App, I managed to get the temporary credentials, but can't get my hand on Access tokens.
here's what I do :
$client = new Etsy([
'identifier' => '*********************',
'secret' => '*********',
'scope' => 'listings_r transactions_r',
'callback_uri' => 'http://*********.loc/slider/'
]);
$tempCred = $client->getTemporaryCredentials();
$tmpSecret = $tempCred->getSecret();
$tmpId = $tempCred->getIdentifier();
// Redirect to Etsy Autorisation login page
$redirect_url = $client->getAuthorizationUrl($tempCred);
$accessTokens = $client->getTokenCredentials($tempCred, $tmpId, $_GET['oauth_verifier']);
Ok, I don't know how to do, because to obtain the oauth verifier ( and do the $_GET['oauth_verifier']), I have to go by the login page, and then, to get the access token, I need my temp credentials, but to get then I 'll have to go again by new Etsy and this is why I always got the token revoked error..
I'm beginner, in PHP and with API, if someone see other mistakes in my way to do this, feel free to point them out for me :)
Thank you for your time.
I am having difficulty get a refresh token. For some reason it seems that the Graph API is not recognizing my offline_access scope. Here is my PHP code:
$oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => "id",
'clientSecret' => "secret",
'redirectUri' => "redirect",
'urlAuthorize' => "https://login.microsoftonline.com/xxxx/oauth2/v2.0/authorize",
'urlAccessToken' => "https://login.microsoftonline.com/xxxx/oauth2/v2.0/token",
'urlResourceOwnerDetails' => '',
'scopes' => 'MailboxSettings.ReadWrite offline_access'
]);
From my redirect script, I get a code but not a refresh token. Shouldn't I get both or am I not understanding how it works.
You were using OAuth 2.0 code grant flow.
In this flow, you will firstly make a request to the authorize endpoint. The authorize endpoint will return an authorization_code to you. Then you will make a POST request with the authorization_code to the token endpoint to get an access token and refresh token.
I checked the tutorial for OAuth 2.0 Client - Authorization Code Grant, the sample contains the logic for getting access token and refresh token. You can refer to the relevant code.
As per sdk documentation.
https://intuit.github.io/QuickBooks-V3-PHP-SDK/authorization.html
"That is what refresh token used for. It is used to request a new access token after access token expired, so you can still access to the QBO company after an hour. Just remember, whenever you make a refreshToken API call, always STORE THE LATEST REFRESH TOKEN value in your session or database"
This is the case: So my access token is expired I need to get a new one I'll run the code below.
$loginHelper = new OAuth2LoginHelper($this->clientID, $this->clientSecret);
$token = $loginHelper->refreshAccessTokenWithRefreshToken($this->refreshToken);
Then the token variable in code above will give me the new access token using this code.
$token->getAccessToken();
It was successful I have the new access token now.
However, seems refresh token is not changing quickbooks said "STORE THE LATEST REFRESH TOKEN" but the $token obj returns are the same.
My refresh token use to request new access token is:
string(50) "Q011532218006WxAY7UnIdulGDJAcgnaoTi7pIkHVaaQld9Me3"
then the return of my request:
QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken Object
(
[accessTokenKey:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..llxj6kOGCzFiqBShGPUtbg.rNbEdMvhD0iER3z4IwB-azYbbk9givKxtaiDh7Uch8HbmZLkF7-xckpgiMDk8V5lYwYOCfP1EaPFa0iJlpbNPZdT7RBfPIkEqotTVfP0UNPwC13a37PpYHOvg_Sxbp_5GuOvdIa1RVskn4tY_FIOaCVnTaxuDF4MWNKOxsitHEoYxzVVcdqigTWri9yfIA6ZqO2vTAc92iTsa30L9jYcFeEdaNVaPt7zyM-y_FzY2W72uq8fyYjpv-fmvWMwv94pCJ6VoV82rM7OmLh5sOWORKfcZJ0xDLMrKddUPnA0GVl3mb3E6D-JyQ2-N2AYNW553nryI9f9iuoAqv7f6bXhzmaO-ByN0xtDEt9E48CFN-tyA_qShtwmEUajhsq0XFrUZgR0rtEq2kSvj79v3-sX1P7qCjPPrGK2q12VQ24DbVWnDYDZslYh9nyJGtiZgXu-GWFNKhfaXI76U_ASC2yefrcWu6ioIdDrn8j75B9AZgg3GpBqkT7H2qHWGqieeuJmcuFVoYIJUiztZNrDWYvmCJv_w2KlG911GHqLO7K7AznzpiSdIWwGXVBSxYRBbCVQTFJge1SYkXYOWj1OP9aFttpxRNX_ctiAiqV5IA9JBs_T3H4w6mGYRt4NpXZCMn3Yguwc1LekmCn0r83taHjvOT0_l78c1zv2nWC_ADKgdd1lPLMzQHiNWnHCDIBrRYm0.h0WaCjevbfdig0G-zQM9eA
[tokenType:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => bearer
[refresh_token:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => Q011532218006WxAY7UnIdulGDJAcgnaoTi7pIkHVaaQld9Me3
[accessTokenExpiresAt:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 1523499723
[refreshTokenExpiresAt:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 1532218006
[accessTokenValidationPeriod:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 3600
[refreshTokenValidationPeriod:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 8721883
[clientID:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => Q032lsDMTnotxhcOudLOpyfYuDXfB9xEMWpMRpvFIwW1VV1eyQ
[clientSecret:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => Ml3Id7ZgeVNzAbxecHwwwzrBmuKeQXw7kljlwT84
[realmID:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] =>
[baseURL:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] =>
)
As per quickbooks developer, "The previous refresh token expires after 24 hours after you create a new one. So you would get the same refresh token from the time you refresh untill the next 24 hours."
Read more: Click Here
I'm trying to use FOSOAuthServerBundle. It works pretty well but I try to make it works in API...
When I register a new user I create a new client and I would like to give him authorization directly.
The request of the access_token will be done when the user will log in...
The problem, the example given in the documentation, it makes a redirection to an authorization page, and after it will redirect to an URL...
It would be great to it without any redirection, only to make the authorization...
Part of my register code :
$user->setUsername($name);
$user->setEmail($email);
$encoder = $this->get('security.encoder_factory')->getEncoder($user);
$password_user = $encoder->encodePassword($password, $user->getSalt());
$user->setPassword($password_user);
$clientManager = $this->get('fos_oauth_server.client_manager.default');
$client = $clientManager->createClient();
$client->setRedirectUris(array('http://localhost:8888/app_dev.php'));
$client->setAllowedGrantTypes(array('token', 'authorization_code'));
$clientManager->updateClient($client);
$user->setClient($client);
// Here we would like to authorize the user witout redirection :
return $this->redirect($this->generateUrl('fos_oauth_server_authorize', array(
'client_id' => $client->getPublicId(),
'redirect_uri' => 'http://localhost:8888/app_dev.php',
'response_type' => 'code'
)));
I would like to authorize without any redirection... Because it's in API :/ , so no URL...
Is there another way to authorize ?
Thanks
I have been trying for several days now to successfully post to a client's Facebook Page wall from their website. I need to be able to do this without having a user logged in, which I was able to achieve with an extended access token generated by going to the URL provided in the docs.
What I am trying to do is to fetch an extended token using the PHP SDK as in this question - Facebook PHP SDK: getting "long-lived" access token now that "offline_access" is deprecated, however I receive the following error:
(#200) The user hasn't authorized the application to perform this action
The debug of the auth token generated by the Graph API Explorer shows myself as the User and includes the needed manage_pages and status_update scopes. However, if I run me/accounts, the perms array does not list these under the data for the page in question - not sure if this is relevant.
Here is the code that I have attempted to use:
$facebook = new Facebook(array('appId' => 'xxxxxxx', 'secret' => 'xxxxxx'));
$pageID = 'xxxxxxxx';
$facebook->setExtendedAccessToken();
$accessToken = $facebook->getAccessToken();
try {
$page_info = $facebook->api("/$pageID?fields=access_token");
print_r ($page_info);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
if( !empty($accessToken) ) {
$args = array(
'access_token' => $accessToken,
'message' => "Catch phrase!"
);
$facebook->api("/$pageID/feed","post",$args);
} else {
// Handle error
}
UPDATE
I found that if I echoed the output of getAccessToken() the result was the app ID and the secret separated by an | - is this what I should be receiving? Seems odd to me since all of the other tokens I have seen are random and much longer.
ANY help at all would be appreciated, I have wasted so much time on this so far. It just seems to work for everyone else.
UPDATE 2
Hi Warren! Looks like you're new around these parts, welcome! Thanks for your research into this, do I need to save these tokens into a DB table and check to see if they are expired every time I try to post? I am ONLY posting to a Page as the Page, apparently this requires the Page access_token rather than what I am assuming is the USER access_token. I believe I also read somewhere that the Page access token never expires, although it changes if I refresh the Graph API Explorer page or request a new user token. Very puzzling.. do not know if I even need to deal with getting new tokens in this app or just use a Page access_token that appears to work?
Also just looking at the base_facebook.php file and the following function:
/**
* Returns the access token that should be used for logged out
* users when no authorization code is available.
*
* #return string The application access token, useful for gathering
* public information about users and applications.
*/
protected function getApplicationAccessToken() {
return $this->appId.'|'.$this->appSecret;
}
Shows what you are experiencing the function setExtendedAccessToken() calls getAccessToken() which calls the function above to do the following inside setExtendedAccessToken:
$access_token_response = $this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array(
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'grant_type' => 'fb_exchange_token',
'fb_exchange_token' => $this->getAccessToken(),
)
);
the return of this function is then {"error":{"message":"No user access token specified","type":"OAuthException","code":1}} but because there is no access_token the function just returns false
the fb_exchange_token can not be the app id and app secret combined.
I have done some testing and what I have found out is if you get the user to login, you can get there access token. If you pass this token into setAccessToken then run setExtendedToken. If you then save the toke by running getAccessToken you can use this token later when the user is logged out.
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // save this for later use
You need to get the user to login to ask them for permission to get access to there account. If you need to get access to a facebook page make sure they are an admin and ask for the manage_page permission.
Hope this helps
From what I have found so far the extended token that is returned when the user is logged in does not expire as you do not get back a unix timestamp so you would have no way of knowing when it expires.
This is what I have done in my application.
Request the user to login to facebook and except the access permissions. Use getAccessToken to get the current access token. With this I pass into getExtendedAccessToken then run getAccessToken again to finally get the extended access token which I store in a database for later use.
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$params = array(
'scope'=>'publish_stream,manage_pages'
);
$loginUrl = $facebook->getLoginUrl($params); // Use this to request them to login in then when they are do the following you will need them to return to your app
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // store $access_token for later use