Go

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • Go 1.8.2
Show requirements

This tutorial shows you how to use the authorization features in the OAuth 2.0 framework to limit access to your or third-party applications. For more information, read the API authorization documentation.

Create a Resource Server (API)

In the APIs section of the Auth0 dashboard, click Create API. Provide a name and an identifier for your API. You will use the identifier as an audience later, when you are configuring the access token verification. For Signing Algorithm, select RS256.

Create API

Add API Authorization

To restrict access to the resources served by your API, check the incoming requests for valid authorization information. The authorization information is stored in the access token created for the user and needs to be sent in the Authorization header. To see if the token is valid, check it against the JSON Web Key Set (JWKS) for your Auth0 account. To learn more about validating access tokens, read the Verify Access Tokens tutorial.

This sample demonstrates how to check for a JWT in the Authorization header of an incoming HTTP request and verify that it is valid. The validity check is done in the checkJwt middleware function which can be applied to any endpoints you wish to protect. If the token is valid, the resources which are served by the endpoint can be released, otherwise a 401 Authorization error will be returned.

Install the Dependencies

The go-jose package can be used to verify incoming JWTs. The go-auth0 library can be used alongside it to fetch your Auth0 public key and complete the verification process. Finally, we'll use the gorilla/mux package to handle our routes.

go get "gopkg.in/square/go-jose.v2"
go get "github.com/auth0-community/go-auth0"
go get "github.com/gorilla/mux"

Configuration

By default, your API will be set up to use RS256 as the algorithm for signing tokens. Since RS256 works by using a private/public keypair, tokens can be verified against the public key for your Auth0 account. This public key is accessible at https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json.

Configure the checkJwt middleware to use the remote JWKS for your Auth0 account.

// main.go
const JWKS_URI = "https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json"
const AUTH0_API_ISSUER = "https://YOUR_AUTH0_DOMAIN/"

var AUTH0_API_AUDIENCE = []string{"{YOUR_API_IDENTIFIER}"}

func checkJwt(h http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    client := auth0.NewJWKClient(auth0.JWKClientOptions{URI: JWKS_URI})
    audience := AUTH0_API_AUDIENCE

    configuration := auth0.NewConfiguration(client, audience, AUTH0_API_ISSUER, jose.RS256)
    validator := auth0.NewValidator(configuration)

    token, err := validator.ValidateRequest(r)

    if err != nil {
      fmt.Println("Token is not valid or missing token")

      response := Response{
        Message: "Missing or invalid token.",
      }

      w.WriteHeader(http.StatusUnauthorized)
      json.NewEncoder(w).Encode(response)

    } else {
      h.ServeHTTP(w, r)
    }
  })
}

Configuring Scopes

The checkJwt middleware above verifies that the access_token included in the request is valid; however, it doesn't yet include any mechanism for checking that the token has the sufficient scope to access the requested resources.

Scopes provide a way for you to define which resources should be accessible by the user holding a given access_token. For example, you might choose to permit read access to a messages resource if a user has a manager access level, or a write access to that resource if they are an administrator.

To configure scopes in your Auth0 dashboard, navigate to your API and choose the Scopes tab. In this area you can apply any scopes you wish, including one called read:messages, which will be used in this example.

Let's extend our backend to check and ensure the access_token has the correct scope before returning a successful response.

// main.go
func checkScope(r *http.Request, validator *auth0.JWTValidator, token *jwt.JSONWebToken) bool {
  claims := map[string]interface{}{}
  err := validator.Claims(r, token, &claims)

  if err != nil {
    fmt.Println(err)
    return false
  }

  if strings.Contains(claims["scope"].(string), "read:messages") {
    return true
  } else {
    return false
  }
}

Next, let's implement this checkScope function in our middleware. We'll omit the redundent code from above.

// main.go
func checkJwt(h http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    // Validate the access_token
    if err != nil {
      // Handle invalid token case
    } else {
      // Ensure the token has the correct scope
      result := checkScope(r, validator, token)
      if result == true {
        // If the token is valid and we have the right scope, we'll pass through the middleware
        h.ServeHTTP(w, r)
      } else {
        response := Response{
          Message: "You do not have the read:messages scope.",
      }
        w.WriteHeader(http.StatusUnauthorized)
        json.NewEncoder(w).Encode(response)
      }
    }
  })
}

Protect Individual Endpoints

Individual routes can now be protected with the checkJwt middleware. Below is an example showing two routes, one which is publicaly accessible, and one that is protected with the checkJwt middlewware. The protected route will require both a valid access_token and the read:messages scope before returning the requested resource.

// main.go
func main() {
  r := mux.NewRouter()

  // This route is always accessible
  r.Handle("/api/public", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    response := Response{
      Message: "Hello from a public endpoint! You don't need to be authenticated to see this.",
    }
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(response)
  }))

  // This route is only accessible if the user has a valid access_token with the read:messages scope
  // We are wrapping the checkJwt middleware around the handler function which will check for a
  // valid token and scope.
  r.Handle("/api/private", checkJwt(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    response := Response{
      Message: "Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this.",
    }
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(response)
  })))
}

In our example we only checked for the read:messages scope. You may want to extend the checkScope function or make it a standalone middleware that accepts multiple roles to fit your use case.

Make a Call to Your API

To make calls to your API, you need an access token. You can get an access token for testing purposes from the test lab in your API settings.

Obtain a JWT

Provide the access token as an Authorization header in your requests.


curl --request GET \
  --url http://your-domain.com/api_path \
  --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
var client = new RestClient("http://your-domain.com/api_path");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE");
IRestResponse response = client.Execute(request);
package main

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

func main() {

	url := "http://your-domain.com/api_path"

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

	req.Header.Add("authorization", "Bearer YOUR_ACCESS_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://your-domain.com/api_path")
  .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")
  .asString();
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://your-domain.com/api_path",
  "method": "GET",
  "headers": {
    "authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"
  }
}

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

var options = { method: 'GET',
  url: 'http://your-domain.com/api_path',
  headers: { authorization: 'Bearer YOUR_ACCESS_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_ACCESS_TOKEN_HERE" };

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://your-domain.com/api_path"]
                                                       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_URL => "http://your-domain.com/api_path",
  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_ACCESS_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("your-domain.com")

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

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

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

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

url = URI("http://your-domain.com/api_path")

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

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

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

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

var request = NSMutableURLRequest(URL: NSURL(string: "http://your-domain.com/api_path")!,
                                        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()

Use Auth0 for FREECreate free Account