10

I was thinking about how I implement login functionality, and realised I have no clue how I came up with it so decided to ask if it was a good way to do things.

Basically, client logs in, username/email and pass are sent to server.

Server salts and hashes password and checks it against the one in the database for that user.

If its correct, send the client the user ID and the user token. (User id could be username, or a number, it depends)

When that client makes a request, the request must contain the ID and token.

The server checks that the ID and token combo are correct, and because the ID is linked to the user we know who it is and can complete the request.

Usually I make the token a random string of 16 or 32 chars, each account has their own token, and it may be stored in the browser so they stay logged in. I also normally add a "log out everywhere" button, which essentially just generates a new token to overrides the current one, making any previously saved tokens invalid.

Comments
  • 3
    How about JWT tokens with encrypted userid in it? Takes away the ID thing
  • 2
    @alexbrooklyn that seems quite nice, I haven't used JWT tokens before but will deffinately look into it
  • 1
    What is your tech stack? Perhaps whatever you're using has an auth system to take care of it
  • 1
    @LavaTheif learn JWT. It will save your life. Does the hard work for you.
  • 1
    Im doing something exactly similar to yours.
    I use JWT to generate the tokens
  • 0
    I second JWT. You can actually store the whole user object inside of it so using a user id to query the db for the user account is unnecessary
  • 0
    @person how do you store the user object, do you do it directly or encrypt it?
    Because I was thinking of doing the same thing, but thought it might be a security risk
  • 0
    @inhamul either way, but since the jwt is stored in a cookie (which should already be secured with a secret key), encrypting the jwt isn't necessary. JWTs are signed, so even if it's not encrypted you can still check the integrity to prevent spoofing. Check out https://jwt.io/introduction/
Add Comment