A demo API to show how to use JWTs for authorization in .NET APIs.
The code uses the JWT Bearer Middleware and Policy Based Authorization.
The API uses an appSettings.json
file to configure its expected issuer, audience and JWT signing algorithm:
{
"Authorization": {
"Issuer": "https://login.example.com/oauth/v2/oauth-anonymous",
"Audience": "demo-api",
"Algorithm": "RS256"
}
}
Before running the app you need to configure an authorization server like a local Docker instance of the Curity Identity Server:
- Run a local Docker instance.
- Use the token designer to configure scopes and claims.
- Create a client that gets an access token to send to the API.
Ensure that an up to date .NET SDK is installed, then run the example.
Use developer-specific settings if required, such as the use of HTTP OAuth URLs.
export ASPNETCORE_ENVIRONMENT='Development'
dotnet build
dotnet run
The configuration uses a local example domain for the authorization server.
To use such a domain, add the following entry to your local computer's hosts file:
127.0.0.1 login.example.com
You can then act as an OAuth client to get an access token and call the API.
The following endpoint returns normal sensitivity data and requires a read
scope:
curl -i http://localhost:5000/demo/data -H "Authorization: Bearer $ACCESS_TOKEN"
The following endpoint return higher sensitivity data and also requires a custom risk
claim with a value below 50.
Such a claim might originate from an external system like a risk engine.
curl -i http://localhost:5000/demo/highworthdata -H "Authorization: Bearer $ACCESS_TOKEN"
To run the API in a Docker container, execute the deployment script:
./deployment/run.sh
- See the .NET API Tutorial for further details on the example API's security behavior.
- See the JWT Best Practices article for further information on using JWTs securely.