janko / rodauth-rails

Rails integration for Rodauth authentication framework
https://github.com/jeremyevans/rodauth
MIT License
571 stars 40 forks source link

#set_jwt_token not working #54

Closed holdenhinkle closed 3 years ago

holdenhinkle commented 3 years ago

Hi there,

I have a :user configuration with jwt enabled.

When I call rodauth(:user).set_jwt_token(rodauth(:user).jwt_token) the Authentication header doesn't get set. So instead, I set it manually, like this: response.headers['Authorization'] = rodauth(:user).jwt_token.

I looked up the documentation for this method here - https://rodauth.jeremyevans.net/rdoc/index.html It's exactly what I'm doing manually. Here's the source:

# File lib/rodauth/features/jwt.rb
def set_jwt_token(token)
  response.headers['Authorization'] = token
end

Here's the context that I'm using it in, in app/controllers/application_controller.rb:

def current_account
  unless @current_account
    if rodauth(:user).use_jwt?
      if rodauth(:user).valid_jwt?
        @current_account = UserAccount.find(rodauth(:user).session_value)
        response.headers['Authorization'] = rodauth(:user).jwt_token
      end
    else
      @current_account = AdminAccount.find(rodauth(:admin).session_value)
    end
  end
rescue ActiveRecord::RecordNotFound
  rodauth.logout
  rodauth.login_required 
end

Perhaps I'm doing something wrong. I thought I'd report it in case there's a bug.

Thanks!

janko commented 3 years ago

I'm not sure why the token isn't being set with #set_jwt_token, probably the headers written to Rodauth's response object aren't somehow being applied to the overall response. The following worked for me:

  after_action :set_jwt_token

  private

  def set_jwt_token
    if rodauth(:user).use_jwt? && rodauth(:user).valid_jwt?
      response.headers["Authorization"] = rodauth(:user).session_jwt
    end
  end

I used #session_jwt just in case there are any session changes during the request to the main app.

It wasn't trivial for me to come up with this solution, so I'll think about how to simplify it and/or document it.

holdenhinkle commented 3 years ago

Hi Janko,

Thanks for looking at this, I appreciate it.

This is smart, which I wasn't doing:

I used #session_jwt just in case there are any session changes during the request to the main app.

All the best,

Holden