Create Rules
You can build your own rule(s) to support your specific functionality requirements. You can modify a pre-existing rule template or choose to start from scratch using one of our samples. Auth0 provides a number of pre-existing rules and rule templates to help you achieve your goal(s). To see a list, visit our rules repository on GitHub.
How rules work
Rules are JavaScript functions that execute when a user authenticates to your application. They run once the authentication process is complete, and you can use them to customize and extend Auth0's capabilities. For security reasons, your rules code executes isolated from the code of other Auth0 tenants in a sandbox. Rules also run during the token refresh flow. To learn more, read Refresh Tokens.
In Auth0, the authentication transaction flow works as follows when you use rules:
An app initiates an authentication request to Auth0.
Auth0 routes the request to an identity provider through a configured connection.
The user authenticates successfully.
The ID token and/or access token is passed through the rules pipeline, then sent to the application.
Prerequisite
If you plan to use global variables in your rule, be sure to configure your rules variables first. To learn more, read Configure Global Variables for Rules.
Use the Dashboard
Go to Dashboard > Auth Pipeline > Rules and click Create.
Select a rule template.
Name the rule, modify the script to suit your needs, and click Save changes.
Use the Management API
Make a POST
call to the Create Rule endpoint. Be sure to replace MGMT_API_ACCESS_TOKEN
, RULE_NAME
, RULE_SCRIPT
, RULE_ORDER
, and RULE_ENABLED
placeholder values with your Management API Access Token, rule name, rule script, rule order number, and rule enabled value, respectively.
curl --request POST \
--url 'https://{yourDomain}/api/v2/rules' \
--header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \
--header 'cache-control: no-cache' \
--header 'content-type: application/json' \
--data '{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }'
Was this helpful?
var client = new RestClient("https://{yourDomain}/api/v2/rules");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN");
request.AddHeader("cache-control", "no-cache");
request.AddParameter("application/json", "{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Was this helpful?
package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
)
func main() {
url := "https://{yourDomain}/api/v2/rules"
payload := strings.NewReader("{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("content-type", "application/json")
req.Header.Add("authorization", "Bearer MGMT_API_ACCESS_TOKEN")
req.Header.Add("cache-control", "no-cache")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}
Was this helpful?
HttpResponse<String> response = Unirest.post("https://{yourDomain}/api/v2/rules")
.header("content-type", "application/json")
.header("authorization", "Bearer MGMT_API_ACCESS_TOKEN")
.header("cache-control", "no-cache")
.body("{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }")
.asString();
Was this helpful?
var axios = require("axios").default;
var options = {
method: 'POST',
url: 'https://{yourDomain}/api/v2/rules',
headers: {
'content-type': 'application/json',
authorization: 'Bearer MGMT_API_ACCESS_TOKEN',
'cache-control': 'no-cache'
},
data: {name: 'RULE_NAME', script: 'RULE_SCRIPT'}
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
Was this helpful?
#import <Foundation/Foundation.h>
NSDictionary *headers = @{ @"content-type": @"application/json",
@"authorization": @"Bearer MGMT_API_ACCESS_TOKEN",
@"cache-control": @"no-cache" };
NSDictionary *parameters = @{ @"name": @"RULE_NAME",
@"script": @"RULE_SCRIPT" };
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/rules"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
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];
Was this helpful?
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://{yourDomain}/api/v2/rules",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }",
CURLOPT_HTTPHEADER => [
"authorization: Bearer MGMT_API_ACCESS_TOKEN",
"cache-control: no-cache",
"content-type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Was this helpful?
import http.client
conn = http.client.HTTPSConnection("")
payload = "{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }"
headers = {
'content-type': "application/json",
'authorization': "Bearer MGMT_API_ACCESS_TOKEN",
'cache-control': "no-cache"
}
conn.request("POST", "/{yourDomain}/api/v2/rules", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
Was this helpful?
require 'uri'
require 'net/http'
require 'openssl'
url = URI("https://{yourDomain}/api/v2/rules")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/json'
request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN'
request["cache-control"] = 'no-cache'
request.body = "{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }"
response = http.request(request)
puts response.read_body
Was this helpful?
import Foundation
let headers = [
"content-type": "application/json",
"authorization": "Bearer MGMT_API_ACCESS_TOKEN",
"cache-control": "no-cache"
]
let parameters = [
"name": "RULE_NAME",
"script": "RULE_SCRIPT"
] as [String : Any]
let postData = JSONSerialization.data(withJSONObject: parameters, options: [])
let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/rules")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
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()
Was this helpful?
Value | Description |
---|---|
MGMT_API_ACCESS_TOKEN |
Access Token for the Management API with the scope create:rules . |
RULE_NAME |
Name of the rule you would like to create. The rule name can only contain alphanumeric characters, spaces, and hyphens; it may not start or end with spaces or hyphens. |
RULE_SCRIPT |
Script that contains the code for the rule. Should match what you would enter if you were creating a new rule using the Dashboard. |
RULE_ORDER (optional) |
Integer that represents the order in which the rule should be executed in relation to other rules. Rules with lower numbers are executed before rules with higher numbers. If no order number is provided, the rule will execute last. |
RULE_ENABLED (optional) |
Boolean that represents whether the rules is enabled (true ) or disabled (false ). |
Manage rate limits
For rules that call Auth0 APIs, you should always handle rate limiting by checking the X-RateLimit-Remaining
header and acting appropriately when the number returned nears 0. You should also add logic to handle cases in which you exceed the provided rate limits and receive the HTTP Status Code 429 (Too Many Requests); in this case, if a retry is needed, it is best to allow for a back-off to avoid going into an infinite retry loop. To learn more about rate limits, read Rate Limit Policy For Auth0 APIs.
Available modules
Rules run in a JavaScript sandbox. The sandbox supports the ECMAScript 6 language and a large number of Node.js (version 8+) modules. For a list of supported sandbox modules, check out Can I require: Auth0 Extensibility.