Auth0 - Ruby

CircleCI Gem Version codecov Yard Docs MIT licensed FOSSA Status

Ruby API client for the Auth0 platform.

Installation

This gem can be installed directly:

$ gem install auth0

... or with Bundler:

bundle add auth0

API Documentation

https://www.rubydoc.info/gems/auth0

Management API v2

This SDK provides access to the Management API v2 via modules that help create clear and accurate calls. Most of the interaction is done through the Auth0Client class, instantiated with the required credentials.

As a simple example of how to get started, we'll create an admin route to point to a list of all users from Auth0:

# config/routes.rb
Rails.application.routes.draw do
  # ...
  get 'admin/users', to: 'all_users#index'
  # ...
end

... and a Controller to handle that route:

# app/controllers/all_users_controllers.rb
require 'auth0'

class AllUsersController < ApplicationController
  # Get all users from Auth0 with "auth0" in their email.
  def index
    @params = {
      q: "email:*auth0*",
      fields: 'email,user_id,name',
      include_fields: true,
      page: 0,
      per_page: 50
    }
    @users = auth0_client.users @params
  end

  private

  # Setup the Auth0 API connection.
  def auth0_client
    @auth0_client ||= Auth0Client.new(
      client_id: ENV['AUTH0_RUBY_CLIENT_ID'],
      client_secret: ENV['AUTH0_RUBY_CLIENT_SECRET'],
      # If you pass in a client_secret value, the SDK will automatically try to get a
      # Management API token for this application. Make sure your Application can make a
      # Client Credentials grant (Application settings in Auth0 > Advanced > Grant Types
      # tab) and that the Application is authorized for the Management API:
      # https://auth0.com/docs/api-auth/config/using-the-auth0-dashboard
      #
      # Otherwise, you can pass in a Management API token directly for testing or temporary
      # access using the key below.
      # token: ENV['AUTH0_RUBY_API_TOKEN'],
      domain: ENV['AUTH0_RUBY_DOMAIN'],
      api_version: 2,
      timeout: 15 # optional, defaults to 10
    )
  end
end

In this example, we're using environment variables to store the values needed to connect to Auth0 and authorize. The token used above is an API token for the Management API with the scopes required to perform a specific action (in this case read:users). These tokens can be generated manually using a test Application or with the Application being used for your project.

Finally, we'll add a view to display the results:

# app/views/all_users/index.html.erb
<h1>Users</h1>
<%= debug @params %>
<%= debug @users %>

This should show the parameters passed to the users method and a list of users that matched the query (or an empty array if none).

Authentication

In addition to the Management API, this SDK also provides access to Authentication API endpoints with the Auth0::API::AuthenticationEndpoints module. For basic login capability, we suggest using our OmniAuth stategy detailed here. Other authentication tasks currently supported are:

  • Register a new user with a database connection using the signup method.
  • Redirect a user to the universal login page for authentication using the authorization_url method.
  • Log a user into a highly trusted app with the Resource Owner Password grant using the login method.
  • Exchange an authorization code for an access token on callback using the obtain_user_tokens method (see the note on state validation below).
  • Send a change password email to a database connection user using the change_password method.
  • Log a user out of Auth0 with the logout_url method.

Important note on state validation: If you choose to implement a login flow callback yourself, it is important to generate and store a state value, pass that value to Auth0 in the authorization_url method, and validate it in your callback URL before calling obtain_user_tokens. For more information on state validation, please see our documentation.

Please note that this module implements endpoints that might be deprecated for newer tenants. If you have any questions about how and when the endpoints should be used, consult the documentation or ask in our Community forums.

ID Token Validation

An ID token may be present in the credentials received after authentication. This token contains information associated with the user that has just logged in, provided the scope used contained openid. You can read more about ID tokens here.

Before accessing its contents, you must first validate the ID token to ensure it has not been tampered with and that it is meant for your application to consume. Use the validate_id_token method to do so:

begin
  @auth0_client.validate_id_token 'YOUR_ID_TOKEN'
rescue Auth0::InvalidIdToken => e
  # In this case the ID Token contents should not be trusted
end

The method takes the following optional keyword parameters:

Parameter Type Description Default value
algorithm JWTAlgorithm The signing algorithm used by your Auth0 application. Auth0::Algorithm::RS256 (using the JWKS URL of your Auth0 Domain)
leeway Integer Number of seconds to account for clock skew when validating the exp, iat and azp claims. 60
nonce String The nonce value you sent in the call to /authorize, if any. nil
max_age Integer The max_age value you sent in the call to /authorize, if any. nil
issuer String By default the iss claim will be checked against the URL of your Auth0 Domain. Use this parameter to override that. nil
audience String By default the aud claim will be compared to your Auth0 Client ID. Use this parameter to override that. nil

You can check the signing algorithm value under Advanced Settings > OAuth > JsonWebToken Signature Algorithm in your Auth0 application settings panel. We recommend that you make use of asymmetric signing algorithms like RS256 instead of symmetric ones like HS256.

# HS256

begin
  @auth0_client.validate_id_token 'YOUR_ID_TOKEN', algorithm: Auth0::Algorithm::HS256.secret('YOUR_SECRET')
rescue Auth0::InvalidIdToken => e
  # Handle error
end

# RS256 with a custom JWKS URL

begin
  @auth0_client.validate_id_token 'YOUR_ID_TOKEN', algorithm: Auth0::Algorithm::RS256.jwks_url('YOUR_URL')
rescue Auth0::InvalidIdToken => e
  # Handle error
end

Development

In order to set up the local environment you'd have to have Ruby installed and a few global gems used to run and record the unit tests. A working Ruby version can be taken from the CI script. At the moment of this writting we're using Ruby 2.5.7.

It is expected that every Pull Request introducing a fix, change or feature contains enough test coverage to assert the new behavior.

Running the tests

Install the gems required for this project.

bundle install

Finally, run the tests.

bundle exec rake test

Running only unit tests

You can run only the unit tests and ignore the integration tests by running the following:

bundle exec rake spec

Running only integration tests

You can run only the unit tests and ignore the integration tests by running the following:

bundle exec rake integration

More Information

What is Auth0?

Auth0 helps you to:

  • Add authentication with multiple authentication sources, either social like Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce among others, or enterprise identity systems like Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider.
  • Add authentication through more traditional username/password databases.
  • Add support for linking different user accounts with the same user.
  • Support for generating signed JSON Web Tokens to call your APIs and flow the user identity securely.
  • Analytics of how, when, and where users are logging in.
  • Pull data from other sources and add it to the user profile with JavaScript rules.

Create a free Auth0 Account

  1. Go to Auth0 and click Sign Up.
  2. Use Google, GitHub or Microsoft Account to login.

Issue Reporting

If you find a bug or have a feature request, please report them in this repository's Issues tab. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

Author

Auth0

License

This project is licensed under the MIT license. See the LICENSE file for more info.

FOSSA Status