ASP.NET Core Web API: Authorization
Sample Project
Download a sample project specific to this tutorial configured with your Auth0 API Keys.
- .NET Core 1.1
- ASP.NET Core 1.1
- Microsoft.AspNetCore.Authentication.JwtBearer 1.1.1
- Visual Studio 2017 (Optional)
- Visual Studio Code (Optional)
This tutorial shows you how to use the authorization features in the OAuth 2.0 framework to limit access to your or third-party applications. For more information, read the API authorization documentation.
This Quickstart will guide you through the various tasks related to using Auth0-issued Access Tokens to secure your ASP.NET Core Web API.
Seed and Samples
If you would like to follow along with this Quickstart you can download the seed project. The seed project is just a basic ASP.NET Web API with a simple controller and some of the NuGet packages which will be needed included. It also contains an appSettings.json
file where you can configure the various Auth0-related settings for your application.
The final project after each of the steps is also available in the Quickstart folder of the Samples repository. You can find the final result for each step in the relevant folder inside the repository.
Create a Resource Server (API)
In the APIs section of the Auth0 dashboard, click Create API. Provide a name and an identifier for your API, for example https://quickstarts/api
. You will use the identifier as an audience
later, when you are configuring the Access Token verification. For Signing Algorithm, select RS256.
Also, update the appsettings.json
file in your project with the correct Domain and API Identifier for your API, such as
{
"Auth0": {
"Domain": "YOUR_AUTH0_DOMAIN",
"ApiIdentifier": "{YOUR_API_IDENTIFIER}"
}
}
To restrict access to the resources served by your API, check the incoming requests for valid authorization information.
The authorization information is stored in the Access Token created for the user and needs to be sent in the Authorization
header. To see if the token is valid, check it against the JSON Web Key Set (JWKS) for your Auth0 account. To learn more about validating Access Tokens, read the Verify Access Tokens tutorial.
This example demonstrates:
- How to check for a JSON Web Token (JWT) in the
Authorization
header of an incoming HTTP request - How to check if the token is valid with the standard ASP.NET Core JWT middleware
Install Dependencies
To use Auth0 Access Tokens with ASP.NET Core you will use the JWT Middleware. Add the Microsoft.AspNetCore.Authentication.JwtBearer
package to your application.
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
Configuration
By default, your API uses RS256 as the algorithm for signing tokens. Since RS256 uses a private/public keypair, it verifies the tokens against the public key for your Auth0 account. You can access this public key here.
The ASP.NET Core JWT middleware will handle downloading the JSON Web Key Set (JWKS) file containing the public key for you, and will use that to verify the access_token
signature.
To add the JWT middleware to your application's middleware pipeline, go to the Configure
method of your Startup
class and add a call to UseJwtBearerAuthentication
passing in the configured JwtBearerOptions
. The JwtBearerOptions
needs to specify your Auth0 API Identifier as the Audience
, and the full path to your Auth0 domain as the Authority
:
// Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
var options = new JwtBearerOptions
{
Audience = Configuration["Auth0:ApiIdentifier"],
Authority = $"https://{Configuration["Auth0:Domain"]}/"
};
app.UseJwtBearerAuthentication(options);
app.UseMvc();
}
The JWT middleware integrates with the standard ASP.NET Core Authentication and Authorization mechanisms. To secure an endpoint you only need to decorate your controller action with the [Authorize]
attribute:
// Controllers/ApiController.cs
[Route("api")]
public class ApiController : Controller
{
[HttpGet]
[Route("private")]
[Authorize]
public IActionResult Private()
{
return Json(new
{
Message = "Hello from a private endpoint! You need to be authenticated to see this."
});
}
}
Configuring Scopes
The JWT middleware above verifies that the access_token
included in the request is valid; however, it doesn't yet include any mechanism for checking that the token has the sufficient scope to access the requested resources.
Scopes let you define which resources can be accessed by the user with a given Access Token. For example, you might choose to give the read access to the messages
resource if a user has the manager access level, and a write access to that resource if they have the administrator access level.
To configure scopes, in your Auth0 dashboard, in the APIs section, click the Scopes tab. Configure the scopes you need.
To make sure that an Access Token contains the correct scope, use the Policy-Based Authorization in ASP.NET Core.
Create a new Authorization Requirement called HasScopeRequirement
. This requirement will check that the scope
claim issued by your Auth0 tenant is present, and if so it will ensure that the scope
claim contains the requested scope. If it does then the Authorization Requirement is met.
// HasScopeRequirement.cs
public class HasScopeRequirement : AuthorizationHandler<HasScopeRequirement>, IAuthorizationRequirement
{
private readonly string issuer;
private readonly string scope;
public HasScopeRequirement(string scope, string issuer)
{
this.scope = scope;
this.issuer = issuer;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)
{
// If user does not have the scope claim, get out of here
if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == issuer))
return Task.CompletedTask;
// Split the scopes string into an array
var scopes = context.User.FindFirst(c => c.Type == "scope" && c.Issuer == issuer).Value.Split(' ');
// Succeed if the scope array contains the required scope
if (scopes.Any(s => s == scope))
context.Succeed(requirement);
return Task.CompletedTask;
}
}
Next, you can define a policy for each of the scopes in your application in the ConfigureServices
method of your Startup
class:
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
string domain = $"https://{Configuration["Auth0:Domain"]}/";
services.AddAuthorization(options =>
{
options.AddPolicy("read:messages",
policy => policy.Requirements.Add(new HasScopeRequirement("read:messages", domain)));
});
}
To secure the API endpoint, we need to make sure that the correct scope is present in the access_token
. To do that, add the Authorize
attribute to the Scoped
action, passing read:messages
as the policy
parameter.
// Controllers/ApiController.cs
[Route("api")]
public class ApiController : Controller
{
[HttpGet]
[Route("private-scoped")]
[Authorize("read:messages")]
public IActionResult Scoped()
{
return Json(new
{
Message = "Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this."
});
}
}
Further Reading
-
To learn how you can call your API from applications, please refer to the Using your API section.
-
If your experience problems with your API, please refer to the Troubleshooting section.