Ruby On Rails API

Sample Project

Download this sample project configured with your Auth0 API Keys.

System Requirements
  • Ruby 2.1.8
  • Rails 4.2.5.1
Show requirements

1. Setup the knock gem

Add this line to your application's Gemfile:

Install

gem 'knock', '~> 2.0'

And then execute:

bundle install

Finally, run the install generator:

rails generate knock:install

It will create the following initializer config/initializers/knock.rb. This file contains all the information about the existing configuration options.

Usage

Then include the Knock::Authenticable module in your ApplicationController

class ApplicationController < ActionController::Base
  include Knock::Authenticable
end

You can now protect your resources by adding the authenticate_user before_action to your controllers like this:

class SecuredResourceController < ApplicationController
  before_action :authenticate_user

  def index
    # etc...
  end

  # etc...
end

If no valid token is passed with the request, Knock will respond with:

head :unauthorized

If a token is given, Knock makes two assumptions by default:

  1. Your app defines a User model with an id field.
  2. The 'sub' claim in the token payload contains the user id.

To retrieve the current user you should implement within your entity model a class method from_token_payload that takes the payload in argument:

class User < ActiveRecord::Base
  def self.from_token_payload payload
    # Returns a valid user, `nil` or raise
    # e.g.
    #   self.find payload["sub"]
  end
end

2. Add your Auth0 account information to secrets.yml

You need to set the ClientID and ClientSecret in config/secrets.yml file so they can be used to validate and sign JWTs for you.

development:
  secret_key_base: 3342e9faedd8fe9ea360c0af568d00a46917923791c23e144d66849b272d2ff63e743f9bb209dab7d6e732bb5f919e46e3fe552b8919140805bb89c346e68876,
  auth0_client_id: YOUR_CLIENT_ID
  auth0_client_secret: YOUR_CLIENT_SECRET

production:
  secret_key_base: ENV["SECRET_KEY_BASE"]
  auth0_client_id: YOUR_CLIENT_ID
  auth0_client_secret: YOUR_CLIENT_SECRET

Warning: If you share your code, you should use environment variable to protect your ClientID and ClientSecret.

3. Tell knock to use your Auth0 account information

In config/initializer/knock.rb, uncomment the following lines:

config.token_audience = -> { Rails.application.secrets.auth0_client_id }
config.token_secret_signature_key = -> { JWT.base64url_decode Rails.application.secrets.auth0_client_secret }

4. Call Your API

You can now make requests against your secure API by providing the Authorization header in your requests with a valid JWT id_token.


curl --request GET \
  --url http://localhost:8000/path_to_your_api \
  --header 'authorization: Bearer YOUR_ID_TOKEN_HERE'
var client = new RestClient("http://localhost:8000/path_to_your_api");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer YOUR_ID_TOKEN_HERE");
IRestResponse response = client.Execute(request);
package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
)

func main() {

	url := "http://localhost:8000/path_to_your_api"

	req, _ := http.NewRequest("GET", url, nil)

	req.Header.Add("authorization", "Bearer YOUR_ID_TOKEN_HERE")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
HttpResponse<String> response = Unirest.get("http://localhost:8000/path_to_your_api")
  .header("authorization", "Bearer YOUR_ID_TOKEN_HERE")
  .asString();
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:8000/path_to_your_api",
  "method": "GET",
  "headers": {
    "authorization": "Bearer YOUR_ID_TOKEN_HERE"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
var request = require("request");

var options = { method: 'GET',
  url: 'http://localhost:8000/path_to_your_api',
  headers: { authorization: 'Bearer YOUR_ID_TOKEN_HERE' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
#import <Foundation/Foundation.h>

NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ID_TOKEN_HERE" };

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/path_to_your_api"]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
[request setHTTPMethod:@"GET"];
[request setAllHTTPHeaderFields:headers];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error) {
                                                    NSLog(@"%@", error);
                                                } else {
                                                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                    NSLog(@"%@", httpResponse);
                                                }
                                            }];
[dataTask resume];
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_PORT => "8000",
  CURLOPT_URL => "http://localhost:8000/path_to_your_api",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "authorization: Bearer YOUR_ID_TOKEN_HERE"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
import http.client

conn = http.client.HTTPConnection("localhost:8000")

headers = { 'authorization': "Bearer YOUR_ID_TOKEN_HERE" }

conn.request("GET", "/path_to_your_api", headers=headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))
require 'uri'
require 'net/http'

url = URI("http://localhost:8000/path_to_your_api")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Get.new(url)
request["authorization"] = 'Bearer YOUR_ID_TOKEN_HERE'

response = http.request(request)
puts response.read_body
import Foundation

let headers = ["authorization": "Bearer YOUR_ID_TOKEN_HERE"]

var request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8000/path_to_your_api")!,
                                        cachePolicy: .UseProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.HTTPMethod = "GET"
request.allHTTPHeaderFields = headers

let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    println(error)
  } else {
    let httpResponse = response as? NSHTTPURLResponse
    println(httpResponse)
  }
})

dataTask.resume()

5. You're done!

Now you have both your FrontEnd and Backend configured to use Auth0. Congrats, you're awesome!

Optional Steps

Configure CORS

In order to configure CORS, install rack-cors gem and follow these instructions.

Use Auth0 for FREECreate free Account