This is a startup web app with essential functionalities:
- Authentication with JWT
- Rate Limiting & CORS settings
- Dockerization (and docker compose)
- EFCore & DbContext
- Production & Development settings
- Fill the variables in
example.envand rename the file to.env - Run
docker-compose.development.yml, you can use the following command:docker-compose -f "docker-compose.development.yml" up -d - Import
Development.postman_collection.jsonto postman for testing.
In this exercise, you will learn how to create a minimal ASP.NET Web API and implement JWT (JSON Web Token) authentication.
- Create a new ASP.NET Web API project.
- Configure the project with the necessary dependencies, such as
Microsoft.AspNetCore.Authentication.JwtBearerpackage, which provides JWT authentication support.
- Create a class called
JwtTokenGeneratorthat will be responsible for generating and validating JWT tokens. - Inside the
JwtTokenGeneratorclass, implement a method calledGenerateTokenthat takes in user credentials (e.g., username and password) and returns a JWT token. - Use the
System.IdentityModel.Tokens.Jwtnamespace to create and sign the JWT token. You can use a secure key or a certificate to sign the token. - Implement another method called
ValidateTokenthat takes in a JWT token and verifies its validity, including the signature and expiration date.
- Create an API controller class that will handle the requests and responses for your API.
- Apply the
[Authorize]attribute to the controller or specific actions that require authentication. - Create a get method that will return today’s weather or a welcome message, just to show the user that he is authorized and has access to the system.
- Open the
Startup.csfile in your project. - In the
ConfigureServicesmethod, configure JWT authentication using theAddAuthenticationmethod and specify the JWT bearer options. - Provide the necessary configuration details such as the issuer, audience, and token validation parameters.
- In the
Configuremethod, add theUseAuthenticationmiddleware to enable authentication in your API.
- Build and run your API project.
- Use a tool like Postman or curl to send HTTP requests to your API endpoints.
- For authenticated endpoints, include the JWT token in the request headers using the
Authorizationheader. The token should be in the formatBearer <token>. - Test both authenticated and unauthenticated endpoints to ensure that the authentication is working as expected.
In this exercise, you have learned how to create a minimal ASP.NET Web API and implement JWT authentication. This provides a secure way to authenticate and authorize requests to your API endpoints. By understanding the concepts and following the steps outlined in this exercise, you are now equipped with the knowledge to build more complex APIs with JWT authentication in the future.
Remember to document your code thoroughly and explain any additional features or enhancements you may have implemented. Good luck with your exercise!