Add Authorization to Your Go Application
This guide demonstrates how to integrate Auth0 with any new or existing Go API application using the go-jwt-middleware package.
If you have not created an API in your Auth0 dashboard yet, use the interactive selector to create a new Auth0 API or select an existing API for your project.
To set up your first API through the Auth0 dashboard, review our getting started guide.
Each Auth0 API uses the API Identifier, which your application needs to validate the access token.
Permissions let you define how resources can be accessed on behalf of the user with a given access token. For example, you might choose to grant read access to the messages
resource if users have the manager access level, and a write access to that resource if they have the administrator access level.
You can define allowed permissions in the Permissions view of the Auth0 Dashboard's APIs section. The following example uses the read:messages
scope.
![Auth0 Dashboard> Applications > APIs > [Specific API] > Permissions tab](http://images.ctfassets.net/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/e61793a2822d095666002c3f65c71ac2/configure-permissions.png)
Add a go.mod
file to list all the necessary dependencies.
// go.mod
module 01-Authorization-RS256
go 1.21
require (
github.com/auth0/go-jwt-middleware/v2 v2.2.0
github.com/joho/godotenv v1.5.1
)
feedbackSection.helpful
Download dependencies by running the following shell command:
go mod download
feedbackSection.helpful
Create a .env
file within the root of your project directory to store the app configuration. Then, fill in the environment variables:
# The URL of our Auth0 Tenant Domain.
If you're using a Custom Domain, be sure to set this to that value instead.
AUTH0_DOMAIN='{yourDomain}'
Our Auth0 API's Identifier.
AUTH0_AUDIENCE='{yourApiIdentifier}'
feedbackSection.helpful
The EnsureValidToken
middleware function validates the access token. You can apply this function to any endpoints you wish to protect. If the token is valid, the endpoint releases the resources. If the token is not valid, the API returns a 401 Authorization
error.
Set up the go-jwt-middleware middleware to verify access tokens from incoming requests.
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://{yourDomain}/.well-known/jwks.json
.
Include a mechanism to check that the token has sufficient scope to access the requested resources.
Create a function HasScope
to check and ensure the access token has the correct scope before returning a successful response.
In this example, create an /api/public
endpoint that does not use the EnsureToken
middleware as it is accessible to non-authenticated requests.
Create an /api/private
endpoint that requires the EnsureToken
middleware as it is only available to authenticated requests containing an access token with no additional scope.
Create an /api/private-scoped
endpoint that requires the EnsureToken
middleware and HasScope
as it is only available for authenticated requests containing an access token with the read:messages
scope granted.
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 view in your API settings.
![Auth0 Dashboard> Applications > API > [Specific API] > Test tab](http://images.ctfassets.net/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/5e79037f6c852d2043789d622bdb9562/Quickstart_Example_App_-_English.png)
Provide the Access Token as an Authorization
header in your requests.
curl --request get \
--url 'http:///{yourDomain}/api_path' \
--header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
feedbackSection.helpful
var client = new RestClient("http:///{yourDomain}/api_path");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE");
IRestResponse response = client.Execute(request);
feedbackSection.helpful
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
url := "http:///{yourDomain}/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))
}
feedbackSection.helpful
HttpResponse<String> response = Unirest.get("http:///{yourDomain}/api_path")
.header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")
.asString();
feedbackSection.helpful
var axios = require("axios").default;
var options = {
method: 'get',
url: 'http:///{yourDomain}/api_path',
headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'}
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
feedbackSection.helpful
#import <Foundation/Foundation.h>
NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" };
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///{yourDomain}/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];
feedbackSection.helpful
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http:///{yourDomain}/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 => [
"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;
}
feedbackSection.helpful
import http.client
conn = http.client.HTTPConnection("")
headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" }
conn.request("get", "/{yourDomain}/api_path", headers=headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
feedbackSection.helpful
require 'uri'
require 'net/http'
url = URI("http:///{yourDomain}/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
feedbackSection.helpful
import Foundation
let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"]
let request = NSMutableURLRequest(url: NSURL(string: "http:///{yourDomain}/api_path")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "get"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
feedbackSection.helpful
checkpoint.header
Now that you have configured your application, run your application and verify that:
GET /api/public
is available for non-authenticated requests.GET /api/private
is available for authenticated requests.GET /api/private-scoped
is available for authenticated requests containing an access token with theread:messages
scope.
Next Steps
Excellent work! If you made it this far, you should now have login, logout, and user profile information running in your application.
This concludes our quickstart tutorial, but there is so much more to explore. To learn more about what you can do with Auth0, check out:
- Auth0 Dashboard - Learn how to configure and manage your Auth0 tenant and applications
- go-jwt-middleware SDK - Explore the SDK used in this tutorial more fully
- Auth0 Marketplace - Discover integrations you can enable to extend Auth0’s functionality
Sign up for an or to your existing account to integrate directly with your own tenant.