Skip to content

t7a6/gin-jwt

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Example

Click here for an implementation example.

https://github.com/ken109/gin-jwt-example

Overview

  1. Issuance of private key
openssl genrsa -out private.key 2048
  1. Add Import
import (
    "github.com/ken109/gin-jwt"
)
  1. Set private key, Issuer, etc.
func main() {
    pemBytes, err := ioutil.ReadFile("private.key")
    if err != nil {
        panic(err)
    }

    // here
    err := jwt.SetUp(pemBytes, jwt.Option{
        Issuer: "[email protected]",
        Subject: "[email protected]",
        KeyId: "test",
        Expiration: time.Hour * 1,
    })
    
    if err != nil {
        panic(err)
    }

    r := gin.New()
  
        :
        :
}
  1. Issue a signed token
func Login(c *gin.Context) {
    user := "user"
    password := "password"
    
    if user == "user" && password == "password" {
        // here
        token, err := jwt.GetToken(jwt.Claims{
            "admin": true,
        })
        
        if err != nil {
            c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed"})
            return
        }
        
        c.JSON(http.StatusOK, map[string]interface{}{"token": string(token)})
        return
    }
    
    c.JSON(http.StatusForbidden, map[string]string{"error": "login failed"})
    return
}
  1. Set the middleware on the route you want to authenticate
func main() {
    :
    
    auth := r.Group("/api")

    // here
    auth.Use(jwt.Verify)
    
    :
}
  1. Receive private claims
func main() {
    :
    
    auth.Use(jwt.Verify)
    
    auth.GET("/hello", func(c *gin.Context) {
        // here
        claims := jwt.GetClaims(c)
        
        fmt.Println(claims["admin"].(bool)) // true
        
        c.JSON(http.StatusOK, claims)
    })
    
    :
}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 100.0%