I am usig JWT to manage the user access to our API system. The problem I am facing is that the token is expiring after some few minutes. How can I make the JWT token expires in such a way that it only expires when user manually logs out.
Thanks.
Add 'exp' in an array as a second parameter for the 'attempt' method. This 'exp' is timestamp.
For example:
$token=JWTAuth::attempt(
['email'=>$email,'password'=>$password],
['exp' => Carbon::now()->addweek()->timestamp]
);
In laravel 5.3, i simply comment the line in config/jwt.php ie..,
// ttl => 60
and now the time-to-live not exist and token expiration is lifetime.
and for invalidate the token use this below code in logout() i.e, JWTAuth::invalidate(JWTAuth::getToken());
You need to store the expiration time for a token server side instead of inside the token. This means that you don't set the exp key in the token. You can for example store the jti with an expiration time in the database. When the token is then received for authentication you can validate the token and then check the last seen date of the token based on the jti stored in the database with the expected lifetime and current time. If the token is still valid you reset the last seen date of the jti to the current time.
Related
My testplan is as follows:
get token: requests to get access token
Setting a user defined variable to get the tokenGeneratedTime, let's say tokenGeneratedTime to ${__time(,)}
Check if token is expired(if controller) - {__jexl3((${__time(,)} - ${tokenGenerationTime}) > 3599000)}
if true, goes to get token sampler
if false, goes to subsequent requests
Some https requests
So if I run this test plan for the first time(only 1 iteration), request to get token is fired, the condition would be evaluated as false and the subsequent requests are fired. All is well and good. But as you can see, if I run the test plan again immediately(not iterating) for the second time, the get token(authorization) requests are fired again, which is not needed. I need to call the get token requests, only on expiry.
I'm thinking of setting a variable to false, if the token is not expired and putting the get token requests under an if controller. But how do I set a variable in if controller?
If you have any other ways of achieving this, please do suggest.
TIA
Use a flag to check the token expiry. e.g. isTokenExpired
Define the variable in the User Defiled Variables section and set the value to true. This will ensure token request is fired for the first time.
Add an IF Controller to the token request and check the condition ${tokenExpired}. Set the flag to false when a token is created successfully. vars.put("tokenExpired","false")
Add a JSR223 Postprocessor to the top level and check the response code 401 for the token expiry response. If the token is expired, set the flag isTokenExpired to true and redirect the thread to the next iteration immediately ctx.setTestLogicalAction(org.apache.jmeter.threads.JMeterContext.TestLogicalAction.START_NEXT_ITERATION_OF_THREAD .
String responseCode=prev.getResponseCode()
if (responseCode.equals("401")) {
log.info("Token is expired ")
vars.put("tokenExpired","true")
ctx.setTestLogicalAction(org.apache.jmeter.threads.JMeterContext.TestLogicalAction.START_NEXT_ITERATION_OF_THREAD )
}
if I run the test plan again immediately(not iterating)
If you run the test plan 2nd time it means that your tokenGenerationTime variable gets a new value of the current timestamp equal to the start time of 2nd execution.
If you want to be able to run your test plan 2nd time within 1 hour without firing the token generation request you can consider writing the tokenGenerationTime into a file using i.e. __StringToFile() function and read it from the file on 2nd and other test executions using __FileToString() function or if your logic is more complex you can go for __groovy() function and implement whatever you want there
More information on JMeter Functions concept: Apache JMeter Functions - An Introduction
Our system is authenticating users by following these validation steps on a token generated by the getUserIdentityTokenAsync() method.
These tokens are failing the following check
Current time is between the times specified in the nbf and exp claims. The nbf claim specifies the earliest time that the token is considered valid, and the exp claim specifies the expiration time for the token. It is recommended to allow for some variation in clock settings between servers.
Our logs show these tokens being invalid by several hours
Current Time: 2020-04-10 17:02:11 +0000,
Valid Start: 2020-04-09 14:46:31 +0000,
Valid End: 2020-04-09 23:16:31 +0000,
We are validating these times as such:
def timeframe_valid?
PAYLOAD_WIGGLE_TIME = 900
if #payload.present?
now = Time.now.to_i
payload_valid_start = #payload[:nbf] - PAYLOAD_VALID_WIGGLE_TIME
payload_valid_expire = #payload[:exp] + PAYLOAD_VALID_WIGGLE_TIME
if now < payload_valid_start || now > payload_valid_expire
# handle invalid token...
end
end
end
We are making a unique call to getUserIdentityTokenAsync before each api request. Since we are seeing such a large difference in the time window for a valid token and the time it is validated, my best guess is that users are leaving the add-in open for long periods of time without refreshing. For some reason, when they return, getUserIdentityTokenAsync is not returning a new token, but rather the old one that is already expired.
Is there any way to force getUserIdentityToken to issue a new token after one has long since expired without a hard refresh of the add-in?
I have problem to make my application is not logged out user on activity
I have code like the picture above
as we know, modify the cakephp session is able by that code
"timeout" values is used to set how long session will be expired in a minutes. and the "autoRegenerate" value is used to renew the timeout value
and the last is "cookieTimeout" is used to set how long activity allowed
the crux of my question is how to auto regenerated the cookieTimeout cakephp in core.php (like renew "timeout" value with "autoRegenerate" => true)
Thanks in advance
I have a webservice that stores an authenticated users token in the HttpRuntime.Cache to be used on all subsequent requests. The cached item has a sliding expiration on it of 24 hours.
Secondly I have a vb.net app that is pinging this webservice every 15 seconds. It gets authenticated once, then uses the cached token for all subsequent requests. My problem is that the application appears to lose authentication at random intervals of time less than the 24 hr sliding expiration. However with it getting pinged every 15 sec the authentication should never expire.
I am looking for a way to view the HttpRuntime.cache to try and determine if the problem is in the webservice security methods or within the vb.net app. Can I view the HttpRuntime.cache somehow?
The webservice is part of a web forms site that was built with asp.net 2.0 on a Windows Server 2008.
The name of my key's were unknown as they were system generated guid values with a username as the value. So in order to view a cache collection that was unknown I used a simple loop as follows.
Dim CacheEnum As IDictionaryEnumerator = Cache.GetEnumerator()
While CacheEnum.MoveNext()
Dim cacheItem As String = Server.HtmlEncode(CacheEnum.Entry.Key.ToString())
Dim cacheItem2 As String = Server.HtmlEncode(CacheEnum.Entry.Value.ToString())
Response.Write(cacheItem & ":" & cacheItem2 & "<br />")
End While
Hope this helps others.
First off, HttpRuntime.Cache would not be the best place to store user authentication information. You should instead use HttpContext.Current.Session to store such data. Technically the cache is allowed to "pop" things in it at its own will (whenever it decides to).
If you actually need to use the cache, you can check if your item is in the cache by simply doing:
HttpRuntime.Cache["Key"] == null
I have a ACL+auth driven app. Everything works fine but I discovered that user is logged out after a random period of time. After doing some research I discovered that the cookie set once doesn't change it's expiration date on page refresh. So it goes like this:
I set up manually expiration time to 1 minute (Security.level low (with some changes in cake/libs) and timeout 60)
19:00:00 - user loads the page - cookie is set up
19:00:05 - user logs in (cookie doesn't change the expiration date)
19:00:30 - page refresh (cookie doesn't change the expiration date)
19:00:55 - page refresh (cookie doesn't change the expiration date)
19:01:05 - page refresh - user is logged out... (cookie expired after 1 minute)
So the problem is the user gets logged out after 60 seconds from setting a cookie in instead of 60 seconds of inactivity. Does CakePHP deal with cookie files automatically? Or do I have to take care about it myself?
All I did is set up a cookie name in config/core.php and setup auth. I don't have any cookie handling function, but the cookie is created itself - correctly, just isn't updated
I had the same issue and countered it with the following code which is called on every page load and ajax call.
if(isset($_COOKIE[Configure::read("Session.cookie")])){
$session_delay = Configure::read("Session.timeout") * (Configure::read("Security.level") == "low" ? 1800 : 100);
setcookie(Configure::read("Session.cookie"), $_COOKIE[Configure::read("Session.cookie")], mktime() + $session_delay, "/");
}