jwt.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. //package jwt
  2. //
  3. //import (
  4. // //"strings"
  5. //
  6. // "github.com/dgrijalva/jwt-go"
  7. // "github.com/gin-gonic/gin"
  8. // "kpt.xdmy/pkg/e"
  9. // "kpt.xdmy/pkg/util"
  10. // jwtGet "kpt.xdmy/pkg/util"
  11. //)
  12. //
  13. //func JWT() gin.HandlerFunc {
  14. // return func(c *gin.Context) {
  15. // var code int
  16. // var data interface{}
  17. //
  18. // code = e.SUCCESS
  19. // //Authorization := c.GetHeader("Authorization")
  20. // //token := strings.Split(Authorization, " ")
  21. // Authorization := c.GetHeader("token")
  22. // token := Authorization
  23. // if Authorization == "" {
  24. // code = e.INVALID_PARAMS
  25. // } else {
  26. // //_, err := util.ParseToken(token[1])
  27. // _, err := util.ParseToken(token)
  28. // if err != nil {
  29. // switch err.(*jwt.ValidationError).Errors {
  30. // case jwt.ValidationErrorExpired:
  31. // code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
  32. // default:
  33. // code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
  34. // }
  35. // }
  36. // }
  37. //
  38. // if code != e.SUCCESS {
  39. // c.JSON(e.SUCCESS, gin.H{
  40. // "code": code,
  41. // "msg": "登录超时",
  42. // "data": data,
  43. // })
  44. //
  45. // c.Abort()
  46. // return
  47. // }
  48. //
  49. // t, _ := jwt.Parse(token, func(*jwt.Token) (interface{}, error) {
  50. // return jwtGet.JwtSecret, nil
  51. // })
  52. // c.Set("jwt_username", jwtGet.GetIdFromClaims("username", t.Claims))
  53. // c.Next()
  54. // }
  55. //}
  56. package jwt
  57. import (
  58. "bytes"
  59. "encoding/base64"
  60. "encoding/json"
  61. "fmt"
  62. "github.com/astaxie/beego/logs"
  63. "github.com/dgrijalva/jwt-go"
  64. "github.com/gin-gonic/gin"
  65. "github.com/pkg/errors"
  66. "io/ioutil"
  67. "kpt.xdmy/pkg/e"
  68. jwtGet "kpt.xdmy/pkg/util"
  69. "net/http"
  70. "strings"
  71. //"strings"
  72. "kpt.xdmy/pkg/setting"
  73. )
  74. //var (
  75. // svc *service.Service
  76. //)
  77. type Introspect struct {
  78. Active bool `json:"active"`
  79. UserName string `json:"user_name"`
  80. }
  81. func JWT() gin.HandlerFunc {
  82. if setting.IDaaSSetting.IsDaaS == 1 {
  83. return func(c *gin.Context) {
  84. //s := new(service.Service)
  85. fmt.Println(setting.IDaaSSetting)
  86. authorization := fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(setting.IDaaSSetting.ClientId+":"+setting.IDaaSSetting.ClientSecret)))
  87. fmt.Println(authorization)
  88. //tokenData := make(map[string]string, 0)
  89. //tokenData["token"] = c.GetHeader("token")
  90. //tokenDataByte, _ := json.Marshal(tokenData)
  91. tokenRespByte, _ := PostPush(setting.IDaaSSetting.Url+fmt.Sprintf("/api/v1/oauth2/introspect?token=%s", c.GetHeader("token")), nil, authorization)
  92. IntrospectResp := new(Introspect)
  93. json.Unmarshal(tokenRespByte, &IntrospectResp)
  94. if !IntrospectResp.Active {
  95. c.JSON(e.SUCCESS, gin.H{
  96. "code": e.INVALID_PARAMS,
  97. "msg": "登录失效!",
  98. "data": "",
  99. })
  100. c.Abort()
  101. return
  102. }
  103. c.Set("jwt_username", IntrospectResp.UserName)
  104. c.Next()
  105. }
  106. } else {
  107. return func(c *gin.Context) {
  108. var code int
  109. var data interface{}
  110. code = e.SUCCESS
  111. //Authorization := c.GetHeader("Authorization")
  112. //token := strings.Split(Authorization, " ")
  113. Authorization := c.GetHeader("token")
  114. token := Authorization
  115. if Authorization == "" {
  116. code = e.INVALID_PARAMS
  117. } else {
  118. //_, err := util.ParseToken(token[1])
  119. _, err := jwtGet.ParseToken(token)
  120. if err != nil {
  121. switch err.(*jwt.ValidationError).Errors {
  122. case jwt.ValidationErrorExpired:
  123. code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
  124. default:
  125. code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
  126. }
  127. }
  128. }
  129. if code != e.SUCCESS {
  130. c.JSON(e.SUCCESS, gin.H{
  131. "code": code,
  132. "msg": "登录超时",
  133. "data": data,
  134. })
  135. c.Abort()
  136. return
  137. }
  138. t, _ := jwt.Parse(token, func(*jwt.Token) (interface{}, error) {
  139. return jwtGet.JwtSecret, nil
  140. })
  141. c.Set("jwt_username", jwtGet.GetIdFromClaims("username", t.Claims))
  142. c.Next()
  143. }
  144. }
  145. }
  146. func PostPush(url string, data []byte, authorization string) ([]byte, error) {
  147. req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
  148. if err != nil {
  149. logs.Error(err)
  150. return nil, err
  151. }
  152. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  153. req.Header.Set("Authorization", authorization)
  154. client := &http.Client{}
  155. resp, err := client.Do(req)
  156. if err != nil {
  157. logs.Error(err)
  158. return nil, err
  159. }
  160. defer resp.Body.Close()
  161. body, _ := ioutil.ReadAll(resp.Body)
  162. fmt.Println(string(body))
  163. if strings.Index(resp.Status, "200") == -1 {
  164. return nil, errors.New(fmt.Sprintf("%s 请求失败!", resp.Status))
  165. }
  166. return body, nil
  167. }