Passa al contingut principal

Remote authentication with devise

Devise is great. It simplifies lots of tasks related to resource management: authentication, registration, confirmation, etc; and it does it in a clean and highly configurable way. But it is only this great if you are managing your resources locally. Devise has adapters only for models backed up with ActiveRecord or MongoId which means that if you’re using resources provided by an external webservice you can’t use Devise.


But don’t despair.


Extending Devise


First of all we have to get a basic idea of how Devise authenticates your resources. This explanation might be a bit rough so I’m going to use the following diagram to ease the explanation (kudos to asischao for his help).


The workflow of a request



  1. A request to authenticate a resource is received in the Rails app and it matches a route generated by devise_for.

  2. The request is handled (by default) by the SessionsController, provided by Devise, which delegates the authentication to Warden

  3. Warden uses one of the strategies provided by Devise to determine if the resource can be authenticated or not.


The output of this process is an authenticated resource. Or not.


So, from this list of steps it seems that we have the following spots to work on:



  • Configure our resource to enable remote authentication.

  • Create an strategy that authenticates the resources with the external webservice.


Configuring the resource


Lets assume that our resource is a PORO called User


User PORO








1
2
3


class User
attr_accessor :id
end



Devise requires some functionallity that we usually have for free when using ActiveRecord resources. As this is not the case we have to do some plumbing: include some ActiveModel modules and extend the class using Devise::Models.


Preparation








1
2
3
4
5
6
7


class User
include ActiveModel::Validations #required because some before_validations are defined in devise
extend ActiveModel::Callbacks #required to define callbacks
extend Devise::Models

define_model_callbacks :validation #required by Devise
end



At this point we are ready to configure Devise.


Enable Devise








1
2
3


class User
devise :remote_authenticatable
end



Authentication module


To understand a bit better what we are doing here take a look at the following Devise modules:



We have to create a module that performs at least three tasks:



  • Authenticate the resouce using the remote webservice.

  • Return an array of data that will be used to store a reference to the resource in the session.

  • Use this session data to re-build the resource.


Authenticate using the remote resource








1
2
3
4
5
6
7
8
9
10
11


module Devise
module Models
module RemoteAuthenticatable
extend ActiveSupport::Concern

def remote_authentication(authentication_hash)
# Your logic to authenticate with the external webservice
end
end
end
end



Devise::Models::RemoteAuthenticatable#remote_authentication will be used later (in the Warden strategy) to authenticate the resource using the remote webservice. This method performs almost the same function as Devise::Models::DatabaseAuthenticatable#valid_pasword? in the sense that they both have to return a resource instance if the creedentials are valid or false otherwise.


Serialize/Deserialize








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20


module Devise
module Models
module RemoteAuthenticatable
extend ActiveSupport::Concern

module ClassMethods
def serialize_from_session(id)
resource = self.new
resource.id = id
resource
end

def serialize_into_session(record)
[record.id]
end

end
end
end
end



We overwrite Devise::Models::ClassMethods#serialize_into_session and Devise::Models::ClassMethods#serialize_from_session because their implementation is tied to resources using some kind of database backup. In this methods you just have to return an array with data that you’ll use later to re-build the resource instance.


The full code (with comments) of Devise::Models::RemoteAuthenticatable is on this gist


Creating an strategy


Strategies contains the logic used by Warden to authenticate users. They must define an authenticate! method, where the request will be processed. Inside this method you can take several actions:



  • halt! which halts the cascading of strategies.

  • fail! fails the strategy. Calls halt!

  • success! log in a user.

  • And other actions. Take a look at the documentation


Because of the conventions used by Devise, the strategy name has to be the same as the name of the module used to authenticate the resource.


Warden strategy for Devise








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18


module Devise
module Strategies
class RemoteAuthenticatable < Authenticatable
def authenticate!
auth_params = authentication_hash
auth_params[:password] = password

resource = mapping.to.new

return fail! unless resource

if validate(resource){ resource.remote_authentication(auth_params) }
success!(resource)
end
end
end
end
end



The previous code is pretty straightforward. We create a new resource and using Devise::Models::RemoteAuthenticatable#remote_authentication we authenticate it. If the authentication succeeds we mark the request as valid with success!.


Gist with the code, and comments, of this strategy.


Putting everything together


So, to sum up, this solution is composed of:



  • Devise::Models::RemoteAuthenticatable, a module used by Devise to authenticate the resource.

  • Devise::Strategies::RemoteAuthenticatable, a class implementing a Warden strategy.


Finally, don’t forguet to configure Devise (in config/initializers/devise.rb) to use all the stuff we have done here : )


Configure Devise








1
2
3
4


config.warden do |manager|
manager.strategies.add(:remote, Devise::Strategies::RemoteAuthenticatable)
manager.default_strategies(:scope => :user).unshift :remote
end







via 4Trabes http://4trabes.com/2012/10/31/remote-authentication-with-devise/

Comentaris

Entrades populars d'aquest blog

Learn Composition from the Photography of Henri Cartier-Bresson

“Do you see it?” This question is a photographic mantra. Myron Barnstone , my mentor, repeats this question every day with the hopes that we do “see it.” This obvious question reminds me that even though I have seen Cartier-Bresson’s prints and read his books, there are major parts of his work which remain hidden from public view. Beneath the surface of perfectly timed snap shots is a design sensibility that is rarely challenged by contemporary photographers. Henri Cartier-Bresson. © Martine Franck Words To Know 1:1.5 Ratio: The 35mm negative measures 36mm x 24mm. Mathematically it can be reduced to a 3:2 ratio. Reduced even further it will be referred to as the 1:1.5 Ratio or the 1.5 Rectangle. Eyes: The frame of an image is created by two vertical lines and two horizontal lines. The intersection of these lines is called an eye. The four corners of a negative can be called the “eyes.” This is extremely important because the diagonals connecting these lines will form the breakdown ...

El meu editor de codi preferit el 2024, que això ja se sap que va canviant 😄

Visual Code Visual Code és un editor de codi font lleuger, però potent que s’executa al teu escriptori i està disponible per a Windows, macOS i Linux. Compta amb suport integrat per a JavaScript, TypeScript i Node.js i té un ric ecosistema d’extensions per a altres llenguatges i entorns d’execució (com C++, C#, Java, Python, PHP, Go, .NET).  És una eina ideal per a desenvolupar i depurar aplicacions web i en el núvol. Per què Visual Code? Visual Code té molts avantatges com a editor de codi font, com per exemple: És gratuït, ràpid i fàcil d’instal·lar i actualitzar. Té un ampli ecosistema d’extensions que et permeten afegir funcionalitats i personalitzar la teva experiència de desenvolupament. Té un suport integrat per a molts llenguatges i entorns d’execució, i et permet depurar i executar el teu codi des del mateix editor. Té una interfície senzilla i elegant, amb diferents temes i modes de visualització. Té un sistema de sincronització de configuracions que et permet guardar les...

Las Mejores Aplicaciones Gratis para iPad de 2012

Las Mejores Aplicaciones Gratis para iPad de 2012 : ¿No tienes ni un duro? No te preocupes, pues hoy os traemos una extensa selección de las mejores apps gratuitas que puedes conseguir en la App Store para que llenes tu iPad de calidad, sin gastar nada de nada.   ¿Estás buscando juegos o apps gratis para tu iPad? En la App Store hay más de 500,000 apps y juegos, y una gran cantidad de ellos está disponible de forma totalmente gratuita. Aquí vamos con la selección de las mejores Apps gratis para iPad (todos los modelos), organizada por categoría. ¿Estás preparado? Las Mejores Apps Gratis de Redes Sociales para iPad Nombre Facebook Gratis Categoría Redes sociales Facebook es la red social más famosa del mundo , con casi mil millones de usuarios. Su app para iPad ha tardado, pero aquí está. Nombre Twitter Gratis Categoría Redes sociales Twitter es la red de microblogging por excelencia. La forma más rápida y directa de informar y mantenerse informado de las cosa...