I want to increase the token expire time to 24hrs. Is this right way to do that?
I am getting 1 hour expire time limit by default.
const generateToken = (config) => { return new AccessToken(config.accountSid, config.apiKey, config.apiSecret,{ttl:86400}); };
Related
So I set up the youtube data api and I added following code to fetch 4 videos on my page: Works fine for like 3 hours before the daily quota of 10.000 is reached. I tested it locally and everything worked fine there. Also: I´m using the search resource and its list method, which result in a quota cost of 100 per call, but that normally shouldnt be a problem, because its a small page.Thx in advance.
const youtubeWrapper = document.querySelector(".youtube-playlist");
async function getFloVideoData(){
const response = await fetch("https://youtube.googleapis.com/youtube/v3/search?part=snippet&channelId=UC78M9ne3s4_XpcmPM4r0Xxw&maxResults=4&order=viewCount&key=myAPIkey");
const data = await response.json();
const {items} = data;
items.forEach((item) => {
youtubeWrapper.innerHTML += `<div class="video-container"><img src="${item.snippet.thumbnails.medium.url}"><p>${item.snippet.title}</p><p>${item.snippet.publishTime}</p></div>`;
});
)
}
setTimeout(getFloVideoData(),3600000); //call function every hour too limit API-Calls
Description:
I'm using cookie in mvc project to remember most recent download format selected by user. While creating cookie, I'm setting expiry date for that cookie. And when I try to get that cookie and expiry date of that cookie then I'm getting "1/1/0001" as expiry date always. I'm not getting the reason behind this. please help to reason behind this.
Code:
1) Setting cookie and it's expiry date:
Response.Cookies.Add(new HttpCookie(base.LoggedOnUser.Email, exportFileFormat.ToString()));
var requestCookie = Request.Cookies[base.LoggedOnUser.Email];
if (requestCookie != null)
{
requestCookie.Expires = DateTime.UtcNow.AddDays(Convert.ToInt32(ConfigurationManager.AppSettings["FileFormatTypeCookieExpiry"]));
}
2) Getting cookie and it's expiry date:
var fileFormatTypeCookie = HttpContext.Current.Request.Cookies[CurrentUser.Email];
if (fileFormatTypeCookie != null && fileFormatTypeCookie.Value != null)
{
var exportFileFormat = fileFormatTypeCookie.Value;
var expiry = fileFormatTypeCookie.Expires;
}
Above variable expiry is always "1/1/0001".
I quote the answer from MikeSmithDev from a possible duplicate question:
Why is the cookie expiration date not surviving across sessions in ASP.NET?
The Short Answer - You cannot read the cookie's expiration date and
time.
Slightly Longer Answer - This is not an issue of sessions in ASP.NET.
It is an issue of what you can read from a cookie server-side in
ASP.NET. Per the MSDN:
The browser is responsible for managing cookies, and the cookie's
expiration time and date help the browser manage its store of cookies.
Therefore, although you can read the name and value of a cookie, you
cannot read the cookie's expiration date and time. When the browser
sends cookie information to the server, the browser does not include
the expiration information. (The cookie's Expires property always
returns a date-time value of zero.)
You can read the Expires property of a cookie that you have set in the
HttpResponse object, before the cookie has been sent to the browser.
However, you cannot get the expiration back in the HttpRequest object.
So basically, the cookie expiration date is set correctly. This can be
verified by inspecting the cookie in the browser. Unfortunately,
reading this cookie like in your Get function will return 1/1/0001.
If you really want to get the expiration, then you'd have to store it
in the cookie itself:
Set
DateTime exp = DateTime.Now.AddDays(1);
HttpCookie PreferredCookie = new HttpCookie("PreferredCookie");
PreferredCookie.Values.Add("cookieType", "Zref");
PreferredCookie.Values.Add("exp", exp.ToString());
PreferredCookie.Expires = exp;
Response.Cookies.Set(PreferredCookie);
Get
HttpCookie PreferredCookie = Request.Cookies["PreferredCookie"];
if (PreferredCookie != null)
{
CookieLiteral.Text = "Value = " + PreferredCookie["cookieType"] + "<br>";
CookieLiteral.Text += "Expires = " + PreferredCookie["exp"];
}
else
{
CookieLiteral.Text = "No Cookie";
}
Using the Google API PHP Client with a service account, it returns an array like the following:
array (size=3)
'access_token' => string '...TOKEN...' (length=127)
'token_type' => string 'Bearer' (length=6)
'expires_in' => int 3600
Is it best practice to generate a new token every page request? It seems wasteful to do so when each token is valid for one hour. But since the token does not include a created value or a token_id value, the builtin isAccessTokenExpired() method will always return true, meaning it is always expired.
I see several options for reusing the same token:
Option 1: When token is created via fetchAccessTokenWithAssertion(), I can manually add a created value to the token array with time() as its value. Then save that to session/database so later when isAccessTokenExpired is called it will have that field to verify.
Option 2: Save token to session/database along with the timestamp the token will expire (time() + $token['expires_in']), and then on subsequent views I can do my own calculations to verify that the token is still in a valid time period. This seems a bit weird too though as I can't be fully sure that Google has not revoked the token or anything funny like that.
Option 3: Call a method that uses the access token and checks its response. If the call succeeded then the access token must be good still, if not then I can go ahead and ask for a new one. But what method could I call? One that would only need the most basic permissions would be good.
Thank you.
You can request a new token each time, but it's needless overhead and I believe it can eat into your API call quota as well.
I basically do #2, but I also subtract 10 seconds off of the expires_in just to be certain I don't have a request made with a just-expired token. TBH there's no reason that Google would revoke an individual token that wouldn't result in full revocation of all access, that's kind of why their token lifetime is so short to begin with.
I don't use the official API client, but the Cliff's Notes version of my logic is:
class Token {
public function __construct($info) {
$this->token = $info['access_token'];
$this->type = $info['token_type'];
$this->expiry = time() + $info['expires_in'] - 10;
}
public function isValid() {
return ($this->validFor()) > 0;
}
public function validFor() {
return $this->expiry - time();
}
}
class TokenFactory implements TokenFactoryInterface {
public function token($force_new=false) {
if( $force_new || !isset($this->token) || !$this->token->isValid() ) {
$this->token = $this->newToken();
}
return $this->token;
}
}
I'm using Mongodb to store users' data, including the user status (online|offline|busy). The expiry time is just a few seconds. If a user doesn't show up (send keepalive request) after a few seconds, I want to set the status to offline.
I'm looking for a scalable solution for this. I was thinking about adding 'lastseen' attribute and to run a cron job to update the statuses, but I think it's not scalable.
Is there a better way to do this? How can I use Redis or Memcashed to help me with this?
You can use a TTL collection. http://docs.mongodb.org/manual/tutorial/expire-data/
One technique that would work is to have a collection of sessions with a last_seen timestamp. The TTL collection would be configured to delete sessions once the last_seen timestamp was more than X seconds ago. As long as a session is online, you'd periodically refresh the last_seen timestamp to prevent it from being cleaned up.
Example:
Setup the TTL collection:
db.sessions.ensureIndex( { last_seen:1 },{ expireAfterSeconds: 60 } );
Ping to keep a session alive (or create it if it wasn't there already)
db.sessions.update( {_id: , last_seen: }, { upsert:true } );
Query to see if a user is online:
session = db.sessions.find( { _id: } )
if returns a document, then the user is online
if no document returns, then they are offline
I want to check the session expired or not.
SO what i decided is Create an action called IsServerExpired and have it return a json object containing a boolean value, and the redirect url.
SO the java script function will do an ajax request to this action with specified time interval ..
I have some basic questions ..
1.If i send an ajax request ,i think that will refresh the session time . So in effect the session will not expire if i am using this method. am i right ?
If it refreshes how can i check session expire using polling
There is more simple approach to log out user once session expired.
You can save SessionTimeout somewhere on the client side and run client side timer, once timer reach end redirect user to log out url.
Here is example. Model here containts SessionTimeout value.
$(document).ready(function () {
var timeOutInMinutes = #Model;
if(timeOutInMinutes > 0)
{
setTimeout(function() {
window.location =
'#Url.Action("Logout", "Authentication", new {area=""})';
},timeOutInMinutes * 1000 * 60);
}
});
More user friendly way is to show popup that will say that session will be expired wihtin one minute(if session timeout 15 mins then show it after 14 mins), so user will be able refresh page. and continue work.
I think you are confusing between an ASP.NET session and the authentication cookie. I suspect that you are talking about the authentication cookie expiration here. If you have set slidingExpiration to true in your web.config then polling AJAX requests will renew the timeout so they are not suitable. Phil Haack described a very elegant way to detect authentication cookie expiration in AJAX calls in this blog post.