Loading

【code】jwt

 

package main

import (
    "fmt"
    "net/http"
    "time"

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

func main() {
    r := gin.Default()

    r.GET("/login", login)

    v1 := r.Group("/v1")
    v1.Use(JWTAuth())
    {
        v1.GET("/userid", userId)
    }

    r.Run()
}

func login(c *gin.Context) {
    name := c.DefaultQuery("name", "admin")
    passwd := c.DefaultQuery("passwd", "123456")

    if name == "admin" && passwd == "123456" {
        userId := 1
        var expireTime = time.Now().Add(time.Minute)

        tokenStr, err := GenerateToken(uint64(userId), expireTime)

        if err != nil {
            // token生成错误
            fmt.Println("token生成错误")
        }
        c.SetCookie("Authorization", tokenStr, 60, "/", "127.0.0.1", false, true)
        c.JSON(http.StatusAccepted, "login ok")
    } else {
        c.JSON(http.StatusForbidden, "用户名或密码错误")
    }
}

func userId(c *gin.Context) {
    userId := c.Query("userid")
    fmt.Printf("userid is %s", userId)
}

type AuthClaims struct {
    UserId uint64 `json:"userId"`
    jwt.StandardClaims
}

// 秘钥
var SecretKey = []byte("thisisasecretofjwt")

// 生成token
func GenerateToken(userId uint64, expireTime time.Time) (string, error) {
    claim := AuthClaims{
        UserId: userId,
        StandardClaims: jwt.StandardClaims{
            ExpiresAt: expireTime.Unix(),
            IssuedAt:  time.Now().Unix(),
            Issuer:    "wsongl",
            Subject:   "login-jwt",
        },
    }
    noSignedToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
    token, err := noSignedToken.SignedString(SecretKey)
    return token, err
}

// 解析token
func ParseToken(token string) (*jwt.Token, error) {
    tokenClaims, err := jwt.ParseWithClaims(token, &AuthClaims{}, func(t *jwt.Token) (interface{}, error) { return SecretKey, nil })

    return tokenClaims, err
}

// 鉴权中间件
func JWTAuth() gin.HandlerFunc {
    return func(c *gin.Context) {
        tokenStr := c.GetHeader("Authorization")
        if tokenStr == "" {
            c.JSON(http.StatusForbidden, "no token, you don't have permission.")
            c.Abort()
            return
        }
        tokenClaims, err := ParseToken(tokenStr)
        if err != nil {
            c.JSON(http.StatusForbidden, "invalid token, you don't have permission.")
        }
        authClaims, ok := tokenClaims.Claims.(*AuthClaims)
        if !ok {
            c.JSON(http.StatusForbidden, "invalid claim, you don't have permission.")
            c.Abort()
            return
        }
        fmt.Printf("authClaim is: %v", authClaims)
        c.Set("authclaims", authClaims)

        c.Next()
    }
}

测试验证:

http://localhost:8080/login?name=admin&passwd=123456

curl --header "Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImV4cCI6MTY0NjEzMDU4NiwiaWF0IjoxNjQ2MTMwNTI2LCJpc3MiOiJ3c29uZ2wiLCJzdWIiOiJsb2dpbi1qd3QifQ.g60g4bpMdwSuQ1qs715KkCieXuqcAT2Hu7pd0yGUBag" -v http://localhost:8080/v1/userid?userid=1

 

非对称加密

https://blog.csdn.net/newbieJ/article/details/121749430

 

 

.

posted @ 2022-03-01 19:05  wsongl  阅读(75)  评论(0编辑  收藏  举报