Devise is a very helpful gem used to resolve authentication in a Ruby on Rails environment. In the words of the Devise team, “Devise is a flexible authentication solution for Rails based on Warden.” Upon seeing this definition you now know that Devise works with another gem called “Warden”. So when working with the Devise gem you are also working with the Warden gem, meaning any problem you need to solve, needs to work for both gems not just Devise. Suppose you need to implement authentication for your amazing new web application, but that you need to use an external resource to make it work. A custom strategy using Devise can help to ensure your website is running right.
How Devise and Warden work together
Devise and Warden interact with your Rails app through Models and Strategies. Models are modules that get mixed into any Ruby class that declares devise. Strategies are Ruby classes that are registered with Warden, must define an instance method, and must be a subclass of Warden::Strategies::Base. Once Warden knows about your Strategy class and Devise knows about your module, the two will work together to allow you to authenticate the resource (or not!) and control what information is exposed to your controller.
The Devise Parts:
Some comments about the above code:
- I created a virtual attribute called “session_token” for save the information about session.
- I added a validation for email and provider.-“serialize_into_session”, “serialize_from_session” are override of methods called internalby Devise.
- The required used on the code will be clarify in the next session.
Now we need to configure the Devise to use this new strategy:
The Warden Parts
Some comments about the above code:
- The “MagicConnector::Custom” is a connector for process the request validation to the external service.
- I create a “custom_authentication” attribute for can review the result and process to sendto the Devise Model method create before.
- Similar with did on Devise we need “tell to Warden” about this new strategy, for this we use the last line of the code: Warden::Strategies.add(:custom_authenticatable, Devise::Strategies::OktaAuthenticatable)
Last Comments
Now we can add our custom implementation to a Devise model using the symbols register on the Devise Parts.
Our Model class looks like this: class User < ActiveRecord::Base devise :database_authenticatable, :custom_authenticatable end
Want to work with Bruno or another person from our amazing team?
Tell us about your project and we’ll pair you with the right developer, designer, or project manager that meets your needs.