Query string JWT JSON Web Token Authentication in PHP Slim API - php

This is a question about the best way of implementing JWT in a Slim PHP API - I'm looking for some guidance from senior/experienced developers as to how to proceed.
I currently have an open API, where users can perform get requests with query parameters such as device and date-time range to pull data. I also have devices which are POSTing data, with no authentication. We're not in production yet, but obviously this is bad.
To tackle this, I've been looking at implementing stateless authentication on the GET requests in the first case, specifically using JWT. I initially thought about passing the JWT through as a query string, with options for resetting a token performed through the web front-end after a user has logged in. However, I can see this being bad for man-in-the-middle attacks and my token being exposed (if using plain http). If I was to make sure all get/post requests were performed as https requests, will this be sufficiently secure?
What seems to be the more secure way would be to pass the token through the header. But from what I understand about this, you'd need something like Postman to be able to send requests, which isn't really an option since my users want to access the data using their browser only.

It's pointless using http, https is a must otherwise everyone in between the user and your server will see the password the responses can even be cached.
The token can be stored in a secure cookie which the browser will automatically include with each request. (The Slim Middleware for JWT has this functionality built in). Check out many available libraries at https://jwt.io/
Adding the token to the query string isn't needed if you use cookies, I would not recommend adding tokens to the query string as they are to easily leaked.
(Users love copy&pasting URLs to each other, this would also leak the token)
Note: If you're not sure if JWT is right for you, check out: http://cryto.net/~joepie91/blog/2016/06/19/stop-using-jwt-for-sessions-part-2-why-your-solution-doesnt-work/

Related

Security PHP RESTful API

I'm starting to develop a simple PHP RESTful API. After reading some tutorials, one of the features about REST is that the
"... statelessness is key. Essentially, what this means is that the
necessary state to handle the request is contained within the request
itself, whether as part of the URI, query-string parameters, body, or
headers"
Therefore, it means that my PHP server won't need to have $_SESSION ? What kind of approach do you recommend ? Using a token (valid for a short limit of time) in the URL doesn't seem a bit unsecure?
For example www.myapi.com/1233asdd123/get_user/12.
Many thanks.
If you're a web developer of any sort, you'll have heard this sentence probably 1,000 times: "HTTP is a stateless protocol". This means that every session works with a token exchanged between the server and the client.
When you use PHP's built-in sessions, the server is actually doing exactly that, even if you don't realize it: it generates a session_id and passes it to the client. The client passes the session_id token back normally on a cookie; PHP allows including the session token also on the URL, as a GET parameter, but I personally recommend disabling that feature (disabled by default on PHP 5.3+).
In your case, yes, you won't be using PHP's sessions.
You create a table in your database storing all session tokens and the associated session.
Tokens should have a short lifespan (for example, 30 minutes) and should be refreshed frequently. Refreshes are important not only to extend the life of the session (every refresh gives you an extra 30 minutes or so), but also help fighting against thefts of the session key. In some REST servers we created, the session token lives for 30 minutes and users are given a new token on the first request made after 10 minutes the session started. When clients are sent a new token, the old one is invalidated immediately.
You could pass the token to the server in any way, but adding it as a GET parameter is not an ideal solution for two reasons: 1. GET parameters are often written in the access logs of the servers and 2. users often copy/paste URLs and share them, and that can expose their session token.
For API servers, the best approach is to include the session token in one of the headers of the HTTP request. For example, you could set your Authorization header: Authorization: SessionToken 123123123 where 123123123 is your token and SessionToken is a string to tell the server to use your authorization method (you're free to choose your own name, as long as it's not one of the default methods like Basic; be consistent, though!).
Security on API servers is normally obtained by using SSL. Basically, if you have an API server, you must protect it with HTTPS (SSL).
There are methods to achieve security also without using SSL, but they require signing each request and are really complicate to implement and to use - and the overhead they add is probably bigger than the one of SSL.
A very common practice is to use a key value inside the URL:
www.myapi.com?key=ABCD1234
It is not less/more secure than POSTing the string. SSL encryption ensures that the whole payload cannot be intercepted by a man-in-the-middle.
More info :
You also mentioned a temporary access (session token). It is common in systems to log in using credentials (like the solution above) and obtain a temporary session token in the response. The session token is then used instead of the login details to query the service. It reduces the exposition of credentials in case of interception, and if someone manages to steal the session token, it will be working only for a few minutes. Good to have although not a necessity.

Per-Request API key

I've been making a standardized JSON API for my company's website; I'd like to have a way of authenticating users to use the API while keeping the API as stateless as possible. My idea was the following:
The user logs in, the web service authenticates the user, and generates a random string that gets passed to the client, along with an expiration date. This is stored in a cookie, as well as an entry in the database.
For every API request, the web service checks the cookie string against the database entry. If it authenticates, the web service will generate a new string, replace the old string with the new one in the database and the cookie, then send back the requested information.
If the client sends a request and the cookie does not match the database entry, the string in the database is set to NULL and the client has to log in again and start the process from step 1.
If a request is sent after the expiration date, the string in the database is set to NULL and the user must log in again.
I want to cause as few disruptions as possible with my company's current setup as we slowly transition to newer technology. Is this method something that is commonly done? What kind of security issues would I be running into if I do it this way? Should I be using a different method?
Yes, this is a common scenario. What you are describing is a session cookie and is widely used.
You might want to read into Session Fixation techniques and ways to mitigate those.
But using a session is not really stateless. If you can provide keys (shared secrets) to your API consumers, you could also consider message signing to authenticate requests. Make sure you are using (H)MAC. Also make sure that you guard yourself from Replay Attacks.

PHP cookies and member security

I've created a forum which uses a PHP session when logged in to determine the user id, and cookies for log-term login.
I suppose I have two questions:
Is this the best/securest method?
Cookies can be added manually via the address bar with javascript, which is a huge security risk. Is there any way around this?
Thanks!
First, make sure you are using https and not http. This will keep your traffic from getting sniffed and exploited.
Secondly, generate as random a value as possible to use as a token in the cookie. This is how many of the big sites do their user tracking. Have a map of token to user on the server side that tracks the identities. Remember: Anything that comes from the client is untrusted and could be tampered with.
Third, use an HMAC to make tampering much more difficult. You don't want users being able to brute force other tokens.
EDIT:
You may find these other SO questions/answers helpful as you build this system:
Long details about creating and using tokens (doesn't necessarily have to be a REST service to be applicable): REST Web Service authentication token implementation
Creating good tokens (don't use microtime): Is using microtime() to generate password-reset tokens bad practice

How do I authenticate users with a site API?

I want to build an API for users to build applications that easily interact with a site, and I was wondering what the best way to authenticate users would be.
Taking a look at other API's a lot of them have the user send the username and password as a GET parameter over a HTTPS connection. Is this the best way to go about it? Or are there other methods that I should look into or consider?
I've seen OAuth been tossed around and it looks like a good solution, but just for a simple API is it overkill?
You can use API key's. Generate a unique hash tied to an account upon request. Then check that the key is a valid key. As long as the API doesn't have any major security issues with someone using someone else's key then Authorization isn't needed. If there is a problem with someone using someone else's key then Authentication would be justified.
This is usually achieved with cookies.
The client sends their username and password with a POST request to your API (do not use GET, that's insecure). If the credentials are acceptable, then generate a random, unique session key, store it on your side and send it in a cookie back to the client (see setcookie()).
When the client now makes further requests, they send the session key cookie with the request. Check $_COOKIE for the session key if it matches a stored key on your side; if yes, that means the user authenticated.
Take note that this minimal example is vulnerable to brute-force attacks trying to guess valid session keys. You need to log invalid keys that clients send in their cookies and block their IP address for some period of time to prevent this.
Username / password in a GET isn't a great way to do this because you're potentially exposing the whole user account for hijacking even if the API has more limited functionality than logging into the site. So it's good practice to separate concerns between Web-site login and API access.
I'm not sure which case you're in but:
If the users are business customers of somekind who are embedding some type of widget or code in another website then it's probably best to use an API key which is scoped to the referrer domain (much like Google Maps does).
If they are end-users who won't know anything about the API but are going to be using Apps built by third parties then oAuth is likely to be your best bet, otherwise your users might literally be giving their usernames/passwords to unknown third parties. It's more complex but likely to be worth it in the long run.
To get a bunch of this stuff out of the box you can use something like 3scale (http://www.3scale.net) and it'll handle most of it for you (disclaimer, I work there so adjust for bias!) or there are open source libraries for oAuth in most languages (in PHP Zend-OAuth component might do the job for you).

Protect HTTP request from being called by others

I have an Android application from which I want to upload some data to a database on my web server. As the MySql java library has a size of about 5 mb, I don't want to include it with the application.
So I'll make a HTTP request for a php script and send the data with the URL as parameters. How do I make sure that only I can call this? I don't want people to sniff up the URL and call it outside my application.
Thanks
Use a simple static token to identify the client is yourself or in an advance way, first authenticate with a username/password, generate a token and use this token for further transactions .This token can expire after some time.
option1: http://[your request url]&key=xyz
where xyz is known only to you
option 2: first ping server with username password and upon successful validation get a dynamic token [dKey], store it locally.
then for further requests.
http://[your request url]&key=dKey.
option 2 is the one normally being followed.
The short answer: you cannot prevent sniffing.
But you can make sniffer's life harder by implement a some sort of internal authentication, GET/POST predefined parameters (or dynamic, but calculated by algorithm you only know how) exchange, hidden header fields, etc.
But all this could also be sniffed/reverse engineered.
A possible Overkill Way would be using some sort of asymmetric private/public key encryption/signature. Such as RSA. Your app will only include public key, and sign the request data with it. And your server-side will have a secret private key, it will use it to check validity of client requests.
I know very little about android - but it's not really relevant to the question.
If you want to prevent someone from sniffing the URL (and authentication details?) then the only option is to use SSL. On the other hand if you merely want to prevent other people from accessing the URL, its simply a question of authentication. If you're not using SSL, then that means you need to use sessions and a challenge-based authentication to avoid people sniffing the traffic. You could do this via digest authentication or roll your own code.
C.

Categories