Simple, secure API authentication system - json

I have a simple REST JSON API for other websites/apps to access some of my website's database (through a PHP gateway). Basically the service works like this: call example.com/fruit/orange, server returns JSON information about the orange. Here is the problem: I only want websites I permit to access this service. With a simple API key system, any website could quickly attain a key by copying the key from an authorized website's (potentially) client side code. I have looked at OAuth, but it seems a little complicated for what I am doing. Solutions?

You should use OAuth.
There are actually two OAuth specifications, the 3-legged version and the 2-legged version. The 3-legged version is the one that gets most of the attention, and it's not the one you want to use.
The good news is that the 2-legged version does exactly what you want, it allows an application to grant access to another via either a shared secret key (very similar to Amazon's Web Service model, you will use the HMAC-SHA1 signing method) or via a public/private key system (use signing method: RSA-SHA1). The bad news, is that it's not nearly as well supported yet as the 3-legged version yet, so you may have to do a bit more work than you otherwise might have to right now.
Basically, 2-legged OAuth just specifies a way to "sign" (compute a hash over) several fields which include the current date, a random number called "nonce," and the parameters of your request. This makes it very hard to impersonate requests to your web service.
OAuth is slowly but surely becoming an accepted standard for this kind of thing -- you'll be best off in the long run if you embrace it because people can then leverage the various libraries available for doing that.
It's more elaborate than you would initially want to get into - but the good news is that a lot of people have spent a lot of time on it so you know you haven't forgotten anything. A great example is that very recently Twitter found a gap in the OAuth security which the community is currently working on closing. If you'd invented your own system, you're having to figure out all this stuff on your own.
Good luck!
Chris

OAuth is not the solution here.
OAuth is when you have endusers and want 3rd party apps not to handle end user passwords. When to use OAuth:
http://blog.apigee.com/detail/when_to_use_oauth/
Go for simple api-key.
And take additional measures if there is a need for a more secure solution.
Here is some more info, http://blog.apigee.com/detail/do_you_need_api_keys_api_identity_vs._authorization/

If someone's client side code is compromised, they should get a new key. There's not much you can do if their code is exposed.
You can however, be more strict by requiring IP addresses of authorized servers to be registered in your system for the given key. This adds an extra step and may be overkill.
I'm not sure what you mean by using a "simple API key" but you should be using some kind of authentication that has private keys(known only to client and server), and then perform some kind of checksum algorithm on the data to ensure that the client is indeed who you think it is, and that the data has not been modified in transit. Amazon AWS is a great example of how to do this.
I think it may be a little strict to guarantee that code has not been compromised on your clients' side. I think it is reasonable to place responsibility on your clients for the security of their own data. Of course this assumes that an attacker can only mess up that client's account.
Perhaps you could keep a log of what ip requests are coming from for a particular account, and if a new ip comes along, flag the account, send an email to the client, and ask them to authorize that ip. I don't know maybe something like that could work.

Basically you have two options, either restrict access by IP or then have an API key, both options have their positive and negative sides.
Restriction by IP
This can be a handy way to restrict the access to you service. You can define exactly which 3rd party services will be allowed to access your service without enforcing them to implement any special authentication features. The problem with this method is however, that if the 3rd party service is written for example entirely in JavaScript, then the IP of the incoming request won't be the 3rd party service's server IP, but the user's IP, as the request is made by the user's browser and not the server. Using IP restriction will hence make it impossible to write client-driven applications and forces all the requests go through the server with proper access rights. Remember that IP addresses can also be spoofed.
API key
The advantage with API keys is that you do not have to maintain a list of known IPs, you do have to maintain a list of API keys, but it's easier to automatize their maintenance. Basically how this works is that you have two keys, for example a user id and a secret password. Each method request to your service should provide an authentication hash consisting of the request parameters, the user id and a hash of these values (where the secrect password is used as the hash salt). This way you can both authenticate and restrict access. The problem with this is, that once again, if the 3rd party service is written as client-driven (for example JavaScript or ActionScript), then anyone can parse out the user id and secret salt values from the code.
Basically, if you want to be sure that only the few services you've specifically defined will be allowed to access your service, then you only option is to use IP restriction and hence force them to route all requests via their servers. If you use an API key, you have no way to enforce this.

All of production of IP's security seems produces a giant bug to users before getting connected. Symbian 60s has the fullest capability to left an untraced, reliable and secure signal in the midst of multiple users(applying Opera Handler UI 6.5, Opera Mini v8 and 10) along with the coded UI's, +completely filled network set-up. Why restrict for other features when discoverable method of making faster link method is finally obtained. Keeping a more identified accounts, proper monitoring of that 'true account'-if they are on the track-compliance of paying bills and knowing if the users has an unexpired maintaining balance will create a more faster link of internet signal to popular/signatured mobile industry. Why making hard security features before getting them to the site, a visit to their accounts monthly may erase all of connectivity issues? All of the user of mobile should have no capability to 'get connected' if they have unpaid bills. Why not provide an 'ALL in One' -Registration/Application account, a programmed fixed with OS, (perhaps an e-mail account) instead with a 'monitoring capability' if they are paying or not (password issues concern-should be given to other department). And if 'not' turn-off their account exactly and their other link features. Each of them has their own interests to where to get hooked daily, if you'd locked/turn them off due to unpaid bills that may initiate them to re-subscribe and discipline them more to become a more responsible users and that may even expire an account if not maintained. Monthly monitoring or accessing of an identified 'true account' with collaboration to the network provider produces higher privacy instead of always asking for users 'name' and 'password', 'location', 'permissions' to view their data services. IP's marked already their first identity or 'finding the location of the users' so, it's seems unnessary to place it on browsers pre-searches, why not use 'Obtaining data' or 'Processing data.'

Related

Secure AND Stateless JWT Implementation

Background
I am attempting to implement token authentication with my web application using JSON Web tokens.
There are two things I am trying to maintain with whatever strategy I end up using: statelessness and security. However, from reading answers on this site and blog posts around the internet, there appears to be some folks who are convinced that these two properties are mutually exclusive.
There are some practical nuances that come into play when trying to maintain statelessness. I can think of the following list:
Invalidating compromised tokens on a per-user basis before their expiration date.
Allowing a user to log out of all of their "sessions" on all machines at once and having it take immediate effect.
Allowing a user to log out of the current "session" on their current machine and having it take immediate effect.
Making permission/role changes on a user record take immediate effect.
Current Strategy
If you utilize an "issued time" claim inside the JWT in conjunction with a "last modified" column in the database table representing user records, then I believe all of the points above can be handled gracefully.
When a web token comes in for authentication, you could query the database for the user record and:
if (token.issued_at < user.last_modified) then token_valid = false;
If you find out someone has compromised a user's account, then the user can change their password and the last_modified column can be updated, thus invalidating any previously issued tokens. This also takes care of the problem with permission/role changes not taking immediate effect.
Additionally, if the user requests an immediate log out of all devices then, you guessed it: update the last_modified column.
The final problem that this leaves is per-device log out. However, I believe this doesn't even require a trip to the server, let alone a trip to the database. Couldn't the sign out action just trigger some client-side event listener to delete the secure cookie holding the JWT?
Problems
First of all, are there any security flaws that you see in the approach above? How about a usability issue that I am missing?
Once that question is resolved, I'm really not fond of having to query the database each time someone makes an API request to a secure end point, but this is the only strategy that I can think of. Does anyone have any better ideas?
You have made a very good analysis of how some common needs break the stateleness of JWT. I can only propose some improvements on your current strategy
Current strategy
The drawback I see is that always is required a query to the database. And trivial modifications on user data could change last_modified and invalidate tokens.
An alternative is to maintain a token blacklist. Usually is assigned an ID to each token, but I think you can use the last_modified. As operations revocation of tokens probably are rare, you could keep a light blacklist (even cached in memory) with just userId, and last_modified.
You only need to set an entry after updating critical data on user (password, permissions, etc) and currentTime - maxExpiryTime < last_login_date. The entry can be discarded when currentTime - maxExpiryTime > last_modified (no more non-expired tokens sent).
Could not sign out the action just trigger some client-side event listener to delete the cookie secure holding the JWT?
If you are in the same browser with several open tabs, you can use the localStorage events to sync info between tabs to build a logout mechanism (or login / user changed). If you mean different browsers or devices, then a you would need to send some way of event from server to client. But it means maintain an active channel, for example a WebSocket, or sending a push message to a native mobile app
Are there any security flaws that you 'see in the above approach?
If you are using a cookie, note you need to set an additional protection against CSRF attacks. Also if you do not need to access cookie from client side, mark it as HttpOnly
How about a usability issue that i am missing?
You need to deal also with rotating tokens when the are close to expire.

oAuth 2 server side vs client side

I'm trying to wrap my head around oauth2 and am comparing the server and client side flows. To me the server side flow sounds much more simpler - the user authorizes once and then everything remains on the server (converting the code to an access token, requests to the remote api, etc).
So, why would someone want to use the client-side flow?
One possible answer to that might be to reduce server traffic. Does anyone have any evidence that client-side reduces a significant amount of traffic from the server?
I think that it would be unlikely for approvals and access token grants to make up any sort of significant fraction of a server's traffic load unless it's implemented in a very obscure way. One might use the client-side flow if the application is very javascript-centric and has no other reason to contact a web server specifically for its service. For example, you could imagine some browser extension written in javascript that uses OAuth 2 to request someone's favorite YouTube videos, Facebook friends, or some other data, and display it to the user in some fashion. It may not make sense to dedicate a web server for serving those grants if it would perform no other function for the application.

Best practices to store CreditCard information into DataBase

In my country the online payments are not an old thing, the first time i saw a web application taking payments directly to a local bank account was last year.
So, Im a newbie coding web payment system.
My question is, what are the best practices to store creditcard information into the database...
I have many ideas: encrypting the creditcard, database security restriction, etc.
What have you done?
DON'T DO IT
There is simply far too much risk involved, and you will typically need to be externally audited to ensure that you're complying with all the relevant local laws and security practises.
There are many third-party companies that do it for you that have already gone through all trouble of making sure their system is secure, that they comply with local laws and so on. An example in the US that I have used in the past is authorize.net. Some banks also have systems that you can hook into to store credit card data and process payments.
I realise the country you're in may not have as strict laws as the U.S., but in my opinion that's no excuse for rolling your own. When you're dealing with other people's money, the risk is just too much to warrant.
In 2020, use Stripe, and avoid storing payment information yourself.
HISTORICAL ANSWER:
For this, I recommend a comprehensive, layered approach.
First, storing credit card info should be an option.
Secondly, the data should be stored securely, using a strong form of encryption. I recommend AES with 256bit key size. Make sure when choosing your key, you use the entire keyspace (it's a rookie mistake to just use a randomly generated alphanumericsymbol string as a key).
Third, the AES key needs to be properly secured. Do not embed the value inside your code. If you are using windows, consider using DPAPI.
Fourth, you will want to setup database permissions so that applications and computers will have access on a need to know basis.
Fifth, secure the connection string to your database.
Sixth, ensure that any application that will have access to the credit card data, will properly secure it.
At miniumum follow the PA DSS (Payment Appliction Data Security Standard). More info can be found here:
https://www.pcisecuritystandards.org/security_standards/pa_dss.shtml
Also it would be wise to look at PCI DSS, which could be found here:
https://www.pcisecuritystandards.org/security_standards/pci_dss.shtml
You should avoid storing any credit card information due to the risks to you and to customers of doing so.
Encrypt encrypt encrypt. Don't decrypt if you don't absolutely have to - don't decrypt to show the last 4 digits. Don't decrypt to tell the user what their card was.
In fact, if you can, don't even keep the encrypted card numbers in the same physical server as the rest of the user information.
Authorize.net has a Customer Information Manager API that allows you to store customer information in their system. It costs $20/mo. as an add-on to your account.
I suggest you encrypt card numbers with a strong algorithm( similar AES) and a long secret key.
Then,keep your secret key in a secure place similar an external hard or optical disk.
When you need to secret key,use external hard.
If you are using a shared host, you have to store your secret key in an external device.
Strict your database
Define strict users for your database
Remove root user of your database if it is not needed.

Should I use SSL on all web pages or just some account pages?

My user account and login pages are SSL, but the rest of my site is not. What bebnefit is there to switching between the two as I am doing vs making the whole site SSL?
There is an overhead to using SSL, although in reality it may not cause a concern - as pointed out in this SO question.
You can minimise what overhead there is by only using SSL for those transactions where it adds value - i.e. where you want to ensure the confidentiality and integrity of the data in transit. In many cases this is only the case for username and password details, however there may be other transactions where you also want these features.
in general, once logged on, a session-id is passed between client and server. if this cookie is sent in clear text (as with non-ssl requests/responses), it can be sniffed and used to enter the user's account without having to log on (session hijacking attack). this is why google recently enabled 'always on https' for gmail.
Use ssl on pages where you ask user to submit his credit card number, for example. Don't overuse it without enought reasons.

Strategy for single sign on with legacy applications

I'm wondering what strategies people use for reduced sign on with legacy applications and how effective they have found them?
We have an ASP.Net based intranet and own a lot of the legacy applications, but not all. We also have BizTalk and are considering the use of it's SSO engine too.
A good compromise between effort/rework and the convenience of single sign on is to continue to maintain a list of users, privileges, roles etc in the legacy app. Make the changes necessary to automatically log the user into your application based on their user account (usually their Windows or network account).
I'm currently running a couple of applications that use this method of sign on, and it makes them seem more integrated even though they aren't.
Another advantage we've found is that it stops people from sharing passwords to legacy applications. They're much less likely to hand out an admin password that also gives others access to their email or payroll details!
Multiple identity storage per application?
Might not be a single sign on solution, but have you try looking into something that is more targetted solution like MS Identity Lifecycle Manager? It will simplify identity synchronization between applications and it's pluggable as well, meaning you can hook up your own code to do the synchronization between different system. So if you change the identity info (i.e. login info) in ILM portal, you can propagate those to the different systems. Same thing for provisioning and deprovisioning identity. Single point of entry.
I supposed you can use biztalk also for similar thing.
As for truly single sign on solution where you just logged in once and you don't have to login again to different applications. I've yet to find one.
I supposed if your legacy apps has a pluggable identity provider module, it's doable, meaning you can customize the login system to hook up to your single identity source of truth whatever that maybe.
We did two things with legacy accounts. (legacy web based apps)
We first mapped the legacy accounts to their system logon accounts (running in a Windows Active Directory).
A facade logon screen then was applied to over the top of the legacy apps (web based), this would request the AD logon, which would then reverse map to the legacy applications logon account and assign the appropriate rights to the user, using the legacy systems security model. The user received a token for the session which kept the doors open for them.
This gave us the benefit of not having to retrofit legacy apps (for example what would happen is app x only had numbers for ID, and the user uses a windows logon (alphanumeric), and also achieve a psuedo single signon from the client's perspective.
The other option that did make sense was at the new logon screen, it would check multiple repositories of security, so even if the user didn't decide to use their windows logon they could still logon with the legacy account name. Obviously this does have some side effects but can also help ease the transition pain end users sometimes feel moving between systems.
There are also programs like the Citrix XenApp Single Signon which take a totally different approach to the issue.
In addition to Jimmy's points about using ILM, this particular system does allow integration with the AD PCNS (Password Change Notification Service) service, that can be used with ILM (ILM "sees" the password change event and can publish it to other consuming applications / services) to at least ensure that as a user's password changes in one system, it gets reflected into others.