Browse Source

feat: 接口增加jwt验证

caipin 3 years ago
parent
commit
25e4ba4f1d
3 changed files with 36 additions and 5 deletions
  1. 3 0
      conf/project.go
  2. 6 5
      web/external/jl_bb.go
  3. 27 0
      web/utils/utils.go

+ 3 - 0
conf/project.go

@@ -41,6 +41,9 @@ var CookieSecret = "cm_login_account"
 // 计量,项目管理互通 请求
 var JLSecretKey = "JL_CM_lksjdofuosdjflj01231209uljsf90@@#(lnm8"
 
+// 计量报表 接口使用
+var JLBBSecretKey = "jl2pm3850key888sc"
+
 // nodejs rpc 服务端
 const NodeRpcHost = "192.168.1.47:50051"
 

+ 6 - 5
web/external/jl_bb.go

@@ -5,6 +5,7 @@ import (
 
 	"github.com/kataras/iris/v12"
 	"go.mod/services"
+	"go.mod/web/utils"
 	"go.mod/web/viewmodels"
 )
 
@@ -38,11 +39,11 @@ func (c *JlBb) GetFolder() {
 		return
 	}
 	// 1-2.验证jwt
-	// _, err := utils.ValidateJwt(data.Token)
-	// if err != nil {
-	// 	c.Ctx.JSON(iris.Map{"code": -1, "msg": fmt.Sprintf("%s", err)})
-	// 	return
-	// }
+	_, err := utils.ValidateJwt(data.Token)
+	if err != nil {
+		c.Ctx.JSON(iris.Map{"code": -1, "msg": fmt.Sprintf("%s", err)})
+		return
+	}
 
 	// 获得项目ID
 	projectDetail := c.ServiceProject.GetNameBs(data.Code)

+ 27 - 0
web/utils/utils.go

@@ -209,6 +209,33 @@ func ValidateJwt(tokenStr string) (map[string]interface{}, error) {
 	return data, nil
 }
 
+// 验证并解析JWT
+func ValidateJwtBB(tokenStr string) error {
+
+	// 1.验证并解析JWT
+	parseAuth, err := jwt.Parse(tokenStr, func(*jwt.Token) (interface{}, error) {
+		return []byte(conf.JLBBSecretKey), nil
+	})
+	if err != nil {
+		log.Println("JWT异常, error=", err)
+		return err
+	}
+	if !parseAuth.Valid {
+		if ve, ok := err.(*jwt.ValidationError); ok {
+			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
+				return errors.New("无效签名")
+			} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
+				return errors.New("过期签名")
+			} else {
+				return errors.New("无效签名")
+			}
+		}
+		return errors.New("无效签名")
+	}
+
+	return nil
+}
+
 func GetEnvInfo(env string) string {
 	viper.AutomaticEnv()
 	return viper.GetString(env)