_main.go_
package main
import (
"time"
"zhijing/apis/web"
"zhijing/infra/base"
"github.com/dgrijalva/jwt-go/request"
"github.com/dgrijalva/jwt-go"
"github.com/kataras/iris"
)
const JwtSecret = "secret"
// JWT验证中间件
func ValidateJwtMiddleware(ctx iris.Context) {
token, err := request.ParseFromRequest(ctx.Request(), request.AuthorizationHeaderExtractor,
func(token *jwt.Token) (i interface{}, e error) {
return []byte(JwtSecret), nil
})
if err != nil || !token.Valid {
ctx.JSON("认证错误")
} else {
ctx.Next()
}
}
func main() {
app := iris.New()
app.Get("/login", func(ctx iris.Context) {
// 判断用户是否存在,密码是否正确
// 比如从数据库查询
// 计算token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": "Username",
"password": "Password",
// 添加过期时间
"exp": time.Now().Add(time.Hour * 2).Unix(),
})
// JwtSecret必须和验证时的一致
tokenStr, _ := token.SignedString([]byte(web.JwtSecret))
ctx.JSON(tokenStr)
})
// 需要JWT验证的接口添加验证中间件
app.Get("/get", ValidateJwtMiddleware, func(ctx iris.Context) {
})
app.Run(iris.Addr(":8080"))
}