⛓️

What is JWT Auth

2024/03/24に公開

📕Overview

Authentication function using JSON Web Token.

Using the Go language, try logging in with dummy data that does not use a database.

🧷summary

The username is hoge and the password is 1234.
If the values match if, you can log in.

package main

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

// mySigningKey is a secret key for signing the token
var mySigningKey = []byte("secret")

// Login is a struct for login request
type Login struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

func main() {
	// Create a new Gin router
	router := gin.Default()
	// Define a route for login
	router.POST("/login", func(c *gin.Context) {
		// Bind the request body to the Login struct
		var login Login
		// If the request body is not valid, return an error
		if err := c.ShouldBindJSON(&login); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		// Check the username and password
		if login.Username != "hoge" || login.Password != "1234" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
			return
		}

		// Create the Claims
		claims := &jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
		}
		// Create a new token
		token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
		// Sign the token
		ss, err := token.SignedString(mySigningKey)
		// If an error occurs, return an error
		if err != nil {
			// Return an error
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Error generating token"})
			return
		}
		// Return the token
		c.JSON(http.StatusOK, gin.H{"token": ss})
	})
	// Define a route for the protected resource
	router.Run(":8080")
}

run command:

go run main.go

POST request body to URL

{
    "username": "hoge",
    "password": "1234"
}

http://localhost:8080/login

🧑‍🎓thoughts

This time, I tried implementing JWT login using dummy data without using a database.

Discussion