Let's consider this use case:
1) I call my API login endpoint with username and password and get my Auth token that I add to every consecutive request to the header as Authorization: Bearer <token>
.
2) I call /current-user
endpoint with no params, only with Authorization header. Server authorizes user using token and gets user's id from that token. Then he finds the user by id in database and returns it's data.
My question is, whether this approach isn't insecure. I'm wondering, what if I was an attacker and was calling /current-user
endpoint using randomly generated tokens. Once I occasionally matched real token, the server would return me other user's data.
Isn't it necessary to store user id on client along with token and call requests using both? Eg. /user?id=<stored user id>
with Authorization header and get rid of /current-user
endpoint? After that some kind of ACL on server would determine, whether used token has allowed access to user with passed user id.
(I also found there are JWT tokens but I see the same problem there. As an attacker I would somehow manage to guess other user's token and server would return me his data)
For security purposes, it is normally assumed that the user id is known to the attacker anyway. For example, if the attacker already has or knows a legitimate account, she might be able to guess how other user ids are assigned.
Also, if your token is long enough and totally random, it doesn't really make any difference.
Look at it this way: let's say your token has length n
, your user id has length m
. Without the user id, the attacker has to guess n
characters, with it included she has to guess n+m
characters. If your n
is high enough, you don't need those extra characters. Keep in mind that the effective length of the user id might be much shorter than its apparent length if your user ids aren't completely random, so the m
added might actually be really small.