Skip to content

Latest commit

 

History

History
222 lines (160 loc) · 10.6 KB

EXAMPLES.md

File metadata and controls

222 lines (160 loc) · 10.6 KB

Examples using ruby-auth0

Build a URL to Universal Login Page

require 'auth0'

client = Auth0Client.new(
  client_id: ENV['AUTH0_RUBY_CLIENT_ID'],
  client_secret: ENV['AUTH0_RUBY_CLIENT_SECRET'],
  domain: ENV['AUTH0_RUBY_DOMAIN'],
)

client.authorize_url 'http://localhost:3000'

> => #<URI::HTTPS https://YOUR_DOMAIN/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000>

Management API Client

As a simple example of how to get started with the management API, 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_controller.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'],
      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).

Organizations

Organizations is a set of features that provide better support for developers who build and maintain SaaS and Business-to-Business (B2B) applications.

Note that Organizations is currently only available to customers on our Enterprise and Startup subscription plans.

Logging in with an Organization

Configure the Authentication API client and pass your Organization ID or name to the authorize url:

require 'auth0'

@auth0_client ||= Auth0Client.new(
  client_id: '{YOUR_APPLICATION_CLIENT_ID}',
  client_secret: '{YOUR_APPLICATION_CLIENT_SECRET}',
  domain: '{YOUR_TENANT}.auth0.com',
  organization: "{YOUR_ORGANIZATION_ID_OR_NAME}"
)

universal_login_url = @auth0_client.authorization_url("https://{YOUR_APPLICATION_CALLBACK_URL}")

# redirect_to universal_login_url

Accepting user invitations

Auth0 Organizations allow users to be invited using emailed links, which will direct a user back to your application. The URL the user will arrive at is based on your configured Application Login URI, which you can change from your Application's settings inside the Auth0 dashboard. When they arrive at this URL, a invitation and organization query parameters will be provided

require 'auth0'

@auth0_client ||= Auth0Client.new(
  client_id: '{YOUR_APPLICATION_CLIENT_ID}',
  client_secret: '{YOUR_APPLICATION_CLIENT_ID}',
  domain: '{YOUR_TENANT}.auth0.com',
  organization: "{YOUR_ORGANIZATION_ID_OR_NAME}"
)

universal_login_url = @auth0_client.authorization_url("https://{YOUR_APPLICATION_CALLBACK_URL}", {
  organization: "{ORGANIZATION_QUERY_PARAM}", # You can override organization if needed
  invitation: "{INVITATION_QUERY_PARAM}"
})

# redirect_to universal_login_url

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
organization String By default the org_id or org_name claims will be compared to the organization value specified at client creation. 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

Organization claim validation

If an org_id or org_name claim is present in the access token, then the claim should be validated by the API to ensure that the value received is expected or known.

In particular:

  • The issuer (iss) claim should be checked to ensure the token was issued by Auth0

  • the org_id or org_name claim should be checked to ensure it is a value that is already known to the application. Which claim you check depends on the organization value being validated: if it starts with org_, validate against the org_id claim. Otherwise, validate against org_name. Further, the value of the org_name claim will always be lowercase. To aid the developer experience, you may also lowercase the input organization name when checking against the org_name, but do not modify the org_name claim value.

This could be validated against a known list of organization IDs or names, or perhaps checked in conjunction with the current request URL. e.g. the sub-domain may hint at what organization should be used to validate the Access Token.

Normally, validating the issuer would be enough to ensure that the token was issued by Auth0. In the case of organizations, additional checks should be made so that the organization within an Auth0 tenant is expected.

If the claim cannot be validated, then the application should deem the token invalid.

begin
  @auth0_client.validate_id_token 'YOUR_ID_TOKEN', organization: '{Expected org_id or org_name}'
rescue Auth0::InvalidIdToken => e
  # In this case the ID Token contents should not be trusted
end

For more information, please read Work with Tokens and Organizations on Auth0 Docs.

Use a private key to authenticate with Auth0

You are able to take advantage of using a JWT signed with a private key to authenticate with Auth0 in place of using a client secret.

Note: you must upload the corresponding public key to your Auth0 tenant, so that Auth0 is able to verify the JWT signature.

Specify the client assertion key when creating the Auth0 client as in the following example:

key_string = File.read 'key.pem'
key = OpenSSL::PKey::RSA.new key_string

client = Auth0Client.new(
  domain: 'AUTH0_DOMAIN',
  client_id: 'AUTH0_CLIENT_ID',
  client_assertion_signing_key: key,
  client_assertion_signing_alg: 'RS256')

Some notes:

  • If both client_secret and client_assertion_signing_key are specified, client_assertion_signing_key takes precedence
  • client_assertion_signing_alg is optional and defaults to RS256 if omitted
  • Only RS256, RS384 and PS256 algorithms are supported by Auth0 currently