Go-Swagger : User Authentication & securing API using JWT — Part 2

Shashank Vivek
3 min readAug 13, 2020

--

This article is the continuation of user authentication using JWT . In Part-1 of this article, we successfully generated a valid JWT token using our /login endpoint. In this section, we’ll work on securing APIs so that it restricts any unauthenticated calls.

1. Define security in swagger.yaml

To enable authentication for an API, we need to define securityDefinitions into swagger.yaml file:

securityDefinitions:  
Bearer:
type: apiKey
name: Authorization
in: header

2. Create restricted API

Lets create an endpoint, say /user/cart which fetches all cart items of a registered user. Since , we want to restrict this API for authorized user only, we need to add below definition in swagger.yaml file under /user/cart yaml property.

security:
- Bearer: []

The final swagger.yaml file will look like:

You view this yaml online on swagger editor, note the “Lock” icon on /user/cart . It informs a developer that this API needs authorization.

3. Generate boilerplate code from swagger.yaml

To generate the code from the above swagger.yaml file, you’ll have run below command:

swagger generate server -f swagger.yaml --default-scheme http --exclude-main

4. Create authentication middleware

Now, that we have the required code generated based on the swagger.yaml file, we can proceed on creating a middleware which would intercept all those API calls that has security defined under it. We’ll be doing below steps to get it done:

  • Create authenticator.go , which will validate the JWT token. If the token is valid, we return the email and error as nil. For any invalid token, we’ll return an error .

That’s it ! 👑

Now, the /user/cart can only be accessed by a valid JWT token.

5. Getting User info from JWT Token in API code.

As I have already explained the during the intro article of go-swagger , We’ll be similarly creating get_user_cart_item.go . We can re-use ValidateHeader() from utils package and use it extract email . Once we have the email, we can pass it on to GetCustomerCart() to get the respective cart items.

To test this endpoint , we need to generate a token using /login endpoint. Once we have the token, we need add it in Authorization header .

Screenshot of a Valid request :

Screenshot of a Invalid request with expired token :

The final code can be referred in my e-food GitHub repository. Feel free to explore the repository. It is a working code with no change in file names.

If you like this article, please 👏 clap 👏 few times to encourage me 🐼 to write more.

--

--

Shashank Vivek
Shashank Vivek

Responses (1)