ASP.NET Web API

ASP.NET Web API Tutorial

Download a sample project.

Otherwise, please follow the steps below to configure your existing ASP.NET Web API app to use it with Auth0.

System Requirements

This tutorial and seed project have been tested with the following:

  • MicroSoft Visual Studio 2015
  • WebApi.JsonWebToken NuGet Package v0.2.0
  • Auth0-ASPNET NuGet Package v1.4.0
  • Microsoft.AspNet.WebApi.Cors NuGet Package v5.2.3

1. Install the WebApi.JsonWebToken & Auth0-ASPNET packages

You can either run the following commands or install them via Package Manager.

Install-Package WebApi.JsonWebToken
Install-Package Auth0-ASPNET

2. Configure the JsonWebToken message handler

Open the WebApiConfig.cs file located in the App_Start folder and add the following using statements:

using YOUR_WEBAPI_PROJECT_NAME.App_Start;
using System.Web.Configuration;

Remember to replace the placeholder for your project name in the first using statement.

Add the following code snippet inside the Register method.

var clientID = WebConfigurationManager.AppSettings["auth0:ClientId"];
var clientSecret = WebConfigurationManager.AppSettings["auth0:ClientSecret"];

config.MessageHandlers.Add(new JsonWebTokenValidationHandler()
{
    Audience = clientID,
    SymmetricKey = clientSecret
});

3. Update the web.config file with your app's credentials

Open the Web.config file located at the project's root.

Locate the following entries inside the <appSettings> section.

<add key="auth0:ClientId" value="YOUR_CLIENT_ID" />
<add key="auth0:ClientSecret" value="YOUR_CLIENT_SECRET" />

Set the respective values.

4. Securing your API

All you need to do now is add the [System.Web.Http.Authorize] attribute to the controllers/actions for which you want to verify that users are authenticated.

5. Call Your API

You can now make requests against your secure API by providing the Authorization header in your requests with a valid JWT id_token.


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

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

func main() {

	url := "http://localhost:8000/path_to_your_api"

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

	req.Header.Add("authorization", "Bearer YOUR_ID_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://localhost:8000/path_to_your_api")
  .header("authorization", "Bearer YOUR_ID_TOKEN_HERE")
  .asString();
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:8000/path_to_your_api",
  "method": "GET",
  "headers": {
    "authorization": "Bearer YOUR_ID_TOKEN_HERE"
  }
}

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

var options = { method: 'GET',
  url: 'http://localhost:8000/path_to_your_api',
  headers: { authorization: 'Bearer YOUR_ID_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_ID_TOKEN_HERE" };

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/path_to_your_api"]
                                                       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 => "8000",
  CURLOPT_URL => "http://localhost:8000/path_to_your_api",
  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_ID_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("localhost:8000")

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

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

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

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

url = URI("http://localhost:8000/path_to_your_api")

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

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

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

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

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

6. You're done!

Now you have both your FrontEnd and Backend configured to use Auth0. Congrats, you're awesome!

Optional Steps

Configuring CORS

One of the requirements is package Microsoft.AspNet.WebApi.Cors. You can use the following command from VS2013 Package Manager Console:

Install-Package Microsoft.AspNet.WebApi.Cors

For more details, you can follow this article to configure CORS in your application.

Try Auth0 for FREECreate free Account