waiting-for-dev / warden-jwt_auth

JWT token authentication with warden
MIT License
113 stars 56 forks source link

Access to token in token dispatch #2

Closed hwaterke closed 7 years ago

hwaterke commented 7 years ago

Hey,

In order to properly use a revocation strategy, I would like to persist on my backend the token that are generated and sent to the clients. In my token dispatch route, how can I access the token to persist it? I know the middleware will add it to the headers but I also need it before the response is sent.

My token dispatch route:

post :login do
    env['warden'].authenticate! :password
    # Grab generated token and store it in DB
    {email: env['warden'].user.email}
end
hwaterke commented 7 years ago

I should have looked at the code before asking -.-

puts "Token is #{env['warden-jwt_auth.token']}"
waiting-for-dev commented 7 years ago

In general, @hwaterke , you should configure revocation paths and let the revocation strategy grab the payload automatically. You don't need to access env for the token:

https://github.com/waiting-for-dev/warden-jwt_auth#revocation-configuration

However, I don't understand why you want to revoke a token when it has been dispatched on the login. How will the user authenticate next request, then?

hwaterke commented 7 years ago

Yeah I didn't explain my intention well enough I think.

Upon login of a user, I want to store in the database the token created. The idea is that I will provide a screen to the user where he can see a list of all his valid tokens and some information. (when was it created, which ip, which user-agent) And on that list, I will allow the user to revoke any token to make sure it cannot be used anymore.

A little bit like Facebook or Google does. You can see a list of your connected devices and revoke some logins

waiting-for-dev commented 7 years ago

Ok, I see...

In this case I would recommend you not to store the whole token in the database. You would be storing a secret so you should take precautions like encrypting and salting. You can instead extract just the jti claim, and give it to a "special" RevocationStrategy which takes it as argument. Or if you need the whole payload just store it serialzed.

hwaterke commented 7 years ago

Makes a lot of sense ! I'll just store the token id (jti) together with the owner (sub)

Any easy way for me to access the jti in my routes?

Thanks a lot for your input !

waiting-for-dev commented 7 years ago

Any easy way for me to access the jti in my routes?

You can do:

payload = Warden::JWTAuth::TokenDecoder.new.call(token)
payload['jti']