AddJwtBearer understanding its purpose
The purpose of using AddJwtBearer is to secure your API endpoint (the ones decorated with Authorization attribute) and setting those constraints for example audience must have certain value before it can access your API.
In example configuration below, we only allow JWT token with audience "https://kepungapp.auth0.com/api/v2/" access. All other request will get 401.
You need to setup options.Authority and it must be a valid token issuer.
builder.Services.AddAuthentication()
.AddJwtBearer(options =>
{
options.Audience = "https://kepungapp.auth0.com/api/v2/";
options.Authority = "https://kepungapp.auth0.com/";
//options.RequireHttpsMetadata = false;
});
If you run the following curl it will work and get a 200 response from /hello endpoint.
curl --location --request GET 'http://localhost:5019/hello' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlFUTXlRMEZCUWpFM1JUUkRRekV6UVRKR1FqYzBSVGsxTkRaR016aEZSamc1TXpORU1UaENRdyJ9.eyJpc3MiOiJodHRwczovL2tlcHVuZ2FwcC5hdXRoMC5jb20vIiwic3ViIjoiZklqTzdGaWdndUkxVlNtc01vcjREQ1FwRXdIYm5uVm9AY2xpZW50cyIsImF1ZCI6Imh0dHBzOi8va2VwdW5nYXBwLmF1dGgwLmNvbS9hcGkvdjIvIiwiaWF0IjoxNzE1MTU5MDc2LCJleHAiOjE3MTUxNTk1NzYsInNjb3BlIjoicmVhZDpjbGllbnRfZ3JhbnRzIGNyZWF0ZTpjbGllbnRfZ3JhbnRzIGRlbGV0ZTpjbGllbnRfZ3JhbnRzIHVwZGF0ZTpjbGllbnRfZ3JhbnRzIHJlYWQ6dXNlcnMgdXBkYXRlOnVzZXJzIGRlbGV0ZTp1c2VycyBjcmVhdGU6dXNlcnMgcmVhZDp1c2Vyc19hcHBfbWV0YWRhdGEgdXBkYXRlOnVzZXJzX2FwcF9tZXRhZGF0YSBkZWxldGU6dXNlcnNfYXBwX21ldGFkYXRhIGNyZWF0ZTp1c2Vyc19hcHBfbWV0YWRhdGEgcmVhZDp1c2VyX2N1c3RvbV9ibG9ja3M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W9uc19zdW1tYXJ5IGNyZWF0ZTphY3Rpb25zX2xvZ19zZXNzaW9ucyBjcmVhdGU6YXV0aGVudGljYXRpb25fbWV0aG9kcyByZWFkOmF1dGhlbnRpY2F0aW9uX21ldGhvZHMgdXBkYXRlOmF1dGhlbnRpY2F0aW9uX21ldGhvZHMgZGVsZXRlOmF1dGhlbnRpY2F0aW9uX21ldGhvZHMgcmVhZDpzY2ltX2NvbmZpZyBjcmVhdGU6c2NpbV9jb25maWcgdXBkYXRlOnNjaW1fY29uZmlnIGRlbGV0ZTpzY2ltX2NvbmZpZyBjcmVhdGU6c2NpbV90b2tlbiByZWFkOnNjaW1fdG9rZW4gZGVsZXRlOnNjaW1fdG9rZW4gcmVhZDpjbGllbnRfY3JlZGVudGlhbHMgY3JlYXRlOmNsaWVudF9jcmVkZW50aWFscyB1cGRhdGU6Y2xpZW50X2NyZWRlbnRpYWxzIGRlbGV0ZTpjbGllbnRfY3JlZGVudGlhbHMiLCJndHkiOiJjbGllbnQtY3JlZGVudGlhbHMiLCJhenAiOiJmSWpPN0ZpZ2d1STFWU21zTW9yNERDUXBFd0hibm5WbyJ9.hZEERX7eN8TU7H0jgybhkrJjXGRVVsWB2C7oVPMhuSHEHlM0DSeQB-QuQDZJtoL0ULb7xE40QwkUELlY29hOFvR_mtxFbsvMGPBOlRv6NoMwW1Ko1ief-pB4hZ4FP3GCZaEawY2dpaSqlj6f6gIZJ_gQkUKQb9UpaJYbZDJTMxlXx6MmmM6200nxfqEthhb7ojeMa8UonfPRPAmhLHGBENP-VCvjEkD-kzAbtecXNXAdKufkpakC0QhXB6vMcK2MjdgQgPQ7FEvannUOXYl51-6s6CjJhWLeKk6ZUAauo3AuUJ2BLz4qPOEUaD7mORUDYgrypBLFFDtISpIA1vtZ4g' \
The code for this simple demo can be found here
https://github.com/mitzenjeremywoo/AddJwtBearer-example
Comments