Specifying OmniAuth
Authentication in a Ruby on Rails application is a problem well-served by libraries like Devise, but the requirement for authentication via a third party comes up in most cases.
With an access token in hand, it’s easy to pass around identities and easier to access personal information, and all of this is only an additional dependency away — OmniAuth.
When authenticating via something like Auth0, it is possible to rely solely on OAuth without Devise and its handy helpers. However, doing so means additional setup to specify protected requests with RSpec.
module AuthenticationHelpers
include Rails.application.routes.url_helpers
def omniauth_user_hash(user)
OmniAuth::AuthHash.new(
'email' => user.email,
'email_verified' => user.email_verified,
'name' => user.name,
'nickname' => user.nickname,
'sub' => user.sub
)
end
def omniauth_auth0_hash(user, info)
OmniAuth::AuthHash.new(
'provider' => 'auth0',
'sub' => user.sub,
'info' => info,
'extra' => { 'raw_info' => info }
)
end
def sign_in(user)
Rails.application.env_config['omniauth.auth'] =
OmniAuth.config.mock_auth[:auth0] =
omniauth_auth0_hash(user, omniauth_user_hash(user))
get auth_auth0_callback_path(
strategy: 'auth0',
code: 'test-callback-code'
)
user
end
end
RSpec.configure do |config|
config.include AuthenticationHelpers, type: :request
end
The code above assumes your user
has the corresponding AuthHash
properties
and reuses the info map in two places. More care may be required to replicate
individual providers accurately.