ASP.NET Core Web API Using your API

Version: v2.0

Calling the API from your application

You can call the API from your client application by passing an access token in the Authorization header of your HTTP request as a Bearer token.


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

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

func main() {

	url := "http://localhost:3010/api/private"

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

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

	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:3010/api/private")
  .header("authorization", "Bearer YOUR_ACCESS_TOKEN")
  .asString();
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:3010/api/private",
  "method": "GET",
  "headers": {
    "authorization": "Bearer YOUR_ACCESS_TOKEN"
  }
}

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

var options = { method: 'GET',
  url: 'http://localhost:3010/api/private',
  headers: { authorization: 'Bearer YOUR_ACCESS_TOKEN' } };

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" };

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:3010/api/private"]
                                                       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 => "3010",
  CURLOPT_URL => "http://localhost:3010/api/private",
  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"
  ),
));

$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:3010")

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

conn.request("GET", "/api/private", headers=headers)

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

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

url = URI("http://localhost:3010/api/private")

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

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

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

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

var request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:3010/api/private")!,
                                        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()

The exact implementation will be dependent on the type of application you are developing and the framework you are using. For more information refer to the relevant client Quickstarts which contain detailed instructions:

Obtaining an access token for testing

If you want to test your API outside your application, for example from the command line or a tool like Postman, you can obtain an access token using the Authentication API Debugger Extension or from the Test tab in your API settings.

You can also obtain an access token using cUrl by using the Client Credentials or Resource Owner Password authorization flows.

1. Using Client Credentials

curl --request POST \
  --url 'https://YOUR_AUTH0_DOMAIN/oauth/token' \
  --header 'content-type: application/json' \
  --data '{ "client_id":"YOUR_CLIENT_ID", "client_secret": "YOUR_CLIENT_SECRET", "audience": "YOUR_API_AUDIENCE", "grant_type": "client_credentials" }'

2. Using Resource Owner Password

curl --request POST \
  --url 'https://YOUR_AUTH0_DOMAIN/oauth/token' \
  --header 'content-type: application/json' \
  --data '{ "client_id":"YOUR_CLIENT_ID", "client_secret": "YOUR_CLIENT_SECRET", "audience": "YOUR_API_AUDIENCE", "grant_type": "password", "username": "USERNAME", "password": "PASSWORD", "scope": "SCOPE" }'

Test Your API with cURL

You can test your API using cURL using an access token you obtained before.

1. Calling the secure endpoint

You can make a request to the /api/private endpoint without passing any access token:

curl -i http://localhost:3010/api/private

The API will return a 401 HTTP (Unauthorized) status code:

Response for unauthorized API request

Once again, make the same request but this time pass along the access token as a Bearer token in the Authorization header of the request:

curl -i http://localhost:3010/api/private \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

This time the API will return a successful response:

Response for authorized API request

2. Testing the scoped endpoint

To test the endpoint that require a scope, pass the access token containing the correct scope as a Bearer token in the Authorization header:

curl -i http://localhost:3010/api/private-scoped \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

If the required scope is present, the API call is successful:

Response for scoped API request

If the required scope is not present, the API returns a 403 HTTP Status (Forbidden):

Response for forbidden scoped API request

Previous Tutorial
1. Authorization
Next Tutorial
3. Troubleshooting
Use Auth0 for FREECreate free Account