JSON Web Token with Devise

Viewed 8699

I hope this does not count as an opinionated question. I just need to be pointed in the right direction.

I am modifying the Devise gem to work purely with JSON. I have had no problems with the registration, confirmation, re-confirmation, locking so far.

However, while working with the sign in, I dug deeper and understand that the default Devise sign in strategy uses Warden as it has to do with sessions and Rack authentication.

I understand JWT contains all the information in itself and does not need sessions.

So if I strip the default Devise strategy of everything and simply return a JWT on success and errors on error, would that be the right approach?

Am I missing something?

4 Answers

I wouldn't use devise_token_auth since it seems like too much hassle and ... you store tokens in db :/. Why would we want to do so if JWT is available.

I'd rather add a new strategy to Warden/Devise couple and let them work as they should.

Here's an example: https://medium.com/@goncalvesjoao/rails-devise-jwt-and-the-forgotten-warden-67cfcf8a0b73 . One thing to note: JWTWrapper doesn't really belong to app/helpers/ . You need to inject somewhere a call to JWTWrapper.encode({ user_id: current_user.id }) once your users successfully signs in with their email/password. Perhaps in the Devise SessionsController?

def create
  self.resource = warden.authenticate!(auth_options)
  sign_in(resource_name, resource)
  yield resource if block_given?
  render json: JWTWrapper.encode({user_id:current_user.id})
end

You might want to do this only for xhr or json (format) requests

Related