Which is more better between basic auth and token auth as security perspective - rest

I am currently developing a RESTful API server, and I am choosing between using ID and password or using a token to authenticate a user.
Let me, explain my situation first. I need to include static authentication information to my library to communicate between a client and my server or provide it to a partnership company to communicate between their server and my server. And when I was researching other services which are in a similar situation as us, they are using token now (for example, Bugfender is using a token to specify a user).
However, what I think is that using ID and PW and using the token are the same or using ID and PW is better because there are two factors to compare it is correct or incorrect.
Is there any reason why other services are using a token?
Which one is better as a security perspective or is there a better way to do this?

I think, if you are going go use on your client fixed username/password, or some fixed token, then the level of the security is the same.
Username and password is not considered as multi-factor authentication. Multi factor means that you are authenticating someone by more than one of the factors:
What you know. This can be the combination of username and password, or some special token.
What you have. Might be some hardware that generates an additional one time password - Google authenticator app on your telephone, or SMS with OTP received with some time expiration.
What you are. This is for example your fingerprint or retina of the eye.
Where you are. This can be the IP address of the origin if it is applicable for your setup.
How you behave. What is your normal way of using the service.
etc.
Maybe not needed to mention that both - the token and the username/password combination have to be carried in an encrypted requests (I believe you are using HTTPS). Otherwise the client's identity can be stolen.
How are you going to provide the credentials to your client library? I thnk this is the most tricky part. If those credentials are saved as a configuration (or worse hard coded) on their server, is that storage secure enough? Who is going to have access to it. Can you avoid it?
What would happen if your partner company realize that the username/password is compromised? Can they change it easily themselves? Or how fast you can revoke the permissions of stolen credentials?
My advice is also to keep audit logs on your server, recording the activity of the client requests. Remember also the GDPR if you work with Europe servers, check for similar regulations in your country based on what you are going to audit log.

In case the credentials (ID and password) and the token are being transferred the same way (say: by a header in a REST request) over a TLS secured channel, the only difference lies in the entropy of the password VS entropy of the token. Since it is something for you to decide in both cases, there is no real difference from the security perspective.
NOTE: I don't count the ID as a secret, as it usually is something far easier to guess than a secret should be.
I'd go for a solution that is easier to implement and manage.
IMHO this would be HTTP basic authentication, as you usually get full support from your framework/web server with little danger of making security mistakes in authentication logic. You know, friends don't let friends write their own auth. ;)

Related

Best practices for token authentication in web apps?

I want to make a simple REST web app, where the user interact with the objects through links in an email. The links have a token that can be used to authenticate a user without a username and password, like the ones that are usually used to reset a password.
What are the best practices for such a login-less, token-based authentication system?
I am by no means a security expert.. but some of the points which come to mind are -
Lifetime - The token should expire after a set period of time. Indefinite access using the token certainly doesn't make sense.
Replay attacks - The mechanism should prevent replay attacks.. which means the token should be valid for not only a set period of time, but also fixed number of calls.. Ideally exactly 1. If this number is not exactly 1, then it opens another can of worms..
Unless, its a feature :( For example, by design, the user is expected to share link with others, and anyone with the link should be able to access the resource in question.
Authorization - Granularity of the access granted by the token. Is it black and white.. or is the token also associated with a fixed set of rights. For example - token X was issued for Read-Only access, vs token Y was issued, for same resource with R/W access.
Administration - User / Admin should be able to see and verify any currently active and issued tokens, and associated information (permissions granted / affected resource etc), and explicitly revoke them, if necessary.
Secure Communication - You should consider security of the medium through which the url with token will be sent to the user. i.e. in your scenario, do the users receive emails over secure channel (TLS / SSL)? Should the email itself be protected with DRM?
Man in the Middle / Leaks - Similarly, even though you are providing the url in email, and the user is not logging on using user name and password over SSL, the resource should still be accessed using the url with token over SSL. This will prevent any capturing of the tokens from url, by a man in the middle. You would also need to be very careful about when the users browser may use this url in places you didn't expect..
I can vaguely recall reading about a popular site being affected by their urls being used as Refer Url, when displaying ads on their website.. which means, the advertisers site would probably get the url with the token as Refer.
Generation - Choice of algorithm to generate the token - May seem pretty obvious, but the token should be extremely obscure and near impossible to guess or brute force. The tokens should never be reused and the algorithm should avoid collisions.
Server Side Security - The tokens should probably be treated with same security as you would secure users id and password. If your user database gets hacked, hackers should not get the users passwords and other sensitive information.. Similarly, if your user / resource / token database gets hacked, despite the expiration on the tokens, hackers should not be able to access the resources as users for x hours.
Point is, when the tokens are stored on server side, they should themselves be secured / encrypted.
On the same lines.. just like its bad practice to log information like passwords in log file (specially plain text), You'd also have to consider any place these urls may get logged (plain text) on your server.. For example web server logs. If only super admins should have access to user's database, then they should also be the only ones to be able to see these token.. Not your web server admin and not any hackers parsing the log file after the hack.
Auditing - If there will be a need for auditing, you'd need some mechanism in place to prove that while the user didn't log on to the system, they are indeed the ones who performed the action / operation in question. Would you want to track the ip address and other information along with the request which would help such auditing?
Consent - Do your users even consent to the use of such alternate means of authentication and authorization? Should this be an optional / opt in feature?
EDIT: I found a link to the referrer url problem I was recalling. Although it was in context of user information.
I agree to 10 points of Vikas however from security perspective I have to tell you few points that you must be careful.
I will try to keep as simple as possible. And here I simplify the technical stuff to your special case.
Firstly tokens are used to prevent Cross Site Request Forgery attacks (XSRF). Keep that in your mind. If there is a web platfrom without unique tokens on the forms then any attacker can force the user to make malicious requests.
If you simply try to authenticate the user with a token, this is pretty wrong. Because there must be no simple authentication process and you can not rely on token.
Here is how the login system works in official security documentations, im writing as I remember:
Identification: you have to identify the user firstly, that is generally done with username. YOu will know that there is a user exist in your system.
Authentication: Let's say you have already identified that user A want to login. So you mast authenticate the user A with something that you know and user A know. We call it password simply :) You cannot by pass this step with plain text methods. Passwords are generally encrypted in your db and also through all communication with secure certicates, check ssl.
Authorization: okay you made the authentication somehow, the user has a right to get Authorization. Let's say if the admin type user is logged in, he has differen rigts and if the normal user is logged in then she has regular rights.
Session control: finally you have to control the session with a secure way. Here generally in web applciations people use access tokens for all requests to be sure that the authorized user is aware of the request. As a platform owner you are responsible to secure everything until the session ends. If you don't satisfy the users with your security, then probably your platf is not going to survive longer.
Tokens have different lifetime to expire and different access rights.
Now let's look at what facebok like companies do with mobile aplications. For the mobile app they generate a unique access token which is alway alive. One shortcoming here is, if any attacker steal the mobile token generally she can do anything in the account anytime :) Anyway here our point is how they verify the users with those tokens; firstly the token is unique for that device. (Actually not exactly unique or not dependent on hardware, because if you clearly steal the necessary files from the device then you can use it on another phone). So with this unique access token which is generated with users password at their initial login on mobile app, they can login always automatically with that. And this method is a little similar to what you want to do. However pay attention that they don't authenticate the users with links or email code.
Verification is not an authentication, don't forget that. By sending e-mail you can verify the users if the emailed code is unique and valid for only 30 sec or 1 minute. I hope you got the point.
Here I suggest you to check single sign on across multiple domains, which is really interesting.
Single Sign On across multiple domains
Let's say you are logged in to google.com and then you visit the youtube.com Opps the youtube is already logged in? Yea, cool right, but exist for long time. They can authenticate users accross domains which use different cookies with a little and secure trick. You will read on the link.
If your service is not really confidential and if you want to make your users happy with easy login system. Here is two of my solutions which I love :)
1-) Ask users their email address: just directly send 4-6 digit code as e-mail. Ask user the enter/click on that. There will be no password at all, only unique code on each login.
2-) Let's say you need to verify the user with a stronger way than email. Then mobile phone :) Here trick is; you will not send the verification code to user, but they will send what you tell them to you.
Ask to user to send a SMS with a unique CODE to XXXXXX your number :) Connect your mobile operator with your web service and check whether the code is sent to you by the user :)
There is always a trade-off between security and simplicity, and also with complexity. You have to find the balance.
Don't try to make it simple if your security is going away.
Don't try to make it complex if it'll seem more secure.
Hope those informationn help you.

Rest application and authorization

I would like to build my own REST app.
I'm planning to use oAuth as a main auth approach.
The question is: Can I use login and password as client_id and client_secret (in terms oAuth spec) ?
I don't have any third side applications, companies, sites etc... which will authenteficate my users.
I have my own REST server and JS-application.
Whole site will be made in usual(RPC) approach, but some private part will be done as RESTfull service, with enough stand-alone JS application.
UPDATED: I'm not sure that I even need full oAuth support. It seems to me that I can ask login and password on https page and then generate some token. Later i could use it to check is this user authenticated already or not. But in this case this oAuth become almost the same what we have in web aplications. I do not need oAuth to athorize users ?
I'm not consider HTTP(s) authotization because i don't want to send evrytime user and password to server.
No.
One if the main reasons OAuth exists is to allow integrations without users compromising their usernames and passwords.
If you plan on using username and password, look into xAuth as an option if you still want to sign your requests. More info: https://dev.twitter.com/docs/oauth/xauth.
But you could likely just as well go for HTTP Basic Authentication. At least if you publish your API over SSL. More info: http://en.wikipedia.org/w/index.php?title=Basic_access_authentication
I think you might get a better answer on the security site. See, for example, this question.
In any case, you need to start with a detailed assessment of what attacks you are trying to prevent and what attacks are "acceptable.". For example, if you are using HTTPS then you can probably accept the remaining danger of a man-in-the-middle attack, because it would require forging an SSL certificate. It is harder to say in general if a replay attack is acceptable.
One reasonable solution would be to create a time-limited temporary token by having the user authenticate over HTTPS with the username and password, generating a secure token with an expiration date, and then sending that token and expiration date back to the client. For example, you can create a (reasonably) secure token by taking the SHA1 hash of a secret plus the user name plus the expiration timestamp. Then the client can include the token, the user name, and the authentication timestamp in future requests and you can validate it using your secret and your clock. These need not be sent as 3 parameters; they can be concatenated into one string user|timestamp|token.
Register your application with SLI. SLI grants a unique client ID and a client secret that enables your application to authenticate to the SLI API. You must also register the redirect URI of your application for use in authentication and authorization flows.
Enable your application with specific education organizations so that the application can be approved for use in those districts.
Configure and implement the appropriate OAuth 2.0 authentication and authorization flow in your application, which includes managing sessions and authorization timeouts.

Best practices for securing API credentials as part of an iPhone app

The apps that I build frequently have 'social media service' requirements; e.g.
Twitter
bit.ly
Facebook
For most of these services, I need to have an API key of some sort. I'm trying to work out the best way of including these API keys in the application binary. The desired level of security depends on the possible attacks that can be conducted by malicious attackers.
Twitter
I have an xAuth-enabled key and secret. Both need to be used by the iPhone app.
Fallout from attack
Malicious users could post twitter status updates masquerading as coming from my app. There is no twitter account to hijack and start posting status updates on.
bit.ly
I have a username, password and API key.
To login to the website and access analytics, the username and password are required.
To create links via the API, only the username and API key are required by my iPhone apps. The password will not be in the app in any form.
Fallout from attack
Malicious users could create links on my bit.ly account. They would need to do a separate attack to brute-force or otherwise gain the password to login to the account.
For both of those services, the potential for harm doesn't seem too great. But for other services, it could be much worse.
I can just define the API credentials as strings in the header or in-line in the code, but then it's vulnerable to someone using strings on the application to see what's in it.
I could then start doing silly concatenation / xor-ing in the code to recreate the API key in memory, and the attacker would have to do a bit more work to recover any keys in the binary. My concern with that is that I'm not a cryptographer and would create an embarrassingly weak form of obfuscation there.
What better suggestions do people have?
The attacker can just sniff your traffic and extract the secret from there. So any obfuscation is easily circumvented.
Even SSL won't help much, since you can intercept the networking API which receives the unencrypted data.
The secure way to solve this is create your own server, keep the secret stuff server side, and use your own server from your app, and the server then relays to the other webservice. This way the attacker never has access to the secret.
A good suggestion is not to worry about it. There are plenty of apps that store their API keys in plain text. The point is you need a lot of different bits of information to construct an access token.
As long as you're not storing username+password combos in plain text on the file system or transmitting them over the network without SSL/HTTPS etc then you're fine.

How do I implement authentication the restful way?

I'm building a picture diary on web application google app engine using python. Users can sign up and post pictures to their diary.
Also, I'm trying to conform as much as I can to the REST architecture of doing things.
The authentication scheme is based like this for the web application:
1. Post username/password from the frontend
2. Backend sets up a cookie if authentication is successful
3. The rest of the AJAX calls made are authenticated using this cookie.
Is there any way to conform to REST without using cookies ?
Now, I'm also building an android application where users can sign in and post/view their picture diary. I need to expose the data from web application's datastore so I'll be building a webservice to fetch data from the datastore.
The authentication scheme for the android client:
OPTION a
1. Post username/password over https to the web service
2. Web service returns a unique authorization token (store the token in the username/pwd table on the datastore)
3. Request subsequent services by adding this token to the Request Header of the request
4. Server maps the token to the username/pwd table and returns data if token is found
5. Authorization token expires after a certain period of time
OPTION b
1. Set up a secret key on the client and server side
2. Use "username:hash of password and secret key" in the authorization header of every request
3. server generates the password by extracting the password from the hash value using the same hash algorithm ; if successful returns data
btw, I didn't wanna use basic authorization because of its security vulnerabilities.
Which is better ?
Are there other significantly better ways to accomplish what I'm trying to do ? Security is quite a concern for me btw.
I'd appreciate if anyone has any insight into this issue. thanks.
I've been doing some research myself as to what would be the best solution. I think the 2-legged oauth might work in my case as Leonm suggested.
In this case the server has to provide the client with a consumer key/secret which in my case is hardcoded in the app.
The steps now would be:
1. Generate a signature using the oauth_parameters(consumer_key, signature_method, timestamp), request url, request parameters, and the SECRET.
2. Include the signature, oauth parameters when making a request.
3. Server verifies the request by generating the signature again except in this case it uses the SECRET that corresponds to the key
I think this way I am pretty much confirming to the REST principles. The server is statless as I far I understand now.
What are the pros/cons on doing things this way?
If "security is a concern" then I would say that you'd be a lot better off using open standards and a library to achieve what you want. The main reason for this is that if you do it yourself, you're very likely to forget something; these standards have had a lot of eyes looking at them, looking for holes.
Your options include (in increasing level of complexity)
Basic authentication and HTTPS
Everything is encrypted, which makes it impossible to compress or look into, it increases the overhead somewhat, using more horsepower on the server, and more perhaps battery power on the client. Simple to implement, since it's well supported by libraries.
Digest authentication
Unencrypted messages pass the wire, but the authentication is securely managed in the Authorization headers. See the wikipedia entry for more information.
OAuth
See how Google is providing OAuth for installed applications. I believe it isn't what you're looking for, since you're not asking to share data between applications, just authenticating users.
Roll your own
If you want to roll your own, I suggest looking at e.g. how Google's (now deprecated ?) ClientLogin used to work.
Clients would GET a protected resource, and get a 401 with instructions to perform a GoogleLogin authentication, including a URI for where to perform the login itself
Clients (knowing how to do this) POST a request in a specific manner to that URI
The server responds with a specific response including a (long) token
The client can now perform GET requests to the protected resource with that token.
Statelessness
You cite REST, which dictates that requests should not specifically depend on prior interaction: "... each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server." (fielding) This means that a server shouldn't store conversational context (like an authentication token) in a table.
One way of fixing this is by using any of the token based approaches (where the server tells the client about a token it should use for future requests) where the token is not a random number, but a message to the server itself. To protect yourself from client tampering, it can be signed, and if you're afraid of clients looking at it, you can encrypt it.
Edit: Although I'm not certain, it seems unlikely that Google has a table of all authentication tokens ever issued; The length of their tokens suggests that the token is some encrypted message proving that whoever holds this token actually provided real credentials in some realm at some time.
OAuth does exactly what you want to do in a standard way.
You could use a combination of HTTPS and HTTP Basic Auth. Both are existing standards and should be secure enough when used together.

Security of REST authentication schemes

Background:
I'm designing the authentication scheme for a REST web service. This doesn't "really" need to be secure (it's more of a personal project) but I want to make it as secure as possible as an exercise/learning experience. I don't want to use SSL since I don't want the hassle and, mostly, the expense of setting it up.
These SO questions were especially useful to get me started:
RESTful Authentication
Best Practices for securing a REST API / web service
Examples of the best SOAP/REST/RPC web APIs? And why do you like them? And what’s wrong with them?
I'm thinking of using a simplified version of Amazon S3's authentication (I like OAuth but it seems too complicated for my needs). I'm adding a randomly generated nonce, supplied by the server, to the request, to prevent replay attacks.
To get to the question:
Both S3 and OAuth rely on signing the request URL along with a few selected headers. Neither of them sign the request body for POST or PUT requests. Isn't this vulnerable to a man-in-the-middle attack, which keeps the url and headers and replaces the request body with any data the attacker wants?
It seems like I can guard against this by including a hash of the request body in the string that gets signed. Is this secure?
A previous answer only mentioned SSL in the context of data transfer and didn't actually cover authentication.
You're really asking about securely authenticating REST API clients. Unless you're using TLS client authentication, SSL alone is NOT a viable authentication mechanism for a REST API. SSL without client authc only authenticates the server, which is irrelevant for most REST APIs because you really want to authenticate the client.
If you don't use TLS client authentication, you'll need to use something like a digest-based authentication scheme (like Amazon Web Service's custom scheme) or OAuth 1.0a or even HTTP Basic authentication (but over SSL only).
These schemes authenticate that the request was sent by someone expected. TLS (SSL) (without client authentication) ensures that the data sent over the wire remains untampered. They are separate - but complementary - concerns.
For those interested, I've expanded on an SO question about HTTP Authentication Schemes and how they work.
REST means working with the standards of the web, and the standard for "secure" transfer on the web is SSL. Anything else is going to be kind of funky and require extra deployment effort for clients, which will have to have encryption libraries available.
Once you commit to SSL, there's really nothing fancy required for authentication in principle. You can again go with web standards and use HTTP Basic auth (username and secret token sent along with each request) as it's much simpler than an elaborate signing protocol, and still effective in the context of a secure connection. You just need to be sure the password never goes over plain text; so if the password is ever received over a plain text connection, you might even disable the password and mail the developer. You should also ensure the credentials aren't logged anywhere upon receipt, just as you wouldn't log a regular password.
HTTP Digest is a safer approach as it prevents the secret token being passed along; instead, it's a hash the server can verify on the other end. Though it may be overkill for less sensitive applications if you've taken the precautions mentioned above. After all, the user's password is already transmitted in plain-text when they log in (unless you're doing some fancy JavaScript encryption in the browser), and likewise their cookies on each request.
Note that with APIs, it's better for the client to be passing tokens - randomly generated strings - instead of the password the developer logs into the website with. So the developer should be able to log into your site and generate new tokens that can be used for API verification.
The main reason to use a token is that it can be replaced if it's compromised, whereas if the password is compromised, the owner could log into the developer's account and do anything they want with it. A further advantage of tokens is you can issue multiple tokens to the same developers. Perhaps because they have multiple apps or because they want tokens with different access levels.
(Updated to cover implications of making the connection SSL-only.)
Or you could use the known solution to this problem and use SSL. Self-signed certs are free and its a personal project right?
If you require the hash of the body as one of the parameters in the URL and that URL is signed via a private key, then a man-in-the-middle attack would only be able to replace the body with content that would generate the same hash. Easy to do with MD5 hash values now at least and when SHA-1 is broken, well, you get the picture.
To secure the body from tampering, you would need to require a signature of the body, which a man-in-the-middle attack would be less likely to be able to break since they wouldn't know the private key that generates the signature.
In fact, the original S3 auth does allow for the content to be signed, albeit with a weak MD5 signature. You can simply enforce their optional practice of including a Content-MD5 header in the HMAC (string to be signed).
http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html
Their new v4 authentication scheme is more secure.
http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
Remember that your suggestions makes it difficult for clients to communicate with the server. They need to understand your innovative solution and encrypt the data accordingly, this model is not so good for public API (unless you are amazon\yahoo\google..).
Anyways, if you must encrypt the body content I would suggest you to check out existing standards and solutions like:
XML encryption (W3C standard)
XML Security