Simplifies setup of JSON Web Tokens (JWT) authentication by:
- providing extension methods for
- setup (on
IServiceCollection
), seeServiceCollectionExtensions
- token retrieval (on
HttpClient
), seeAuthenticationTokenHelper
- setup (on
- an authentication controller that will provide an authentication endpoint
- abstracts JWT creation
- Add the nuget.
- Add authentication
- In
ConfigureServices
add the following line, ensuring to change the parameter to an appropriate issuer that will be added to the JWT:
services.AddHousingRepairsOnlineAuthentication("<REPLACE WITH APPROPRIATE ISSUER");
- In
Configure
add the following line
app.UseAuthentication();
- Also in
Configure
, add callRequireAuthorization
to lock down all endpoints
app.UseEndpoints(endpoints => { endpoints.MapControllers().RequireAuthorization(); });
- In
- Optionally, if using Swagger, in
ConfigureServices
withinservices.AddSwaggerGen
addc.AddJwtSecurityScheme();
This will allow setting a JWT authentication token via the Swagger web UI.services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "HousingRepairsOnlineApi", Version = "v1" }); c.AddJwtSecurityScheme(); });
- All
HttpClient
's should have their BaseAddress property set. - To simplify the two steps of authentication and request,
HttpRequestMessage.SetupJwtAuthentication
extension method has been created which will authenticate and then add the retrieved token to the header. Example:
HttpClient httpClient = new HttpClient { BaseAddress = "http://api.address" }
HttpRequestMessage httpRequestMessage = ...
httpRequestMessage.SetupJwtAuthentication(httpClient, "authenticationIdentifier");
After following the steps above, the following describes how to authenticate and make requests. It's advisable to copy the below to the documentation of consuming projects.
Requests to the API require authentication. The API implements JSON Web Tokens (JWT) for authentication.
A unique, secret identifier is required to generate a JWT.
This should be set in an AUTHENTICATION_IDENTIFIER
environment variable which will be consumed during startup.
A JWT can be generated using a POST request to the Authentication
endpoint, i.e.
POST https://localhost:5001/Authentication?identifier=<AUTHENTICATION_IDENTIFIER>
The body of the response will contain a JWT which will expire after 1 minute.
All other requests require a valid JWT to be sent in the Authorization
header with a value of
Bearer <JWT TOKEN>
, i.e.
GET https://localhost:5001/Addresses?postcode=1
Authorization: Bearer <JWT TOKEN>