A simple API created using gin framework for authentication and logging requests using middleware.
Server port: 8080
JWT Token used: HMAC SHA-256 algorithm
Two middleware functions are applied to all routes:
- LoggerMiddleware: Logs information about incoming requests, including the HTTP method, URL path, client IP address, and request processing time.
- AuthMiddleware: Validates JWT tokens for routes under the
/sam-api
group. It checks for the presence of the Authorization header containing a valid JWT token.
Handles POST
request for user authentication and returns a JWT token in the response body.
Only accessible if the GET
request includes a valid JWT token
in the Authorization header and returns a message indicating a secure route in the response body.
If the request made to the secured endpoint has a valid token in the Authorization header is valid, then the middleware allows the the request to proceed to the Secured Handler
.
- Run
go mod init gin-middleware
- Run
go mod tidy
- Finally run
go run main.go
- Use POST request
localhost:8080/sam-login
- In body, select
x-www-form-urlencoded
- Add the key value pair as follows,
username: sam
password: gin-gonic
- We will get a unique
<token>
in the response body as follows,
{
"token": <token>
}
- Use GET request
localhost:8080/sam-api/secured
- In Headers, add key value pair as follows where we paste the
<token>
from the login endpoint's response,
Authorization: <token>
- The desired output is as follows,
{
"message": "You have entered a secured route"
}