jwtauth.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. package jwtauth
  2. import (
  3. "crypto/rsa"
  4. "errors"
  5. "net/http"
  6. "os"
  7. "strings"
  8. "time"
  9. "github.com/gin-gonic/gin"
  10. "github.com/golang-jwt/jwt/v4"
  11. )
  12. const JwtPayloadKey = "JWT_IOT_PAYLOAD"
  13. const JwtTokenKey = "JWT_TOKEN"
  14. // GinJWTMiddleware 提供了Json Web Token身份验证实现
  15. // 失败时,将返回401 HTTP响应,成功后将调用封装的中间件,并将 userID 作为 c.Get("userID").(string).Users 提供。
  16. // 通过向LoginHandler POST请求来获取令牌, 在Authentication标头中传递令牌 Authorization:Bearer XX_TOKEN_XXX
  17. type GinJWTMiddleware struct {
  18. // Realm 用户姓名 (必需)
  19. Realm string
  20. // 签名算法-可能的值为HS256、HS384、HS512 。默认 HS256.
  21. SigningAlgorithm string
  22. // 签名密钥 (必需)
  23. Key []byte
  24. // jwt令牌有效的持续时间, 默认为一小时
  25. Timeout time.Duration
  26. // 此字段允许客户端刷新其令牌,直到MaxRefresh过期为止。 默认为0,表示不可刷新
  27. // 请注意,客户端可以在MaxRefresh的最后一刻刷新其令牌,这意味着令牌的最大有效时间跨度是TokenTime+MaxRefresh。
  28. MaxRefresh time.Duration
  29. //回调函数,应根据登录信息对用户进行身份验证。
  30. //必须将用户数据作为用户标识符返回,它将存储在Claim Array中。(必需)
  31. //检查错误(e)以确定适当的错误消息。
  32. Authenticator func(c *gin.Context) (interface{}, error)
  33. //回调函数,该函数应执行已验证用户的授权。仅在身份验证成功后调用。成功时必须返回真,失败时必须返回假。 默认为 true。
  34. Authorizator func(data interface{}, c *gin.Context) bool
  35. // 将在登录期间调用的回调函数。 默认情况下不会设置其他数据。
  36. // 使用此函数可以将额外的有效负载数据添加到网络令牌中。通过c.Get(“JWT_PAYLOAD”)在请求期间获取数据。
  37. // 请注意,有效载荷未加密。 jwt.io上提到的属性不能用作贴图的关键点。
  38. PayloadFunc func(data interface{}) MapClaims
  39. // 自定义未授权回调。
  40. Unauthorized func(*gin.Context, int, string)
  41. // 自定义登录响应回调
  42. LoginResponse func(*gin.Context, int, string, time.Time)
  43. // Antd登录响应回调.
  44. AntdLoginResponse func(*gin.Context, int, string, time.Time)
  45. // 自定义刷新响应回调
  46. RefreshResponse func(*gin.Context, int, string, time.Time)
  47. // 设置Identity处理程序函数
  48. IdentityHandler func(*gin.Context) interface{}
  49. // 关键字段,用于存储用户信息
  50. // Set the identity key
  51. IdentityKey string
  52. // 用户名
  53. NiceKey string
  54. // 数据权限类型
  55. DataScopeKey string
  56. // role key
  57. RKey string
  58. // 角色id
  59. RoleIdKey string
  60. // 角色key
  61. RoleKey string
  62. // 角色名称
  63. RoleNameKey string
  64. // TokenLookup is a string in the form of "<source>:<name>" that is used
  65. // to extract token from the request.
  66. // Optional. Default value "header:Authorization".
  67. // Possible values:
  68. // - "header:<name>"
  69. // - "query:<name>"
  70. // - "cookie:<name>"
  71. TokenLookup string
  72. // TokenHeadName is a string in the header. Default value is "Bearer"
  73. TokenHeadName string
  74. // TimeFunc provides the current time. You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens.
  75. TimeFunc func() time.Time
  76. // HTTP Status messages for when something in the JWT middleware fails.
  77. // Check error (e) to determine the appropriate error message.
  78. HTTPStatusMessageFunc func(e error, c *gin.Context) string
  79. // Private key file for asymmetric algorithms
  80. PrivKeyFile string
  81. // Public key file for asymmetric algorithms
  82. PubKeyFile string
  83. // Private key
  84. privKey *rsa.PrivateKey
  85. // Public key
  86. pubKey *rsa.PublicKey
  87. // Optionally return the token as a cookie
  88. SendCookie bool
  89. // Allow insecure cookies for development over http
  90. SecureCookie bool
  91. // Allow cookies to be accessed client side for development
  92. CookieHTTPOnly bool
  93. // Allow cookie domain change for development
  94. CookieDomain string
  95. // SendAuthorization allow return authorization header for every request
  96. SendAuthorization bool
  97. // Disable abort() of context.
  98. DisabledAbort bool
  99. // CookieName allow cookie name change for development
  100. CookieName string
  101. }
  102. var (
  103. // ErrMissingSecretKey 需要密钥
  104. ErrMissingSecretKey = errors.New("secret key is required")
  105. // ErrForbidden when HTTP status 403
  106. ErrForbidden = errors.New("you don't have permission to access this resource")
  107. // ErrMissingAuthenticatorFunc indicates Authenticator is required
  108. ErrMissingAuthenticatorFunc = errors.New("ginJWTMiddleware.Authenticator func is undefined")
  109. // ErrMissingLoginValues indicates a user tried to authenticate without username or password
  110. ErrMissingLoginValues = errors.New("missing Username or Password or Code")
  111. // ErrFailedAuthentication indicates authentication failed, could be faulty username or password
  112. ErrFailedAuthentication = errors.New("incorrect Username or Password")
  113. // ErrFailedTokenCreation indicates JWT Token failed to create, reason unknown
  114. ErrFailedTokenCreation = errors.New("failed to create JWT Token")
  115. // ErrExpiredToken indicates JWT token has expired. Can't refresh.
  116. ErrExpiredToken = errors.New("token is expired")
  117. // ErrEmptyAuthHeader can be thrown if authing with a HTTP header, the Auth header needs to be set
  118. ErrEmptyAuthHeader = errors.New("auth header is empty")
  119. // ErrMissingExpField missing exp field in token
  120. ErrMissingExpField = errors.New("missing exp field")
  121. // ErrWrongFormatOfExp field must be float64 format
  122. ErrWrongFormatOfExp = errors.New("exp must be float64 format")
  123. // ErrInvalidAuthHeader indicates auth header is invalid, could for example have the wrong Realm name
  124. ErrInvalidAuthHeader = errors.New("auth header is invalid")
  125. // ErrEmptyQueryToken can be thrown if authing with URL Query, the query token variable is empty
  126. ErrEmptyQueryToken = errors.New("query token is empty")
  127. // ErrEmptyCookieToken can be thrown if authing with a cookie, the token cokie is empty
  128. ErrEmptyCookieToken = errors.New("cookie token is empty")
  129. // ErrEmptyParamToken can be thrown if authing with parameter in path, the parameter in path is empty
  130. ErrEmptyParamToken = errors.New("parameter token is empty")
  131. // ErrInvalidSigningAlgorithm indicates signing algorithm is invalid, needs to be HS256, HS384, HS512, RS256, RS384 or RS512
  132. ErrInvalidSigningAlgorithm = errors.New("invalid signing algorithm")
  133. ErrInvalidVerificationode = errors.New("验证码错误")
  134. // ErrNoPrivKeyFile indicates that the given private key is unreadable
  135. ErrNoPrivKeyFile = errors.New("private key file unreadable")
  136. // ErrNoPubKeyFile indicates that the given public key is unreadable
  137. ErrNoPubKeyFile = errors.New("public key file unreadable")
  138. // ErrInvalidPrivKey indicates that the given private key is invalid
  139. ErrInvalidPrivKey = errors.New("private key invalid")
  140. // ErrInvalidPubKey indicates the the given public key is invalid
  141. ErrInvalidPubKey = errors.New("public key invalid")
  142. // IdentityKey default identity key
  143. IdentityKey = "identity"
  144. UserIdKey = "userid"
  145. // UserNameKey 用戶名
  146. UserNameKey = "username"
  147. NiceKey = "nice"
  148. DataScopeKey = "datascope"
  149. RKey = "r"
  150. // RoleIdKey 角色id Old
  151. RoleIdKey = "roleid"
  152. // RoleKey 角色名称 Old
  153. RoleKey = "rolekey"
  154. // RoleNameKey 角色名称 Old
  155. RoleNameKey = "rolename"
  156. // OrgIdKey 组织机构id
  157. OrgIdKey = "orgid"
  158. // OrgNameKey 组织机构名称
  159. OrgNameKey = "orgname"
  160. )
  161. // New for check error with GinJWTMiddleware
  162. func New(mw *GinJWTMiddleware) (*GinJWTMiddleware, error) {
  163. if err := mw.MiddlewareInit(); err != nil {
  164. return nil, err
  165. }
  166. return mw, nil
  167. }
  168. func (mw *GinJWTMiddleware) readKeys() error {
  169. err := mw.privateKey()
  170. if err != nil {
  171. return err
  172. }
  173. err = mw.publicKey()
  174. if err != nil {
  175. return err
  176. }
  177. return nil
  178. }
  179. func (mw *GinJWTMiddleware) privateKey() error {
  180. keyData, err := os.ReadFile(mw.PrivKeyFile)
  181. if err != nil {
  182. return ErrNoPrivKeyFile
  183. }
  184. key, err := jwt.ParseRSAPrivateKeyFromPEM(keyData)
  185. if err != nil {
  186. return ErrInvalidPrivKey
  187. }
  188. mw.privKey = key
  189. return nil
  190. }
  191. func (mw *GinJWTMiddleware) publicKey() error {
  192. keyData, err := os.ReadFile(mw.PubKeyFile)
  193. if err != nil {
  194. return ErrNoPubKeyFile
  195. }
  196. key, err := jwt.ParseRSAPublicKeyFromPEM(keyData)
  197. if err != nil {
  198. return ErrInvalidPubKey
  199. }
  200. mw.pubKey = key
  201. return nil
  202. }
  203. func (mw *GinJWTMiddleware) usingPublicKeyAlgo() bool {
  204. switch mw.SigningAlgorithm {
  205. case "RS256", "RS512", "RS384":
  206. return true
  207. }
  208. return false
  209. }
  210. // MiddlewareInit initialize jwt configs.
  211. func (mw *GinJWTMiddleware) MiddlewareInit() error {
  212. if mw.TokenLookup == "" {
  213. mw.TokenLookup = "header:Authorization"
  214. }
  215. if mw.SigningAlgorithm == "" {
  216. mw.SigningAlgorithm = "HS256"
  217. }
  218. if mw.TimeFunc == nil {
  219. mw.TimeFunc = time.Now
  220. }
  221. mw.TokenHeadName = strings.TrimSpace(mw.TokenHeadName)
  222. if len(mw.TokenHeadName) == 0 {
  223. mw.TokenHeadName = "Bearer"
  224. }
  225. if mw.Authorizator == nil {
  226. mw.Authorizator = func(data interface{}, c *gin.Context) bool {
  227. return true
  228. }
  229. }
  230. if mw.Unauthorized == nil {
  231. mw.Unauthorized = func(c *gin.Context, code int, message string) {
  232. c.JSON(http.StatusOK, gin.H{
  233. "code": code,
  234. "message": message,
  235. })
  236. }
  237. }
  238. if mw.LoginResponse == nil {
  239. mw.LoginResponse = func(c *gin.Context, code int, token string, expire time.Time) {
  240. c.JSON(http.StatusOK, gin.H{
  241. "code": http.StatusOK,
  242. "token": token,
  243. "expire": expire.Format(time.RFC3339),
  244. })
  245. }
  246. }
  247. if mw.AntdLoginResponse == nil {
  248. mw.AntdLoginResponse = func(c *gin.Context, code int, token string, expire time.Time) {
  249. c.JSON(http.StatusOK, gin.H{
  250. "code": http.StatusOK,
  251. "success": true,
  252. "token": token,
  253. "currentAuthority": token,
  254. "expire": expire.Format(time.RFC3339),
  255. })
  256. }
  257. }
  258. if mw.RefreshResponse == nil {
  259. mw.RefreshResponse = func(c *gin.Context, code int, token string, expire time.Time) {
  260. c.JSON(http.StatusOK, gin.H{
  261. "code": http.StatusOK,
  262. "token": token,
  263. "expire": expire.Format(time.RFC3339),
  264. })
  265. }
  266. }
  267. if mw.IdentityKey == "" {
  268. mw.IdentityKey = IdentityKey
  269. }
  270. if mw.IdentityHandler == nil {
  271. mw.IdentityHandler = func(c *gin.Context) interface{} {
  272. claims := ExtractClaims(c)
  273. return claims
  274. }
  275. }
  276. if mw.HTTPStatusMessageFunc == nil {
  277. mw.HTTPStatusMessageFunc = func(e error, c *gin.Context) string {
  278. return e.Error()
  279. }
  280. }
  281. if mw.Realm == "" {
  282. mw.Realm = "gin vb jwt"
  283. }
  284. if mw.CookieName == "" {
  285. mw.CookieName = "IotAdmin jwt"
  286. }
  287. if mw.usingPublicKeyAlgo() {
  288. return mw.readKeys()
  289. }
  290. if mw.Key == nil {
  291. return ErrMissingSecretKey
  292. }
  293. return nil
  294. }
  295. // MiddlewareFunc makes GinJWTMiddleware implement the Middleware interface.
  296. func (mw *GinJWTMiddleware) MiddlewareFunc() gin.HandlerFunc {
  297. return func(c *gin.Context) {
  298. mw.middlewareImpl(c)
  299. }
  300. }
  301. func (mw *GinJWTMiddleware) middlewareImpl(c *gin.Context) {
  302. claims, err := mw.GetClaimsFromJWT(c)
  303. if err != nil {
  304. mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(err, c))
  305. return
  306. }
  307. exp, err := claims.Exp()
  308. if err != nil {
  309. mw.unauthorized(c, http.StatusBadRequest, mw.HTTPStatusMessageFunc(err, c))
  310. return
  311. }
  312. if exp < mw.TimeFunc().Unix() {
  313. mw.unauthorized(c, 6401, mw.HTTPStatusMessageFunc(ErrExpiredToken, c))
  314. return
  315. }
  316. c.Set(JwtPayloadKey, claims)
  317. identity := mw.IdentityHandler(c)
  318. if identity != nil {
  319. c.Set(mw.IdentityKey, identity)
  320. }
  321. if !mw.Authorizator(identity, c) {
  322. mw.unauthorized(c, http.StatusForbidden, mw.HTTPStatusMessageFunc(ErrForbidden, c))
  323. return
  324. }
  325. c.Next()
  326. }
  327. // GetClaimsFromJWT get claims from JWT token
  328. func (mw *GinJWTMiddleware) GetClaimsFromJWT(c *gin.Context) (MapClaims, error) {
  329. token, err := mw.ParseToken(c)
  330. if err != nil {
  331. return nil, err
  332. }
  333. if mw.SendAuthorization {
  334. if v, ok := c.Get(JwtTokenKey); ok {
  335. c.Header("Authorization", mw.TokenHeadName+" "+v.(string))
  336. }
  337. }
  338. return MapClaims(token.Claims.(jwt.MapClaims)), nil
  339. }
  340. // LoginHandler can be used by clients to get a jwt token.
  341. // Payload needs to be json in the form of {"username": "USERNAME", "password": "PASSWORD"}.
  342. // Reply will be of the form {"token": "TOKEN"}.
  343. func (mw *GinJWTMiddleware) LoginHandler(c *gin.Context) {
  344. if mw.Authenticator == nil {
  345. mw.unauthorized(c, http.StatusInternalServerError, mw.HTTPStatusMessageFunc(ErrMissingAuthenticatorFunc, c))
  346. return
  347. }
  348. data, err := mw.Authenticator(c)
  349. if err != nil {
  350. mw.unauthorized(c, 400, mw.HTTPStatusMessageFunc(err, c))
  351. return
  352. }
  353. // Create the token
  354. token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))
  355. claims := token.Claims.(jwt.MapClaims)
  356. if mw.PayloadFunc != nil {
  357. for key, value := range mw.PayloadFunc(data) {
  358. claims[key] = value
  359. }
  360. }
  361. expire := mw.TimeFunc().Add(mw.Timeout)
  362. claims["exp"] = expire.Unix()
  363. claims["orig_iat"] = mw.TimeFunc().Unix()
  364. tokenString, err := mw.signedString(token)
  365. if err != nil {
  366. mw.unauthorized(c, http.StatusOK, mw.HTTPStatusMessageFunc(ErrFailedTokenCreation, c))
  367. return
  368. }
  369. // set cookie
  370. if mw.SendCookie {
  371. maxage := int(expire.Unix() - time.Now().Unix())
  372. c.SetCookie(
  373. mw.CookieName,
  374. tokenString,
  375. maxage,
  376. "/",
  377. mw.CookieDomain,
  378. mw.SecureCookie,
  379. mw.CookieHTTPOnly,
  380. )
  381. }
  382. mw.AntdLoginResponse(c, http.StatusOK, tokenString, expire)
  383. }
  384. func (mw *GinJWTMiddleware) signedString(token *jwt.Token) (string, error) {
  385. var tokenString string
  386. var err error
  387. if mw.usingPublicKeyAlgo() {
  388. tokenString, err = token.SignedString(mw.privKey)
  389. } else {
  390. tokenString, err = token.SignedString(mw.Key)
  391. }
  392. return tokenString, err
  393. }
  394. // RefreshHandler can be used to refresh a token. The token still needs to be valid on refresh.
  395. // Shall be put under an endpoint that is using the GinJWTMiddleware.
  396. // Reply will be of the form {"token": "TOKEN"}.
  397. func (mw *GinJWTMiddleware) RefreshHandler(c *gin.Context) {
  398. tokenString, expire, err := mw.RefreshToken(c)
  399. if err != nil {
  400. mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(err, c))
  401. return
  402. }
  403. mw.RefreshResponse(c, http.StatusOK, tokenString, expire)
  404. }
  405. // RefreshToken refresh token and check if token is expired
  406. func (mw *GinJWTMiddleware) RefreshToken(c *gin.Context) (string, time.Time, error) {
  407. claims, err := mw.CheckIfTokenExpire(c)
  408. if err != nil {
  409. return "", time.Now(), err
  410. }
  411. // Create the token
  412. newToken := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))
  413. newClaims := newToken.Claims.(jwt.MapClaims)
  414. for key := range claims {
  415. newClaims[key] = claims[key]
  416. }
  417. expire := mw.TimeFunc().Add(mw.Timeout)
  418. newClaims["exp"] = expire.Unix()
  419. newClaims["orig_iat"] = mw.TimeFunc().Unix()
  420. tokenString, err := mw.signedString(newToken)
  421. if err != nil {
  422. return "", time.Now(), err
  423. }
  424. // set cookie
  425. if mw.SendCookie {
  426. maxage := int(expire.Unix() - time.Now().Unix())
  427. c.SetCookie(
  428. mw.CookieName,
  429. tokenString,
  430. maxage,
  431. "/",
  432. mw.CookieDomain,
  433. mw.SecureCookie,
  434. mw.CookieHTTPOnly,
  435. )
  436. }
  437. return tokenString, expire, nil
  438. }
  439. // CheckIfTokenExpire check if token expire
  440. func (mw *GinJWTMiddleware) CheckIfTokenExpire(c *gin.Context) (jwt.MapClaims, error) {
  441. token, err := mw.ParseToken(c)
  442. if err != nil {
  443. // If we receive an error, and the error is anything other than a single
  444. // ValidationErrorExpired, we want to return the error.
  445. // If the error is just ValidationErrorExpired, we want to continue, as we can still
  446. // refresh the token if it's within the MaxRefresh time.
  447. // (see https://github.com/appleboy/gin-jwt/issues/176)
  448. validationErr, ok := err.(*jwt.ValidationError)
  449. if !ok || validationErr.Errors != jwt.ValidationErrorExpired {
  450. return nil, err
  451. }
  452. }
  453. claims := MapClaims(token.Claims.(jwt.MapClaims))
  454. origIat, err := claims.OrigIat()
  455. if err != nil {
  456. return nil, err
  457. }
  458. if origIat < mw.TimeFunc().Add(-mw.MaxRefresh).Unix() {
  459. return nil, ErrExpiredToken
  460. }
  461. return token.Claims.(jwt.MapClaims), nil
  462. }
  463. // TokenGenerator method that clients can use to get a jwt token.
  464. func (mw *GinJWTMiddleware) TokenGenerator(data interface{}) (string, time.Time, error) {
  465. token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))
  466. claims := token.Claims.(jwt.MapClaims)
  467. if mw.PayloadFunc != nil {
  468. for key, value := range mw.PayloadFunc(data) {
  469. claims[key] = value
  470. }
  471. }
  472. expire := mw.TimeFunc().UTC().Add(mw.Timeout)
  473. claims["exp"] = expire.Unix()
  474. claims["orig_iat"] = mw.TimeFunc().Unix()
  475. tokenString, err := mw.signedString(token)
  476. if err != nil {
  477. return "", time.Time{}, err
  478. }
  479. return tokenString, expire, nil
  480. }
  481. func (mw *GinJWTMiddleware) jwtFromHeader(c *gin.Context, key string) (string, error) {
  482. authHeader := c.Request.Header.Get(key)
  483. if authHeader == "" {
  484. return "", ErrEmptyAuthHeader
  485. }
  486. parts := strings.SplitN(authHeader, " ", 2)
  487. if !(len(parts) == 2 && parts[0] == mw.TokenHeadName) {
  488. return "", ErrInvalidAuthHeader
  489. }
  490. return parts[1], nil
  491. }
  492. func (mw *GinJWTMiddleware) jwtFromQuery(c *gin.Context, key string) (string, error) {
  493. token := c.Query(key)
  494. if token == "" {
  495. return "", ErrEmptyQueryToken
  496. }
  497. return token, nil
  498. }
  499. func (mw *GinJWTMiddleware) jwtFromCookie(c *gin.Context, key string) (string, error) {
  500. cookie, _ := c.Cookie(key)
  501. if cookie == "" {
  502. return "", ErrEmptyCookieToken
  503. }
  504. return cookie, nil
  505. }
  506. func (mw *GinJWTMiddleware) jwtFromParam(c *gin.Context, key string) (string, error) {
  507. token := c.Param(key)
  508. if token == "" {
  509. return "", ErrEmptyParamToken
  510. }
  511. return token, nil
  512. }
  513. // ParseToken parse jwt token from gin context
  514. func (mw *GinJWTMiddleware) ParseToken(c *gin.Context) (*jwt.Token, error) {
  515. var token string
  516. var err error
  517. methods := strings.Split(mw.TokenLookup, ",")
  518. for _, method := range methods {
  519. if len(token) > 0 {
  520. break
  521. }
  522. parts := strings.Split(strings.TrimSpace(method), ":")
  523. k := strings.TrimSpace(parts[0])
  524. v := strings.TrimSpace(parts[1])
  525. switch k {
  526. case "header":
  527. token, err = mw.jwtFromHeader(c, v)
  528. case "query":
  529. token, err = mw.jwtFromQuery(c, v)
  530. case "cookie":
  531. token, err = mw.jwtFromCookie(c, v)
  532. case "param":
  533. token, err = mw.jwtFromParam(c, v)
  534. }
  535. }
  536. if err != nil {
  537. return nil, err
  538. }
  539. return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
  540. if jwt.GetSigningMethod(mw.SigningAlgorithm) != t.Method {
  541. return nil, ErrInvalidSigningAlgorithm
  542. }
  543. if mw.usingPublicKeyAlgo() {
  544. return mw.pubKey, nil
  545. }
  546. c.Set(JwtTokenKey, token)
  547. return mw.Key, nil
  548. }, jwt.WithJSONNumber())
  549. }
  550. // ParseTokenString 解析jwt令牌
  551. func (mw *GinJWTMiddleware) ParseTokenString(token string) (*jwt.Token, error) {
  552. return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
  553. if jwt.GetSigningMethod(mw.SigningAlgorithm) != t.Method {
  554. return nil, ErrInvalidSigningAlgorithm
  555. }
  556. if mw.usingPublicKeyAlgo() {
  557. return mw.pubKey, nil
  558. }
  559. return mw.Key, nil
  560. })
  561. }
  562. func (mw *GinJWTMiddleware) unauthorized(c *gin.Context, code int, message string) {
  563. c.Header("WWW-Authenticate", "JWT realm="+mw.Realm)
  564. if !mw.DisabledAbort {
  565. c.Abort()
  566. }
  567. mw.Unauthorized(c, code, message)
  568. }
  569. // ExtractClaims 获取JWT声明
  570. func ExtractClaims(c *gin.Context) MapClaims {
  571. claims, exists := c.Get(JwtPayloadKey)
  572. if !exists {
  573. return make(MapClaims)
  574. }
  575. return claims.(MapClaims)
  576. }
  577. // ExtractClaimsFromToken 从令牌中获取JWT声明
  578. func ExtractClaimsFromToken(token *jwt.Token) MapClaims {
  579. if token == nil {
  580. return make(MapClaims)
  581. }
  582. claims := MapClaims{}
  583. for key, value := range token.Claims.(jwt.MapClaims) {
  584. claims[key] = value
  585. }
  586. return claims
  587. }
  588. // GetToken 获取JWT令牌
  589. func GetToken(c *gin.Context) string {
  590. token, exists := c.Get(JwtTokenKey)
  591. if !exists {
  592. return ""
  593. }
  594. return token.(string)
  595. }