How do I determine which Devise/Warden strategy was used to authenticate/log in the user?

Viewed 1303

Let's say I have two default strategies with Warden, :database_authenticatable and :jwt.

How do I determine (inside of a controller) which strategy was used to log in the current_user?

2 Answers

You can get the label of the last run strategy with env['warden'].winning_strategy. This means that the strategy was run, but its result can be :failure, :success or even :custom. You should check if env['warden'].result == :success in order to ensure the strategy was run successfully.

AFAIK there is no implementation to directly do this. You can override those strategies behaviors to inject some kind of session parameter to identify which is which, or you can use JWT Headers requisites to identify that it was used on a given request. If you are using default database_authenticable in a default setup it is being used for your general WEB navigation, which takes advantage of browser sessions. You could leverage this to identify your user, since when consuming via API cookies/sessions are not usually there. Take a look what you can do with Rails' sessions and use that to identify your user's browsers, it could be something like this:

session[:user_id] = @current_user.id
User.find(session[:user_id])

Then you could use session[:user_id].present? to check if a session is being used on a given context, excluding JWT HTTP Header behavior.

You could also do that the other way around, identifying the presence of and Authorization or Authentication HTTP Header. This would not be there unless you have JWT or other kind of HTTP authentication in place for the current request. This can be done as follows:

request.headers['Authorization'].present? || request.headers['Authentication'].present?
Related