Yii2 Rest Api User bearer Authentication expiration time - yii2

i am currently working on a yii2 based Rest api. i use bearer token for user authentication.let me explain the requirement.
1)first user authenticated from a external php application using their credentials.
2)he/she got an access Token.
3)each subsequent request is made using this access token.
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['auth_key' => $token]);
}
this is where i start thinking. i do not found any expiration time for the access token. is that really needed? if yes how can i archive that? Thanks in advance.

Your question is kind of broad, but I will attempt to help your thought process along.
i do not found any expiration time for the access token. is that really needed?
That depends on your requirements. Do you want your users to be able to access your API indefinitely after authenticating the first time? Would you like your users to renew their token every so often?
I would recommend the latter, as it limits the time a potential attacker could use a compromised access token.
if yes how can i archive that?
One option would be to add a field containing the datetime of the expiry date to the database table corresponding with your identity class and to check wether this is still valid in the implementation of findIdentityByAccessToken()
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne([
'AND',
['auth_key' => $token],
['>=', 'token_expire', new \yii\db\Expression('NOW()')]
]);
}

Related

how long a firebase cli token stays functional?

I have the following chunk as a part of a recursive delete cloud function , my question is I managed to store the cli token inside fb.token, but how long this token will last ? Is it forever or should have to update it frequently ? , is it even a thing for the user to be able to call this function ? , in my use case , I want to automate the process of deleting user account and his all related collections in one action, and this function really serves me well, not to mention I don’t have to get all docs … so if this stored token fails and deletes gets rejected due to token expiration during production for some reason it could cause big issues in my db structure..
await firebase_tools.firestore.delete(path, {
project: process.env.GCLOUD_PROJECT,
recursive: true,
yes: true,
token: functions.config().fb.token,
force: true,
});
But how long this token will last ? Is it forever or should have to update it frequently ?
Tokens obtained by firebase login:ci doesn't have expiration, though it can be revoked manually. The token is tied to the access privileges of the user and you can check the tokens used in here.
If you want to use another method, I suggest that you use service account for authentication. Then, grant any necessary permissions to the service account in your project. These permissions depend on the actions that had to be performed by the CLI. You can refer to this documentation for further explanation that you must follow.

Flutter send push notifications using fcm for all devices

How are you guys , my problem that my flutter app is connected to mysql db , when the user is registered a string with the class name is saved to shared preferences and there is a wall to post some posts on it , is there any way to work with fcm bassed on the shared preferences string ? Like if the user has this string and posted let all users with the same string get notifications i hope i could make it more uderstandable but i dont know how ! Thanks
This sounds like a perfect use-case for using topics to target those messages. Step-wise:
Each device subscribes to the topic based on their class. If they can have multiple classes, they'd subscribe to all topics for those classes.
You then send the message to the correct topic for its class, and FCM will deliver it to all devices subscribed to that topic.
As usual, you will need to perform the actual send operation from a trusted environment, such as your development machine, a server you control, or Cloud Functions.
you will get the token id from the device which you can store to the user table so it will use while giving the notification to every device.
For getting the token :
_firebaseMessaging.getToken().then((String token) {
assert(token != null);
setState(() {
_homeScreenText = "Push Messaging token: $token";
});
print(_homeScreenText);
});
this token variable which you can store to the user table and use it while giving the notification to every device.

Guide how to actually encrypt JSON Token for APNS

Hope somebody can get me past this point... because I spend pretty much time on it and still not working.
Short story is that I want to use Azure Notification Hub for my Xamarin.Forms app.
It want's these info to work:
That's all good and I got all of them under control, expect the Token one.
Ok, so I follow the Microsoft docs on the subject:
https://learn.microsoft.com/en-us/azure/notification-hubs/notification-hubs-push-notification-http2-token-authentification
I follow along and got things under controls I think, until I get to:
"Authentication token"
Here it says:
The authentication token can be downloaded after you generate a token for your application. For details on how to generate this token, refer to Apple’s Developer documentation.
Like it's no big deal and then it links to this page, which is suppose to help me. Read through it, clicked the links etc. read stuff.
I end up on this page: Establishing a Token-Based Connection to APNs
And the the craziness and confusion really kicks off for me, because, it then says, like it's the most common thing in the world:
Encrypt the resulting JSON data using your authentication token signing key and the specified algorithm
It doesn't really explain much, other than link to the jwt.io tool.
Well, that would have been great if I could make the tool work...
On the surface it's pretty easy, as the docs explains what to put in where, so I do that:
So the "header" and the "payload" is filled in and I assume it's correct - however, at the bottom I clearly need to put in some keys for this to be able to decrypted correctly on the other end...the question what do I put in here?
When I created my key in the Apple Developer portal, I of cause downloded the .p8 file, which I can see contains my PRIVATE key...but I have 2 problems.
Putting that into this jwt.io tool, result in a "invalid signature" right away, and I have no idea what to put into the "PUBLIC KEY" part.
So, what am I doing wrong?
Thanks in advance and really hope somebody can help me, as I'm starting to go crazy over this, "tiny" step in the development that have been taking WAY too long now.
At the bottom of jwt.io there are libraries you can use to encrypt the token on your server. For example, this php library: https://github.com/lcobucci/jwt/blob/3.3/README.md
About public key. I think it's the KeyID that is the public key that APNs uses to verify. You only need the private key to generate the token. It goes like this in this php sample:
$token = (new Builder())->issuedBy('http://example.com') // Configures the issuer (iss claim)
->permittedFor('http://example.org') // Configures the audience (aud claim)
->identifiedBy('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
->issuedAt($time) // Configures the time that the token was issue (iat claim)
->canOnlyBeUsedAfter($time + 60) // Configures the time that the token can be used (nbf claim)
->expiresAt($time + 3600) // Configures the expiration time of the token (exp claim)
->withClaim('uid', 1) // Configures a new claim, called "uid"
->getToken($signer, $privateKey); // Retrieves the generated token
Just to whoever stumbles upon this question.
The token field in the Azure Notification Hubs Settings is the private key which you will find inside the .p8 file you downloaded from Apple Developer Account for Universal APN.
As for the JWT encryption, you need that when you sending a request to apple's apn server directly. You will need to send a Bearer token by encrypting the header and payload ( specifications are in apple's website). The encryption is done by crypto libraries, using algorithm ES256 ( only one supported for APN ) and the signing key is the token we mentioned above, that is the private key in the .p8. This creates a JWT that you include in your Authorization header for the request to APN server

infusionsoft - How to get token without clicking link?

I need to access infusionsoft api without user interaction. I do not want let user to click on a click so I can get a tocken. Is it possible?
$infusionsoft = new Infusionsoft\Infusionsoft(array(
'clientId' => '...',
'clientSecret' => '...',
'redirectUri' => '...',
));
// If the serialized token is available in the session storage, we tell the SDK
// to use that token for subsequent requests.
if (isset($_SESSION['token'])) {
$infusionsoft->setToken(unserialize($_SESSION['token']));
}
// If we are returning from Infusionsoft we need to exchange the code for an
// access token.
if (isset($_GET['code']) and !$infusionsoft->getToken()) {
$infusionsoft->requestAccessToken($_GET['code']);
}
if ($infusionsoft->getToken()) {
// Save the serialized token to the current session for subsequent requests
$_SESSION['token'] = serialize($infusionsoft->getToken());
// MAKE INFUSIONSOFT REQUEST
} else {
echo 'Click here to authorize';
}
Make 3 files
Request_new_token.php. It is similar to your code(Need to run one time only), but you will have to save the token to database or txt file.
//Convert object to string
$token = serialize($infusionsoft->requestAccessToken($_GET['code']));
//Update the token in database.
$update = new Update("systemsettings");
$update->addColumn('systemsettings_strvalue', $token);
$update->run(1);
exit;
Refresh_token.php. With saved token, you will need to refresh it within 21 hours. I suggest to use cronjob to auto run it on server back-end.
General_request.php(Up to your system preference). Whenever you need to make single request to GET/PUT/POST, you just need to initiate infusionsoft object and set token to the new object from database.
Good luck!
If you're looking to interact with the API and not get access via the newer oAuth methods, you'll need to use the depreciated legacy API which uses an API key from the actual Infusionsoft application. The upside is that unless the user changes their API key, you don't need to "renew" or "refresh" the token and you don't need the user to click through an authorize their app.
The big downside, of course, is that this older API has been depreciated and all new applications need to use oAuth.
What is the use case where you can't walk the users through an oAuth authentication flow?

Box Api v2 java - How to reuse the access-token within 3600 secs

I am using Box Api v2 (java) for integrating my webapp with Box.com.
I forward the user to the authorize url
https://www.box.com/api/oauth2/authorize?response_type=code&client_id=client-id
..and receive the 'code' at my redirect end-point. Using this code, I am able to get the access_token and refresh_token. I know that access_token is valid only for 1 hr.
But can I re-use the access_token within this 3600 sec period?
eg:a user comes back within 30 minutes and tries to fetch/put files
In this scenario, I will need to create a new BoxClient.
So what is the recommended method of client authentication using the existing access token?
If answerer can paste code snippets using the box java api, it would be quite helpful.
Or is the refreshing to get new access_token and refresh_token, the only method available?
BoxClient client = new BoxClient(MY_CLIENT_ID, MY_CLIENT_SECRET);BoxOAuthManager mgr = client.getOAuthManager();
// This is refresh
BoxOAuthRequestObject requestObject = BoxOAuthRequestObject.refreshOAuthRequestObject(REFRESH_TOKEN, MY_CLIENT_ID, MY_CLIENT_SECRET);
BoxOAuthToken newToken = mgr.refreshOAuth(requestObject);
client.authenticate(newToken);
Yes, you can re-use the access token within the 3600-second period. A common pattern for web applications is to store the access_token and refresh_token (and optionally their expiration datetimes) in a database record associated with the user.
what is the recommended method of client authentication using the existing access token?
You'll use the same authentication method as when you first acquired the access token. You don't have to do anything special to reuse it. If the access_token is expired, as determined by either an expiration timestamp comparison or 401 response, you can use the refresh_token to get a new token pair. By refreshing and persisting the token pair in this manner you can keep the user authenticated indefinitely.
BoxOAuthToken accessToken = new BoxOAuthToken(Map) will work here.
// where Map contains
{
"exprires_in":"3600",
"token_type":"bearer",
"refresh_token":"<refresh_token>",
"access_token":"<access_token>"
}
Map authMap;
BoxOAuthToken accessToken = new BoxOAuthToken(authMap);
client.authenticate(newToken);