Yammer authentication - check if token is valid - javascript

I'm using Yammer JS SDK to authenticate users to access some web service. I'm using JS SDK to obtain a token and I store it in session. Current flow is following (may be wrong, correct me, if necessary):
User accesses any page, PHP is checking for token stored in session vars. If not - user is redirected to login page
Using Yammer SDK I'm getting an access token and save it to session vars (POSTing it to our server side login service) and render the requested page.
Problem so far - I can't find any way in Yammer API to check if the access token stored\passed to my web service is actually the right thing. Which means, that potentially anyone can generate some random gibberish data, use that as a token and view content - the rest of Yammer functionality will be broken, but content will be visible.
The smartest way I thought of so far is to try and get some client info from Yammer REST API using the token and if response is invalid - delete the session stored token.
How do I do that the proper way?

Checking for HTTP status code 401 Unauthorized Access on a request is the only way I know of to determine if your Token is valid. There are a couple instances where you will get a 401 back with a valid token, but this is pretty rare.

Related

Not Getting refresh token as a part of response after the Auth 2.0 Login Authorization code for google actions

Google actions AuthO 2.0 not getting refresh token
After successful login with my web application i get the access token in response.
where can i get the refresh token on actions-on-google side?
The Flow is Authorization_Code and not implicit.
After successful user authentication, in the first response where can i see the refresh token?
Is it possible to get the refresh token?
I am asking the user to signIn if access token is not present.How can i get the refresh token as a part of the code response, if it's a part of http response, how can you access it when GET request is done by googl-actions in background.
if (isNullOrUndefined(conv.user.access.token))
{
conv.ask(new SignIn('To get your account details'));
}
Google requires that you provide the special parameter access_type=offline if you need a refresh token. You need to include that in the authorization URL to receive a refresh token.
Google's Refresh Token docs:
If you are not using a client library, you need to set the access_type HTTP query parameter to offline when redirecting the user to Google's OAuth 2.0 server. In that case, Google's authorization server returns a refresh token when you exchange an authorization code for an access token. Then, if the access token expires (or at any other time), you can use a refresh token to obtain a new access token.
Note that Google will not issue refresh tokens for users that have already authorized an application unless you also include the prompt=consent parameter, forcing the user to affirmatively re-consent to the application's access.

How to generate access token(for future use) for Google APIs using JavaScript?

I want to fetch the data(Pageview, Session, Users and all) from Google analytics and show it on another website but my problem is that I don't know how to get access token using JavaScript.
I referred some Google docs for getting access token Query Explorer, OAuth 2.0 Playground but this access token is expired in 60 minute and I want to save this access token for future use(long live access token). Anyone know about how to get access token using js or how to get refresh token for using future use.
Whenever I used expired access token and fire the API so I got this error:
{"error":{"errors":[{"domain":"global","reason":"authError","message":"Invalid Credentials","locationType":"header","location":"Authorization"}],"code":401,"message":"Invalid Credentials"}}
And my Google analytics API which is generated by Query Explorer included access_token.
https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A123456&start-date=2016-10-21&end-date=2016-11-20&metrics=ga%3Asessions%2Cga%3Apageviews&dimensions=ga%3AlandingPagePath&start-index=3&max-results=1&access_token=za29.aaaaaaaaabbbbbbbbbccccccccdddddddmmvermrm
Access tokens are only good for 60 minutes.
What you are looking for is a Refresh Token. Refresh tokens are used are good as long as they are valid. They can be used to request a new access token from the server at anytime.
Answer: It is not possible to extend the time that an access token is good for. It is not possible to get a refresh token with JavaScript. This is probably for security reasons.
Option: Switch to a server sided programing language if you want to get a refresh token. If this is your own personal account and you wont be accessing user data I would recommend you looking into service accounts instead. You will need to use a server sided language for service accounts as well.

Handling JWT expiration and JWT payload update

I have a Koa based Node.js backend for my personal/hobby application.
I implemented session handling with JWT tokens. The client (AngularJS) gets the token after a successful login and stores the token somewhere (currently in sessionStorage but for the purposes of this question it shouldn't matter).
I have two questions:
When I need to update the user record which the JWT represents, say, the user turned on Two-factor authentication (2FA) so I asked him to provide his phone number and I'd like to set this phone number in the user's record. Currently, after a successful verification on the phone number I call my backend to update the user record and I create a new JWT token with the updated user record (I exclude sensitive information from the JWT token like the hashed password, but I'd like to include the phone number for client side usage). Is it okay to create a new token when some of the credentials change and update the existing client side token with this new token? Should I never-ever create another token, only to create the one and only upon successful authentication? How do I then update the payload in the token?
How should I handle expired JWT tokens? In my mind I have 3 (possible) scenarios:
2.1. The JWT is set to short living, say 15 minutes. If the backend server replies with a 401 Unauthenticated 'Invalid token' (I guess this is the default behavior of koa-jwt) then I automatically log-out my client and require re-authentication. But I also set up a complementary middleware, which is the last in the chain on the backend to re-create the token with a refreshed expiry and the client would also replace the existing token with the refreshed one. So if the user is active and uses the application every protected API call, in case of success, would create a new token to replace the old token.
2.2. The JWT is set long-living, say 1 week, and if it expires I opt-in re-authentication from the client.
2.3. Copy https://www.rfc-editor.org/rfc/rfc6749#section-1.5. Here when creating the JWT token after a successful authentication we send an access_token as well as a refresh_token. When the access_token is expired and the server responds with HTTP 401 'invalid token' (koa-jwt default) then the client sends the refresh_token to the backend to require a new access_token (and optionally a new refresh_token). In this case I don't fully understand how the refresh_token is verified against the old access_token to provide a new token? Or why do we need to have a refresh_token?
Any generic advice on the upper topics (JWT updates and JWT expiration) would be helpful.
Starting from the bottom, I would ignore refresh tokens as I don't think they will help you here. They are generally aimed at other scenarios where the client application can provide storage more secure than the user browser -- think native mobile applications or server-side web applications.
Refresh Tokens are long-lived. This means when a client gets one from a server, this token must be stored securely to keep it from being used by potential attackers, for this reason it is not safe to store them in the browser.
(emphasis is mine; source refresh tokens)
This means that option 2.3 is basically the same as 2.2, which is not a bad option. It's not uncommon to have web applications with long session duration. If your application is not highly sensitive it's acceptable to use long session to improve user experience. For example, Django uses a default of two weeks for the age of its session cookie. See SESSION_COOKIE_AGE.
The remaining option (2.1), is usually referred as sliding session. The session timeout is short, but as long as the user keeps using the application within that interval the session gets automatically renewed. This is possibly the most common approach, or at least the one I used most time, so I'm biased. The only thing I would note is that sliding session are usually implemented with opaque session identifiers stored client-side as cookies and then with the actual session data stored on the server.
Your approach is a bit different because you have a stateless JWT token (it contains actual user data) stored on browser local storage. Like you said, in order to update the token you'll have to generate a new one, because you'll have to generate a new signature.
The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn’t changed in the way.
(emphasis is mine; source JSON web tokens)
Having said all that, I would consider the following:
Ask yourself if you really need JWT's or if regular session identifiers stored as cookies (HTTP Only) would simplify your logic.
If JWT's are a requirement, for example, you have another API that will also accept these tokens as authentications, then I would consider option 2.1 or 2.2 as refresh tokens for a browser-based application are not recommended.
Having said that, you should also consider that JWT's are not huge, but they will still be an overhead if you decide to be automatically renewing. You may mitigate this a little by choosing a session duration of 20 minutes and only perform automatic renewal after half the session has elapsed.
Another point is that a vulnerability like XSS in your application will expose the access token to an attacker as the injected scripts would be able to read from localStorage/sessionStorage, this can be another point in favor of HTTP only session cookie storage.
I would like to answer your second question before I can get on to the first one.
Basically the third option which you have mentioned is the best way to renew your access tokens. Access token should be short living(~5mins) and refresh token has longer life. When your access token gets expired, send your refresh token to the backend and get a new access token. So your response should be something like this:
{
"token_type":"bearer",
"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiVlx1MDAxNcKbwoNUwoonbFPCu8KhwrYiLCJpYXQiOjE0NDQyNjI4NjYsImV4cCI6MTQ0NDI2Mjg4Nn0.Dww7TC-d0teDAgsmKHw7bhF2THNichsE6rVJq9xu_2s",
"expires_in":10,
"refresh_token":"7fd15938c823cf58e78019bea2af142f9449696b"
}
So the idea is to seperate your application into Authorization Server (which generates access token / refresh token) & Resource Server (validate access token and access the resources ). You can maintain a schema to validate the refresh token against the access token in Authorization Server. Please refer to the schema section mentioned in this link which might give you some idea. Oauth2. You can modify the schema according to your need. You need not send your refresh token along with your access token for each request call. Refresh token can only be sent to Authorization server for generating new access token. How to generate refresh tokens? If I am using Java, I would use UUID.randomUUID() to generate a unique refresh token.
Now to answer your first question, if you want to update your JWT payload based on your updated user records, then you can use the same refresh token to generate a new access token with the updated payload. The logic remains same because if phone number exists in the user record it gets added to the payload and if not, it will be null in the payload.
The main advantage of using Refresh token is that the Access Tokens can be renewed at any time using Refresh Tokens

JWT Refresh token using Sails JS

I have read a lot of posts but nothing really helped.
I am using a simple auth approach: user logs in, backend checks if its a valid user and gives back an access token using JWT. Now I want to implement a refresh token. How would that be? What should be the content of the refresh token? When I sign a new access token, what should I do to also sign a refresh token and send both of them? When I get an expired access token, how do I verify the refresh token in order to send two new tokens?
Im using Sails JS in the backend, so it would be perfect to have an example with that
Well, my implementation was to create another different jwtSignature, with a different secret, and that would be my refresh token on the backend. I know it's not too fancy, but it does the work for now.

Facebook Insights API - Retrieve data without being logged in

I'm trying to programmatically fetch Insights data from the Facebook Pages that I am the admin of. Using the access token generated by the Graph API explorer, I can access the insights data for every page no problem.
However, this only works if I'm logged into Facebook; otherwise I receive the message "Error validating access token: The session is invalid because the user logged out". Is there a way to access this data without being logged in? Should I log myself in using the Javascript SDK before every API call?
Is there a better way than this to retrieve insight data from the pages that I manage?
You should use a Page Token to access Insights data from Facebook Pages. An Extended Page Token is valid forever, you just need to store it on your server for future usage.
Basically, you just need to extend the User Token and request a Page Token with that Extended User Token with /me/accounts.
Here are some links explaining how to generate an Extended Page Token:
https://developers.facebook.com/docs/facebook-login/access-tokens/
http://www.devils-heaven.com/facebook-access-tokens/
http://www.devils-heaven.com/extended-page-access-tokens-curl/
Automatic post to my facebook page from Node.js server

Categories