golang web服务器开发使用JsonWebToken(JWT)身份验证

jwt的介绍我就不再写了,之前的文章有介绍过Asp.Net WebApi 使用JsonWebToken(JWT)身份验证,这篇文章主要简单说一下在golang的使用。

主要文件

package utils

import (
	"github.com/dgrijalva/jwt-go" //引入的jwt包
	"time"
)

//自定义Claims,继承包内的Claims
type jwtCustomClaims struct {
	jwt.StandardClaims        

	// 追加自己需要的信息
	Uuid     string `json:"uuid"`
	Nickname string `json:"nickname"`
}

//生成token
func CreateJWT(SecretKey []byte, Uuid string, Nickname string) (tokenString string, err error) {
    //生成Clamis
	claims := &jwtCustomClaims{
		jwt.StandardClaims{
			ExpiresAt: int64(time.Now().Add(time.Hour * 1).Unix()),//有效期
		},
		Uuid,    //用户uuid
		Nickname,    //用户名
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err = token.SignedString(SecretKey)    //签名(加密)
	return
}

//解析token
func ParseJWT(tokenSrt string, SecretKey []byte) (claims jwt.Claims, err error) {
	var token *jwt.Token
	token, err = jwt.Parse(tokenSrt, func(*jwt.Token) (interface{}, error) {
		return SecretKey, nil
	})
	claims = token.Claims
	return
}

 

使用方法:

package http

import (
	"net/http"
	"strings"

	sql "github.com/LyonNee/grom_echo_demo/data"
	"github.com/LyonNee/grom_echo_demo/model"
	"github.com/LyonNee/grom_echo_demo/utils"
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

func Start() {
	e := echo.New()

	e.Use(middleware.Logger())

	var mjwt = middleware.JWTWithConfig(middleware.JWTConfig{
		SigningKey: []byte("secret"),
	})

	e.POST("/register", register)
	e.POST("/login", login)
	e.POST("/my", my, mjwt)

	e.Logger.Fatal(e.Start(":8080"))
}

func register(c echo.Context) error {
	user := new(model.User)
	if err := c.Bind(user); err != nil {
		return err
	}

	err := sql.AddUser(*user)
	if err != nil {
		return c.String(http.StatusOK, "用户已存在")
	} else {
		return c.String(http.StatusOK, "组册成功")
	}
}

func login(c echo.Context) error {
	loginIM := new(model.LoginIM)
	if err := c.Bind(loginIM); err != nil {
		return err
	}

	var user = model.User{}
	user, err := sql.GetUserByUsername(loginIM.Username)

	if err != nil {
		return c.String(http.StatusOK, "用户不存在")
	} else if utils.GetMD5HashCode(loginIM.Password) != user.Password {
		return c.String(http.StatusOK, "密码错误")
	}

	// Generate encoded token and send it as response.
	t, err := utils.CreateJWT([]byte("secret"), user.UUID, user.Nickname)
	if err != nil {
		return c.String(http.StatusOK, err.Error())
	}
	return c.JSON(http.StatusOK, map[string]string{
		"token": t,
	})
}

func my(c echo.Context) error {
	tokenStr := c.Request().Header.Get("Authorization")
	if strings.Contains(tokenStr, "Bearer ") {
		tokenStr = tokenStr[7:]
	}

	claims, err := utils.ParseJWT(tokenStr)
	name := claims.Nickname
	//uuid:=claims.Uuid
	if err != nil {
		return c.JSON(http.StatusOK, map[string]string{
			"name": name,
		})
	}
	return c.String(http.StatusOK, "Welcome "+name+" !")
}

 

Demo源码链接

基本上就是这样了,有问题或者是有建议的欢迎留言评论或者私信我。

你可能感兴趣的:(golang开发,go,golang,jwt,echo)