In action

Within the Echo project, there is a directory called middleware, which contains many contributed middleware solutions seen here: https://github.com/labstack/echo/tree/master/middleware. These middleware functions have been vetted by the community, and follow the middleware best practices guidelines. In this section, we will dissect one very useful middleware, and show how to use these middleware in our example application.

We will start by looking at middleware.JWT, which is a very helpful middleware that takes a JSON Web Token (JWT) from the request header specified by the developer and validates that the token is legitimate. In our example, the handlers.Login handler will validate the user credentials with bcrypt, and after that verification, we will create a JWT for the caller to insert into their request headers. The following is the JWT creation code located in $GOPATH/src/github.com/PacktPublishing/Echo-Essentials/chapter4/handlers/login.go:

        // need to make a token, successful login
        signingKey := c.Get(models.SigningContextKey).([]byte)

        // Create the Claims
        claims := &jwt.StandardClaims{
                ExpiresAt: time.Now().Add(time.Hour * 72).Unix(),
                Issuer:    "service",
        }

        token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
        ss, err := token.SignedString(signingKey)
        if err != nil {
                resp.Success = false
                resp.Message = "Server Error"
                return c.JSON(http.StatusInternalServerError, resp)
        }

        resp.Token = ss

        return c.JSON(http.StatusOK, resp)

After we have this JWT token created, on successful login, our client can attach this token to the Authentication request header with the Bearer authentication scheme for subsequent requests. Taking our example back to inserting the middleware, the following inside $GOPATH/src/github.com/PacktPublishing/Echo-Essentials/chapter4/cmd/service/main.go will allow us to insert the JWT middleware that comes with Echo in order to validate (for the specific group of routes denoted) that the request contains the correct authentication information:

   // Latest Reminder Routes
   reminderGroup := e.Group("/reminder")
   reminderGroup.Use(middleware.JWT(signingKey))

As you can see, we are assigning our /reminder group, which includes all of the API endpoints for reminder manipulation and retrieval to use the Echo-contributed middleware.JWT middleware. This change has the effect that every single route that is within the reminder group will have the JWT authentication middleware applied, which performs this code to validate the JWT from the token passed in the request:

   token, err = jwt.ParseWithClaims(auth, claims, config.keyFunc)
        
        if err == nil && token.Valid {
                // Store user information from token into context.
                c.Set(config.ContextKey, token)
                return next(c)
        }

This allows our handlers to remain completely ignorant of the fact that we need to perform authentication, causing our routes to be less complex and easier to read.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.217.17