PHP Token Authentication - Expiration - php

I have a hybrid SPA php web application that makes calls to a remote REST API for all it's needs. I'm starting to implement token authentication between the web server and api and I'm not quite sure how to handle expiration of the token. There may be some flaws in my design as well.
User submits login credentials (username & password) to the web server.
Web server sends call to the API.
API looks up creds., if good, a JWT Auth token is generated and returned to the web server where the Token is stored in a php session variable. The token is never made public.
Each call the web server makes to the api sends a request with an authorization header that includes the token pulled from the session.
My problem is, what's the best way to issue a new token if one has expired during an incoming request. The api checks each request's token to determine if it's valid and if it's expired. If the request API was GET foo/bar for example, expecting a JSON string in return, but the token has expired, what would be the expected behavior?
Hope this makes sense. Please let me know if I'm not clear enough. Have not had much luck researching this particular scenario.

Related

How to secure api end point in php slim framework

I have already created an api using php slim framework. But I have an issue with securing my api. I want to access only api for the authenticated users only.
I have already added user login to my front end angular project. That is fine. But when the someone directly calls the api endpoint its show the result related to that endpoint.
For example. I have the following endpoint.
slimapi/customers/view
This endpoint shows all the data in the customer's table.
When someone types this URL in the browser. it shows all data related to that api endpoint. but I want to show some customers message when someone tries to access my api endpoint without using front end application.
You can Manage JWT Token
when client sends you login request and if login request and credential matched then you give the client a token. Then After every request, you check the token is it valid then you give the access.
just see the documentation of JWT
https://github.com/tuupola/slim-jwt-auth
You could use the OpenID Connect protocol (based on OAuth 2 and JSON Web Tokens​).
But this would maybe an overkill for the most scenarios, because a JWT would only makes sense if you have to scale the "session" over multiple servers and/or load balancers in the back-end infrastructure. Also a simple logout is not possible with JWT based tokens. If you start to manage JWT blacklists on the server-side, the API will not be stateless anymore.
I think a very long API-Token within the HTTP header, e.g. a UUID, would be secure and good enough in the most cases.
The HTTP Authorization request header contains the credentials to authenticate a user agent with a server, usually after the server has responded with a 401 Unauthorized status and the WWW-Authenticate header.
Syntax:
Authorization: <type> <credentials>
Basic Auth
Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
Token based
Authorization: Bearer eyJhbGciOiJIUzI1NiIXVCJ9...TJVA95OrM7E20RMHrHDcEfxjoYZgeFONFh7HgQ
UUID as Token
Authorization: Bearer bb79dfb5-17fd-4ebc-acd5-548e308e5f9a
Also make sure, that all API request are SSL (HTTPS) encrypted.
PS: If you just want secure your API for a web application, a classic Session with Cookies is also good enough and very secure.

Quickbooks online API with oauth2

I need to use Quickbooks online API to synchronize data between my system and my client's accounts on quickbooks.
I need to know if is it possible to complete the oauth2 authorization flow and make API calls without human interaction (without the need to interact with Intuit's authentication and authorization windows)?
I read the Intuit's docs on: https://developer.intuit.com/docs/0100_quickbooks_online/0100_essentials/000500_authentication_and_authorization/connect_from_within_your_app
On the first step, I made a GET request to:
https://appcenter.intuit.com/connect/oauth2?client_id=MY_ID&scope=com.intuit.quickbooks.accounting&redirect_uri=https%3A%2F%2FMY_NGROK_URL.ngrok.io%2FOAuth2PHPExample.php&response_type=code&state=RandomState#/Authorize/COMPANY_ID
Then, the Intuit's authentication and authorization windows opens and I need to put my username and password and then, click in the authorize button to get the authorization code.
Is there a way to obtain the authorization code without authenticate and authorize?
I need to automate this task to make API calls in the backend with PHP.
Thanks,
Marcelo.
Is there a way to obtain the authorization code without authenticate and authorize?
No... but read below.
I need to automate this task to make API calls in the backend with PHP.
You are misunderstanding how OAuth (either 1 or 2) works.
The very first time you connect you will be prompted to authenticate/authorize access to the QuickBooks Online data.
You are then given a refresh token (or access token depending on if you're using OAuth2 vs. OAuth1).
You then store that refresh token (or access token for OAuth1) and can use that token going forward to make your requests, unattended, without requiring the user to be involved at all.
Key take-away: You only need the user involved the VERY FIRST TIME you connect, and then never again.

How to manage session for a user logged in from mobile app in PHP?

I'm a PHP programmer by profession. So, I don't have any idea about iOS and Android coding.
The scenario is there is one website developed using a Social Networking PHP software titled "PHPFox".
Now there are two similar mobile apps which exactly replicates the functionality of this website. One mobile app is in iOS and another is in Android.
So, I've written a set of RESTful APIs where I'm accepting the request from mobile app, parse the request, pass the request parameters to the function which does the same job for website, get the response from this function, convert it into JSON format and sent it back to mobile app. For iOS and Android app I'm using the same set of REST API files.
When user logs in, the REST API for login gets called. Eventually the PHPFox function for authentication gets called, a security token is generated along with some other user data. With every login the different security token is generated by PHPFox. This data is set into the session. Now every time I call any of the functions through any REST API file the security token generated at the time of login is verified and only upon successful verification of token the PHPFox function gets called. This verification process is done internally by PHPFox. So no need to pass the security token explicitly or implicitly to any REST API call.
Till now everything works absolutely fine.
My doubt starts from here. I don't know whether the session is maintained in iOS/Android app. So, if session on server i.e. PHPFox gets timed out then what will happen to the app? Will it crash? Will the user have to login again? If user kills the app on the device and again comes to the app, does he/she have to do the login process again?
There are too many doubts in my mind. I get totally confused with these things.
Can someone please put more focus on the issue I'm facing? It would be really great if you could explain in detail.
Thanks.
REST is sessionless for its nature. You need to generate a token when user logged in. You must save this token on your mobile client.
For every request, you need to attach a valid token in request header and check it at server side.
If token expires, the token stored on a client is not valid. So, you need to login again because of 401 response. If token it's not correct you need to responde 400.
I hope that I'm helpful for you.
Unlike web browsers, iOS and android apps cannot maintain sessions. Usually, once a user has logged in (login credentials verified from server), its login credentials are saved on client side. Then the app gets data from server using session less REST api calls. This is how mostly it is done in mobile applications.
However, if you want the server session and mobile app go hand in hand (which i don't think is a good idea), the way is
1) When the user logs in, a security token is generated on the server side and saved on both server and client side.
2) The mobile app will be able to communicate with the server as long as the security token is valid.
3) When the session expires, the security token becomes invalid. Now there must be an understanding between server and client about the response when the session is expired. Now the mobile app must redirect the user to login page again. The user will login again and then communicate with the server. This should happen every time the session is expired.
If your are using Oauth 2 for athentication, here is the common setup:
User logs in on mobile app
If the credentials are ok, the server returns the access token, a refresh token and the token's lifetime
The mobile app stores those values + current timestamp
On the server's side, a garbage collector is configured to clear expired tokens
Before making any api call, the mobile app checks if the token is about to expire (with the help of the stored values). If the token is about to expire, the app sends the refresh token which instructs the server to generate a new access token
If you want users to stay connected, the app can be configured to check the access token periodically and request a new one if it's stale
Hope this helps.
Cheers
Your server should be completely stateless, and so no session should be stored.. a REST API is effectively just a data abstraction layer with optional security (through token)
So you API expose an authentication service, which will respond with an Authorization token to be used on subsequent requests as a header, this token should be a 1to1 relation with each user, and Universally Unique. It should also have an expire time, at which point your server responds with appropriate error response requesting your app to refresh the token, which can be done either via a separate refresh token system, or requesting that the user logs in again to refresh the token.
It is the APP which should maintain the state, not the server. The server is merely there for data purposes, and so should not rely on any kind of session based authentication.
A session is "something" that lives on the server. It can be an object storing details about the user (for instance session id, username, email address...) or any other data that will be required to process future requests (such as shopping cart details, delivery address...).
That "something" is typically an object, which can be stored in memory, in a database or even serialized and saved to the file system (I believe this is the default in PHP).
So when you say "I don't know whether the session is maintained in iOS/Android app", I'm afraid that doesn't make sense. Only the server can maintain sessions.
Typically, the only thing that the client would know (web browser or mobile app) is the session id (in the form of a token or GUID). That is the only thing the client/app needs to remember and it needs to be sent alongside any request to the server.
It could be stored as a cookie and/or sent to the server as a request header.
Then the server will read the session id/token from the cookies or header and will retrieve the session details from the place where it stores sessions (file system, memory or database). That is what happens behind the scene when you call session_start().
To read more about session handling and how to create custom session handler (which might be required in your case to get a token from the request headers):
http://php.net/manual/en/function.session-start.php
You should not worry about the session from the mobile development side.in Android we use SharedPrefrence and NSUserDefaults (Flag which maintains the session locally).
I dont have any experience working with PHPFox but this is how a mobile frontend should ideally handle the issues:
Case 1: Mobile app actively talking to server:
Session timeout stamp keeps bumping up and session stays alive.
Case 2: Mobile app active without any server communication (e.g. incoming phone call, moving between apps etc.):
Server session may or may not timeout.
If it times out, next query to server will fail auth and return an error.
App consumes this error and gracefully redirects to login screen with a message toast urging the user to login.
(This happens in my banking app)
Case 3: User kills the app on device and relaunches it:
The app should store the token either in sqllite or shared preferences. (Always logged in apps take this approach)
Upon relaunch, app can query the server with the presistent token.
If session is alive, communication goes through and user can
continue. If not, user goes to login screen as in Case 2.

Does OAuth2 verify the request domain via http headers?

I am currently learning about OAuth2, and I am slightly confused about one part of it. Does the OAuth2 server compare the domain in the JWT with the domain in the request header?
What prevents someone from ripping a bearer token out of a JS app and then using it to make fraudulent API requests? Even if HTTPS is used, the token sent back from OAuth2 still has to be stored before it can be used in subsequent requests, thus making it vulnerable. What am I missing?
Edit: what if I create an oauth2 token from a non-browser client and there is no domain name to match against?
Nothing prevents it from being used. That's why you store it safely or you don't store it at all.

Server-side Twitter client possible with OAUTH?

Twitter'll phase out HTTP basic authentication by August 2010. In the link my scenarios are from Desktop Applications. Basically my client should tweet new posts on a website.
This would be incredibly simple with HTTP basic auth, because I can store and use my account's username and password in the app to authenticate.
However, with OAUTH I can get final credentials by two means:
Callback method. You are redirected to Twitter, (login if isn't), click allow access, get redirection back to your callback URL.
PIN mode. You get a link to open, (login if isn't), click allow access, receive PIN code. Use this PIN code to authenticate your app.
Do I understand correctly that PIN codes also expire? How is it possible, given a username and password just to tweet from a client application? How can a server side script log in with the username/password and click allow access? All scenarios I could google up are for a web application to authenticate via twitter where the user is in front of the browser to walk through the redirect.
All scenarios I could google up are for a web application to authenticate via twitter where the user is in front of the browser to walk through the redirect.
The user has to be there to authorise you the first time (just as they'd have to provide you a username and password), but the resulting access token does not expire and can be reused (unless the user deauthorises your application, that is).
Store the access token - it's as good as a username/password. Better, actually - if they change their password, your access remains.
The PIN does expire under OAuth 1.0a. Using the verification code returned requires use of the temporary request token in the initial authorization request.
OAuth 2.0 defines more flows - one of which uses a direct login/password mechanism. It's up to Twitter to determine which flows they decide to implement. You can also embed a user-agent in the app.
Desktop apps suffered from a really bad user-experience with OAuth 1.0 which led to 2.0. It's doable, but painful. You can request XAuth access if you need to from Twitter as well. It's almost the same as basic auth.

Categories