Implementing JWT Authentication in Go
JSON Web Tokens (JWTs) are a popular method for dealing with online authentication. In this article, we will explore how to implement JWT authentication in Go using the golang-jwt package.
Prerequisites
- Go 1.16 or later installed on your machine
- Experience building web applications in Go or any other language (optional)
Getting Started with the Golang-JWT Package
To get started, install the golang-jwt package by running the following command in your terminal:
go get github.com/golang-jwt/jwt/v4
Next, create a new Go file and import the necessary packages:
“`go
import (
“encoding/json”
“fmt”
“log”
“net/http”
“time”
"github.com/golang-jwt/jwt/v4"
)
“`
Setting up a Web Server in Go
Create a simple web server with an endpoint that will be secured with a JWT:
“`go
func main() {
http.HandleFunc(“/home”, handlePage)
log.Fatal(http.ListenAndServe(“:8080”, nil))
}
func handlePage(w http.ResponseWriter, r *http.Request) {
// TO DO: Implement JWT authentication
}
“`
Generating JWTs
To generate a JWT, you need a secret key. For this example, we will use a simple string as our secret key:
go
var sampleSecretKey = []byte("secretkey")
Create a function to generate a JWT:
“`go
func generateJWT(username string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
“username”: username,
“exp”: time.Now().Add(time.Minute * 10).Unix(),
})
tokenString, err := token.SignedString(sampleSecretKey)
if err != nil {
return "", err
}
return tokenString, nil
}
“`
Verifying JWTs
To verify a JWT, use the jwt.Parse
function:
go
func verifyJWT(tokenString string) (*jwt.Token, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return sampleSecretKey, nil
})
if err != nil {
return nil, err
}
return token, nil
}
Using JWTs for Authentication
Use the generateJWT
and verifyJWT
functions to authenticate requests:
“`go
func authPage(w http.ResponseWriter, r *http.Request) {
tokenString, err := generateJWT(“username”)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
req, err := http.NewRequest("GET", "/home", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
req.Header.Set("Authorization", "Bearer "+tokenString)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
var data map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprint(w, data)
}
“`
Conclusion
In this article, we explored how to implement JWT authentication in Go using the golang-jwt package. We generated and verified JWTs, and used them for authentication.