This tutorial performs access token validation using the jwt Gem within a custom Auth0Client class. A Concern called Secured is used to authorize endpoints which require authentication through an incoming access token.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.
New to Auth0? Learn how Auth0 works and read about implementing API authentication and authorization using the OAuth 2.0 framework.
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.
This example uses the read:messages scope.
Install the **jwt **Gem.
gem
'jwt'
bundle install
Create a class called Auth0Client. This class decodes and verifies the incoming access token taken from the Authorization header of the request.The Auth0Client class retrieves the public key for your Auth0 tenant and then uses it to verify the signature of the access token. The Token struct defines a validate_permissions method to look for a particular scope in an access token by providing an array of required scopes and check if they are present in the payload of the token.Create a Concern called Secured which looks for the access token in the Authorization header of an incoming request.If the token is present, the Auth0Client.validate_token will use the jwt Gem to verify the token’s signature and validate the token’s claims.In addition to verifying that the access token is valid, the Concern also includes a mechanism for confirming the token has the sufficient scope to access the requested resources. In this example we define a validate_permissions method that receives a block and checks the permissions by calling the Token.validate_permissions method from the Auth0Client class.For the /private-scoped route, the scopes defined will be intersected with the scopes coming in the payload, to determine if it contains one or more items from the other array.By adding the Secure concern to your application controller, you’ll only need to use a before_action filter in the controller that requires authorization.Create a controller to handle the public endpoint /api/public.The /public endpoint does not require any authorization so no before_action is needed.Create a controller to handle the private endpoints: /api/private and /api/private-scoped./api/private is available for authenticated requests containing an access token with no additional scopes./api/private-scoped is available for authenticated requests containing an access token with the read:messages scope grantedThe protected endpoints need to call the authorize method from the Secured concern, for that you use before_action :authorize, this ensure the Secured.authorize method is called before every action in the PrivateController.

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.Provide the Access Token as an Authorization header in your requests.
Tab panes
curl --request get \
--url 'http:///{yourDomain}/api_path' \
--header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
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
)
;
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
)
)
}
HttpResponse
<
String
>
response
=
Unirest
.
get
(
"http:///{yourDomain}/api_path"
)
.
header
(
"authorization"
,
"Bearer YOUR_ACCESS_TOKEN_HERE"
)
.
asString
(
)
;
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
)
;
}
)
;
#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(@&quot;%@&quot;, error);

                                            } else {

                                                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;

                                                NSLog(@&quot;%@&quot;, httpResponse);

                                            }

                                        }];

[dataTask resume];
$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
=>
[
&
quot
;
authorization
:
Bearer
YOUR_ACCESS_TOKEN_HERE
&
quot
;
]
,
]
)
;
$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
(
""
)
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"
)
)
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
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
(
)
Checkpoint
Now that you have configured your application, run your application to verify that:
  • GET /api/publicis available for non-authenticated requests.
  • GET /api/privateis available for authenticated requests.
  • GET /api/private-scopedis available for authenticated requests containing an Access Token with the read:messagesscope.
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:Did it work?Any suggestion or typo?
1

Define permissions

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.
This example uses the read:messages scope.
2

Install dependencies

Install the **jwt **Gem.
gem
'jwt'
bundle install
3

Create an Auth0Client class

Create a class called Auth0Client. This class decodes and verifies the incoming access token taken from the Authorization header of the request.The Auth0Client class retrieves the public key for your Auth0 tenant and then uses it to verify the signature of the access token. The Token struct defines a validate_permissions method to look for a particular scope in an access token by providing an array of required scopes and check if they are present in the payload of the token.
4

Define a Secured concern

Create a Concern called Secured which looks for the access token in the Authorization header of an incoming request.If the token is present, the Auth0Client.validate_token will use the jwt Gem to verify the token’s signature and validate the token’s claims.In addition to verifying that the access token is valid, the Concern also includes a mechanism for confirming the token has the sufficient scope to access the requested resources. In this example we define a validate_permissions method that receives a block and checks the permissions by calling the Token.validate_permissions method from the Auth0Client class.For the /private-scoped route, the scopes defined will be intersected with the scopes coming in the payload, to determine if it contains one or more items from the other array.
5

Include the Secure concern in your ApplicationController

By adding the Secure concern to your application controller, you’ll only need to use a before_action filter in the controller that requires authorization.
6

Create the public endpoint

Create a controller to handle the public endpoint /api/public.The /public endpoint does not require any authorization so no before_action is needed.
7

Create the private endpoints

Create a controller to handle the private endpoints: /api/private and /api/private-scoped./api/private is available for authenticated requests containing an access token with no additional scopes./api/private-scoped is available for authenticated requests containing an access token with the read:messages scope grantedThe protected endpoints need to call the authorize method from the Secured concern, for that you use before_action :authorize, this ensure the Secured.authorize method is called before every action in the PrivateController.

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.Provide the Access Token as an Authorization header in your requests.
Tab panes
curl --request get \
--url 'http:///{yourDomain}/api_path' \
--header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
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
)
;
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
)
)
}
HttpResponse
<
String
>
response
=
Unirest
.
get
(
"http:///{yourDomain}/api_path"
)
.
header
(
"authorization"
,
"Bearer YOUR_ACCESS_TOKEN_HERE"
)
.
asString
(
)
;
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
)
;
}
)
;
#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(@&quot;%@&quot;, error);

                                            } else {

                                                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;

                                                NSLog(@&quot;%@&quot;, httpResponse);

                                            }

                                        }];

[dataTask resume];
$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
=>
[
&
quot
;
authorization
:
Bearer
YOUR_ACCESS_TOKEN_HERE
&
quot
;
]
,
]
)
;
$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
(
""
)
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"
)
)
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
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
(
)
Checkpoint
Now that you have configured your application, run your application to verify that:
  • GET /api/publicis available for non-authenticated requests.
  • GET /api/privateis available for authenticated requests.
  • GET /api/private-scopedis available for authenticated requests containing an Access Token with the read:messagesscope.