This is a theoretical question. For some APIs, user need to authenticate themselves and we have authentication token for a user. I feel using GET api is not good idea due to this token.
/get_data/?user_token=hshhlj8979kjhk&dataid=87979
Indeed it's not a good idea, but not due to GET in itself. The real problem is the token as part of the URL and the security problems it creates.
The URL portion of a request is very often cached and logged for auditing or debugging purposes, and having the token there causes it to leak unintentionally.
For example, browsers save your browsing history, and the main portion they record is the URL, so there goes your password to your history, a place it doesn't belongs and is easily exposed accidentally.
Most web servers by default also log the URLs they receive, so again there goes your token. It's quite common for it to end up in logs on web servers, load balancers, intermediate routers and so on, again leaking all over the place.
The solution to this is to strip the token from the URL portion, leaving there only data that's not security-critical. The most common place to put it is in the request's headers. Those are well respected by the HTTP standard and almost never logged or accidentally dumped like the URL.
Of course, all other methods suffer the same. POST, PUT, DELETE, OPTIONS for example, none of them should be ever called with secret data in the URL. Headers provide a "safer" place for that available across all methods. The request body is another common place, but you can't have one in GET, making a header the best alternative.
Related
I am a newbie in Javascript and Vue.js. Try to learn more about it. Now I will be facing a problem when calling an API login that will display a password in the request payload.
I was wondering it does not secure, right? And if it was correct. How to hide it from the browser?
Anyone please help or suggest to me.
This is a pretty heavy topic and the question is not very specific, so I'll make some assumptions along the way.
calling an API login that will display a password in the request payload
I suspect you mean that if you're looking into the requests in the browser dev toolbar, the password is seen.
If this is the case, this is expected and can't be 100% mitigated. I've known people to assume that this means that this means that the data is not encrypted and develop custom solutions to obscure the sensitive data. The thing to keep in mind though is that the browser already does the encryption for you as long as you use https. The encryption happens after the request leaves your browser, so you're not seeing it as encrypted, but it travels to the designated server in a way that hides the content for anyone in the middle. If you add some additional encryption system, you're adding complexity and as long as you're passing the key as-well, the "man in the middle" has access to that too. The endpoints within the target server are also encrypted, so you could even use GET to pass sensitive information without anyone between your browser and server knowing what it is, but don't use GET, since POST has additional benefits like not storing the values in your url cache and the server is less likely to be storing the data in the logs.
When using https properly, your data will be encrypted between browser and server.
You should be using POST requests for sending sensitive data
Avoid adding custom encryption on top of https. It will add more complexity than security.
There's also some considerations around storing the token in LocalStorage vs cookies. The final decision on which is better is inconclusive, but as long as proper precautions are taken, they can both be secure (though I think cookies can be more secure, but only if you make them inaccessible by js, so it makes working with them in context of an SPA harder)
I'm using Session-based authentication in my app, and I want to protect against CSRF attacks I thought about just sending the session id in the header of the request.
To be clear the backed server will set the session id in a cookie but will validate the request against the id in the header. so the front end has to read the value of the cookie and send it in custom header
in that way no request will pass the security checkup without knowing the session id (the attacker can't relay on the browser to send it like the cookies).
is that considered as a bad practise or there's something that I'm missing here.
For this you would have to set the session id in a non-httpOnly cookie, which is against the traditional best practice.
However, if you just call it a token, it magically becomes ok. :)
Speaking seriously, you need to assess and accept (or not) the risk. You can generate your session id and return it in the response body upon login. It would behave like a token, you would probably store it in localStorage (or leave it in the cookie, which is even worse because cookies are sometimes stored as plain files in the client filesystem) and send it as a request header. It would be accessible by javascript, meaning it would be susceptible to potential xss. The same is true for any token-based authentication. This would effectively mitigate csrf, and is a usual thing to do.
However, exchanging csrf for xss when you don't actually need a token-based solution does not sound like a good deal. You will have xss in your app if it grows big enough. The best possible place for request authentication info (ie. a session id) is a httpOnly cookie so that it's protected against xss. Then of course you need separate csrf protection.
The only scenario where you would use tokens is if you need to send the token to multiple origins (eg. multiple apis on different domain), or in a single sign-on scenario where the identity provider and service providers are different. Cookies cannot do this.
So if you don't need tokens, it's best to avoid the higher risk xss (at least for the session id) and implement separate csrf protection.
No, don't do that.
I'm assuming the session ID is the token/string/whatever that is equivalent to the password. IE, if an attacker can get the sessionid, then they can impersonate the user.
The only way to show javascript the sessionid is to expose it to javascript.
There is a section in the RFC talking about cookie security issues. Let's accept it as a truth that you want to keep it private from javascript.
If you want to skip XSRF checking then you need to make sure to do some things perfectly, today, and again a year from now.
never allow get requests to change state. they are unprotected.
never set a CORS policy to allow other origins.
never trust query string parameters.
always validate the referer header.
Probably other things too.
XSRF tokens are much easier. Here's the standard approach.
when you generate the session ID, take a one way hash of it, and set it as a cookie with without httpOnly.
read the value of that cookie from your javascript and set it in the request header.
That's easier than 1-4 above.
Libraries like axios have built in support for applying the xsrf token to all requests (search for xsrf).
Wikipedia has a good writeup on xsrf too...
I'm kind of surprised that, after searching for this for a while, I didn't find as many answers as I thought would be out there (well I found none), so maybe by asking it here we can help improve search results.
I'm building a REST api which has JWT-based authentication. There is an /auth/login route which returns the token after login/password verification, and the token is subsequently sent in every route in a Authorization http header.
Not, suppose that someone queries another route (say, /cars), without sending the token (that is, before logging in). If I return a 401 unauthorized, I can make the frontend query /auth/login to get the token.
But, strictly speaking, this does not conform to the REST specification, because every resource should be discoverable from the initial one, and a client accessing /cars and receiving a 401 will not know about /auth/login.
So another option would be a redirection like 302. But this semantics means that the resource was temporarily moved, and this is not the case (the resource is still /cars, you just need to authenticate first).
So, what is the correct way to do this procedure in a "true" rest api?
I 100% agree, and that's why I proposed this standard:
https://datatracker.ietf.org/doc/html/draft-pot-authentication-link-01
The idea is that for cases like this, you should be able to return a Link header with an authentication rel, so the client can discover how to proceed.
I know this is not the first time the topic is treated in StackOverflow, however, I have some questions I couldn't find an answer to or other questions have opposed answers.
I am doing a rather simple REST API (Silex-PHP) to be consumed initially by just one SPA (backbone app). I don't want to comment all the several authentication methods in this question as that topic is already fully covered on SO. I'll basically create a token for each user, and this token will be attached in every request that requires authentication by the SPA. All the SPA-Server transactions will run under HTTPS. For now, my decision is that the token doesn't expire. Tokens that expire/tokens per session are not complying with the statelessness of REST, right? I understand there's a lot of room for security improvement but that's my scope for now.
I have a model for Tokens, and thus a table in the database for tokens with a FK to user_id. By this I mean the token is not part of my user model.
REGISTER
I have a POST /users (requires no authentication) that creates a user in the database and returns the new user. This complies with the one request one resource rule. However, this brings me certain doubts:
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
If I decided to return the token together with the user, then I believe POST /users would be confusing for the API consumer, and then something like POST /auth/register appears. Once more, I dislike this idea because involves a verb. I really like the simplicity offered in this answer. But then again, I'd need to do two requests together, a POST /users and a POST /tokens. How wrong is it to do two requests together and also, how would I exactly send the relevant information for the token to be attached to a certain user if both requests are sent together?
For now my flow works like follows:
1. Register form makes a POST /users request
2. Server creates a new user and a new token, returns both in the response (break REST rule)
3. Client now attaches token to every Request that needs Authorization
The token never expires, preserving REST statelessness.
EMAIL VALIDATION
Most of the current webapps require email validation without breaking the UX for the users, i.e the users can immediately use the webapp after registering. On the other side, if I return the token with the register request as suggested above, users will immediately have access to every resource without validating emails.
Normally I'd go for the following workflow:
1. Register form sends POST /users request.
2. Server creates a new user with validated_email set to false and stores an email_validation_token. Additionally, the server sends an email generating an URL that contains the email_validation_token.
3. The user clicks on the URL that makes a request: For example POST /users/email_validation/{email_validation_token}
4. Server validates email, sets validated_email to true, generates a token and returns it in the response, redirecting the user to his home page at the same time.
This looks overcomplicated and totally ruins the UX. How'd you go about it?
LOGIN
This is quite simple, for now I am doing it this way so please correct me if wrong:
1. User fills a log in form which makes a request to POST /login sending Basic Auth credentials.
2. Server checks Basic Auth credentials and returns token for the given user.
3. Web app attached the given token to every future request.
login is a verb and thus breaks a REST rule, everyone seems to agree on doing it this way though.
LOGOUT
Why does everyone seem to need a /auth/logout endpoint? From my point of view clicking on "logout" in the web app should basically remove the token from the application and not send it in further requests. The server plays no role in this.
As it is possible that the token is kept in localStorage to prevent losing the token on a possible page refresh, logout would also imply removing the token from the localStorage. But still, this doesn't affect the server. I understand people who need to have a POST /logout are basically working with session tokens, which again break the statelessness of REST.
REMEMBER ME
I understand the remember me basically refers to saving the returned token to the localStorage or not in my case. Is this right?
If you'd recommend any further reading on this topic I'd very much appreciate it. Thanks!
REGISTER
Tokens that expire/tokens per session are not complying with the statelessness of REST, right?
No, there's nothing wrong with that. Many HTTP authentication schemes do have expiring tokens. OAuth2 is super popular for REST services, and many OAuth2 implementations force the client to refresh the access token from time to time.
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
Typically, if you create a new resource following REST best practices, you don't return something in response to a POST like this. Doing this would make the call more RPC-like, so I would agree with you here... it's not perfectly RESTful. I'll offer two solutions to this:
Ignore this, break the best practices. Maybe it's for the best in this case, and making exceptions if they make a lot more sense is sometimes the best thing to do (after careful consideration).
If you want be more RESTful, I'll offer an alternative.
Lets assume you want to use OAuth2 (not a bad idea!). The OAuth2 API is not really RESTful for a number of reasons. I'm my mind it is still better to use a well-defined authentication API, over rolling your own for the sake of being RESTful.
That still leaves you with the problem of creating a user on your API, and in response to this (POST) call, returning a secret which can be used as an access/refresh token.
My alternative is as follows:
You don't need to have a user in order to start a session.
What you can do instead is start the session before you create the user. This guarantees that for any future call, you know you are talking to the same client.
If you start your OAuth2 process and receive your access/refresh token, you can simply do an authenticated POST request on /users. What this means is that your system needs to be aware of 2 types of authenticated users:
Users that logged in with a username/password (`grant_type = passsword1).
Users that logged in 'anonymously' and intend to create a user after the fact. (grant_type = client_credentials).
Once the user is created, you can assign your previously anonymous session with the newly created user entity, thus you don't need to do any access/refresh token exchanges after creation.
EMAIL VALIDATION
Both your suggestions to either:
Prevent the user from using the application until email validation is completed.
Allow the user to use the application immediately
Are done by applications. Which one is more appropriate really depends on your application and what's best for you. Is there any risk associated with a user starting to use an account with an email they don't own? If no, then maybe it's fine to allow the user in right away.
Here's an example where you don't want to do this: Say if the email address is used by other members of your system to add a user as a friend, the email address is a type of identity. If you don't force users to validate their emails, it means I can act on behalf of someone with a different email address. This is similar to being able to receive invitations, etc. Is this an attack vector? Then you might want to consider blocking the user from using the application until the email is validated.
You might also consider only blocking certain features in your application for which the email address might be sensitive. In the previous example, you could prevent people from seeing invitations from other users until the email is validated.
There's no right answer here, it just depends on how you intend to use the email address.
LOGIN
Please just use OAuth2. The flow you describe is already fairly close to how OAuth2 works. Take it one step further an actually use OAuth2. It's pretty great and once you get over the initial hurdle of understanding the protocol, you'll find that it's easier than you thought and fairly straightforward to just implement the bits you specifically need for your API.
Most of the PHP OAuth2 server implementations are not great. They do too much and are somewhat hard to integrate with. Rolling your own is not that hard and you're already fairly close to building something similar.
LOGOUT
The two reasons you might want a logout endpoint are:
If you use cookie/session based authentication and want to tell the server to forget the session. It sounds like this is not an issue for you.
If you want to tell the server to expire the access/refresh token earlier. Yes, you can just remove them from localstorage, and that might be good enough. Forcing to expire them server-side might give you that little extra confidence. What if someone was able to MITM your browser and now has access to your tokens? I might want to quickly logout and expire all existing tokens. It's an edge case, and I personally have never done this, but that could be a reason why you would want it.
REMEMBER ME
Yea, implementing "remember me" with local storage sounds like a good idea.
I originally took the /LOGON and /LOGOUT approach. I'm starting to explore /PRESENCE. It seems it would help me combine both knowing someone's status and authentication.
0 = Offline
1 = Available
2 = Busy
Going from Offline to anything else should include initial validation (aka require username/password). You could use PATCH or PUT for this (depending how you see it).
You are right, SESSION is not allowed in REST, hence there is no need to login or logout in REST service and /login, /logout are not nouns.
For authentication you could use
Basic authentication over SSL
Digest authentication
OAuth 2
HMAC, etc.
I prefer to use PUBLIC KEY and PRIVATE KEY [HMAC]
Private key will never be transmitted over web and I don't care about public key. The public key will be used to make the user specific actions [Who is holding the api key]
Private key will be know by client app and the server. The private key will be used to create signature. You generate a signature token using private key and add the key into the header. The server will also generate the signature and validate the request for handshake.
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
Now how you will get private key? you have to do it manually like you put facebook, twitter or google api key on you app.
However, in some case you can also return [not recommended] the key only for once like Amazon S3 does. They provide "AWS secret access key" at the registration response.
An intelligent coworker friend of mine brought up a question to me that I was uncertain how to answer and I'd like to pose it to the world.
If a RESTful endpoint uses token-based authentication, aka a time-based token is required to access a resource and that token expires after a certain amount of time, would this violate the RESTful principle? In other words, if the same URL expires after a certain amount of time, so the resource returns a different response depending when it was requested, is that breaking REST?
No, your scenario is not breaking any restful principle that I can think of. You seem to be confusing a request returning a different resource and a request getting a different response.
In your scenario I would expect after the token has expired that the server would return a 401 and the client would initiate some kind of authentication exchange to re-validate the user.
Once revalidated, the server should then return the intended resource.
There are many cases when a request could have completely different responses. 403 Forbidden, 410 Gone are examples.
The user/application access right to the URL may expire but that does not mean the URL expires. In large real world systems the auth part of the API may be handles by a different product, shielding the real API from attacks, unauthorized users, etc. So the RESTful API still follows the restful principles.
Your design is not violating REST constraints, but you must be careful that you use HTTP correctly. If your resources are only intended to be seen by a certain user, that user should be authenticated using HTTP authentication. This will tell public caches not to cache the representations of the resource (which they otherwise usually would).
So, even if you intend the URL to be only known by a certain user, make sure you also have that user authenticate itself using the correct HTTP headers.
Jan
Resources will frequently give a different response depending on when they are requested. That's what happens when the actual resources change over time. Requesting the resource of this page (for instance) in a week will likely give different responses than doing so when you read this the first time.