1
0

jwtauth.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. package jwtauth
  2. import (
  3. "crypto/rsa"
  4. "errors"
  5. "github.com/dgrijalva/jwt-go"
  6. "github.com/gin-gonic/gin"
  7. "github.com/go-redis/redis/v7"
  8. "io/ioutil"
  9. "net/http"
  10. "strings"
  11. "time"
  12. )
  13. const JwtPayloadKey = "JWT_PAYLOAD"
  14. type MapClaims map[string]interface{}
  15. // GinJWTMiddleware provides a Json-Web-Token authentication implementation. On failure, a 401 HTTP response
  16. // is returned. On success, the wrapped middleware is called, and the userID is made available as
  17. // c.Get("userID").(string).
  18. // Users can get a token by posting a json request to LoginHandler. The token then needs to be passed in
  19. // the Authentication header. Example: Authorization:Bearer XXX_TOKEN_XXX
  20. type GinJWTMiddleware struct {
  21. // Realm name to display to the user. Required.
  22. Realm string
  23. // signing algorithm - possible values are HS256, HS384, HS512
  24. // Optional, default is HS256.
  25. SigningAlgorithm string
  26. // Secret key used for signing. Required.
  27. Key []byte
  28. // Duration that a jwt token is valid. Optional, defaults to one hour.
  29. Timeout time.Duration
  30. // This field allows clients to refresh their token until MaxRefresh has passed.
  31. // Note that clients can refresh their token in the last moment of MaxRefresh.
  32. // This means that the maximum validity timespan for a token is TokenTime + MaxRefresh.
  33. // Optional, defaults to 0 meaning not refreshable.
  34. MaxRefresh time.Duration
  35. // Callback function that should perform the authentication of the user based on login info.
  36. // Must return user data as user identifier, it will be stored in Claim Array. Required.
  37. // Check error (e) to determine the appropriate error message.
  38. Authenticator func(c *gin.Context) (interface{}, error)
  39. // Callback function that should perform the authorization of the authenticated user. Called
  40. // only after an authentication success. Must return true on success, false on failure.
  41. // Optional, default to success.
  42. Authorizator func(data interface{}, c *gin.Context) bool
  43. CheckUserAccount func(id int64, c *gin.Context) error
  44. // Callback function that will be called during login.
  45. // Using this function it is possible to add additional payload data to the webtoken.
  46. // The data is then made available during requests via c.Get("JWT_PAYLOAD").
  47. // Note that the payload is not encrypted.
  48. // The attributes mentioned on jwt.io can't be used as keys for the map.
  49. // Optional, by default no additional data will be set.
  50. PayloadFunc func(data interface{}) MapClaims
  51. // User can define own Unauthorized func.
  52. Unauthorized func(*gin.Context, int, string)
  53. // User can define own LoginResponse func.
  54. LoginResponse func(*gin.Context, int, string, time.Time)
  55. // User can define own RefreshResponse func.
  56. RefreshResponse func(*gin.Context, int, string, time.Time)
  57. // Set the identity handler function
  58. IdentityHandler func(*gin.Context) interface{}
  59. // Set the identity key
  60. IdentityKey string
  61. // username
  62. NiceKey string
  63. DataScopeKey string
  64. // rolekey
  65. RKey string
  66. // roleId
  67. RoleIdKey string
  68. RoleKey string
  69. // roleName
  70. RoleNameKey string
  71. // TokenLookup is a string in the form of "<source>:<name>" that is used
  72. // to extract token from the request.
  73. // Optional. Default value "header:Authorization".
  74. // Possible values:
  75. // - "header:<name>"
  76. // - "query:<name>"
  77. // - "cookie:<name>"
  78. TokenLookup string
  79. // TokenHeadName is a string in the header. Default value is "Bearer"
  80. TokenHeadName string
  81. // 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.
  82. TimeFunc func() time.Time
  83. // HTTP Status messages for when something in the JWT middleware fails.
  84. // Check error (e) to determine the appropriate error message.
  85. HTTPStatusMessageFunc func(e error, c *gin.Context) string
  86. // Private key file for asymmetric algorithms
  87. PrivKeyFile string
  88. // Public key file for asymmetric algorithms
  89. PubKeyFile string
  90. // Private key
  91. privKey *rsa.PrivateKey
  92. // Public key
  93. pubKey *rsa.PublicKey
  94. // Optionally return the token as a cookie
  95. SendCookie bool
  96. // Allow insecure cookies for development over http
  97. SecureCookie bool
  98. // Allow cookies to be accessed client side for development
  99. CookieHTTPOnly bool
  100. // Allow cookie domain change for development
  101. CookieDomain string
  102. // SendAuthorization allow return authorization header for every request
  103. SendAuthorization bool
  104. // Disable abort() of context.
  105. DisabledAbort bool
  106. // CookieName allow cookie name change for development
  107. CookieName string
  108. // 单一登录
  109. SingleLogin func(c *gin.Context) (bool, error)
  110. // 保存token的key
  111. TokenCachekey string
  112. // 保存token的key
  113. SaveTokenToCache func(c *gin.Context, userId int64, key, token string, expire int64) error
  114. GetTokenToCache func(c *gin.Context, userId int64, key string) (string, error)
  115. }
  116. var (
  117. // ErrMissingSecretKey indicates Secret key is required
  118. ErrMissingSecretKey = errors.New("secret key is required")
  119. // ErrForbidden when HTTP status 403 is given
  120. ErrForbidden = errors.New("you don't have permission to access this resource")
  121. // ErrMissingAuthenticatorFunc indicates Authenticator is required
  122. ErrMissingAuthenticatorFunc = errors.New("ginJWTMiddleware.Authenticator func is undefined")
  123. // ErrMissingLoginValues indicates a user tried to authenticate without username or password
  124. ErrMissingLoginValues = errors.New("missing Username or Password or Code")
  125. // ErrFailedAuthentication indicates authentication failed, could be faulty username or password
  126. //ErrFailedAuthentication = errors.New("incorrect Username or Password")
  127. ErrFailedAuthentication = errors.New("用户名或密码不正确")
  128. ErrAccountDeactivated = errors.New("账号已停用")
  129. // ErrFailedTokenCreation indicates JWT Token failed to create, reason unknown
  130. ErrFailedTokenCreation = errors.New("failed to create JWT Token")
  131. // ErrExpiredToken indicates JWT token has expired. Can't refresh.
  132. ErrExpiredToken = errors.New("token is expired")
  133. // ErrEmptyAuthHeader can be thrown if authing with a HTTP header, the Auth header needs to be set
  134. ErrEmptyAuthHeader = errors.New("auth header is empty")
  135. // ErrMissingExpField missing exp field in token
  136. ErrMissingExpField = errors.New("missing exp field")
  137. // ErrWrongFormatOfExp field must be float64 format
  138. ErrWrongFormatOfExp = errors.New("exp must be float64 format")
  139. // ErrInvalidAuthHeader indicates auth header is invalid, could for example have the wrong Realm name
  140. ErrInvalidAuthHeader = errors.New("auth header is invalid")
  141. // ErrEmptyQueryToken can be thrown if authing with URL Query, the query token variable is empty
  142. ErrEmptyQueryToken = errors.New("query token is empty")
  143. // ErrEmptyCookieToken can be thrown if authing with a cookie, the token cokie is empty
  144. ErrEmptyCookieToken = errors.New("cookie token is empty")
  145. // ErrEmptyParamToken can be thrown if authing with parameter in path, the parameter in path is empty
  146. ErrEmptyParamToken = errors.New("parameter token is empty")
  147. // ErrInvalidSigningAlgorithm indicates signing algorithm is invalid, needs to be HS256, HS384, HS512, RS256, RS384 or RS512
  148. ErrInvalidSigningAlgorithm = errors.New("invalid signing algorithm")
  149. ErrInvalidVerificationCode = errors.New("验证码错误")
  150. // ErrNoPrivKeyFile indicates that the given private key is unreadable
  151. ErrNoPrivKeyFile = errors.New("private key file unreadable")
  152. // ErrNoPubKeyFile indicates that the given public key is unreadable
  153. ErrNoPubKeyFile = errors.New("public key file unreadable")
  154. // ErrInvalidPrivKey indicates that the given private key is invalid
  155. ErrInvalidPrivKey = errors.New("private key invalid")
  156. // ErrInvalidPubKey indicates the the given public key is invalid
  157. ErrInvalidPubKey = errors.New("public key invalid")
  158. UUIDKey = "uuid"
  159. // IdentityKey default identity key
  160. IdentityKey = "identity"
  161. // NiceKey 昵称
  162. UserNameKey = "username"
  163. DataScopeKey = "dataScope"
  164. // RoleIdKey 角色id Old
  165. RoleIdKey = "roleId"
  166. // RoleKey 角色key Old
  167. RoleKey = "roleKey"
  168. // RoleNameKey 角色名称 Old
  169. RoleNameKey = "roleName"
  170. )
  171. // New for check error with GinJWTMiddleware
  172. func New(m *GinJWTMiddleware) (*GinJWTMiddleware, error) {
  173. if err := m.MiddlewareInit(); err != nil {
  174. return nil, err
  175. }
  176. return m, nil
  177. }
  178. func (mw *GinJWTMiddleware) readKeys() error {
  179. err := mw.privateKey()
  180. if err != nil {
  181. return err
  182. }
  183. err = mw.publicKey()
  184. if err != nil {
  185. return err
  186. }
  187. return nil
  188. }
  189. func (mw *GinJWTMiddleware) privateKey() error {
  190. keyData, err := ioutil.ReadFile(mw.PrivKeyFile)
  191. if err != nil {
  192. return ErrNoPrivKeyFile
  193. }
  194. key, err := jwt.ParseRSAPrivateKeyFromPEM(keyData)
  195. if err != nil {
  196. return ErrInvalidPrivKey
  197. }
  198. mw.privKey = key
  199. return nil
  200. }
  201. func (mw *GinJWTMiddleware) publicKey() error {
  202. keyData, err := ioutil.ReadFile(mw.PubKeyFile)
  203. if err != nil {
  204. return ErrNoPubKeyFile
  205. }
  206. key, err := jwt.ParseRSAPublicKeyFromPEM(keyData)
  207. if err != nil {
  208. return ErrInvalidPubKey
  209. }
  210. mw.pubKey = key
  211. return nil
  212. }
  213. func (mw *GinJWTMiddleware) usingPublicKeyAlgo() bool {
  214. switch mw.SigningAlgorithm {
  215. case "RS256", "RS512", "RS384":
  216. return true
  217. }
  218. return false
  219. }
  220. // MiddlewareInit initialize jwt configs.
  221. func (mw *GinJWTMiddleware) MiddlewareInit() error {
  222. if mw.TokenLookup == "" {
  223. mw.TokenLookup = "header:Authorization"
  224. }
  225. if mw.SigningAlgorithm == "" {
  226. mw.SigningAlgorithm = "HS256"
  227. }
  228. if mw.TimeFunc == nil {
  229. mw.TimeFunc = time.Now
  230. }
  231. mw.TokenHeadName = strings.TrimSpace(mw.TokenHeadName)
  232. if len(mw.TokenHeadName) == 0 {
  233. mw.TokenHeadName = "Bearer"
  234. }
  235. if mw.Authorizator == nil {
  236. mw.Authorizator = func(data interface{}, c *gin.Context) bool {
  237. return true
  238. }
  239. }
  240. if mw.Unauthorized == nil {
  241. mw.Unauthorized = func(c *gin.Context, code int, message string) {
  242. c.JSON(http.StatusOK, gin.H{
  243. "code": code,
  244. "message": message,
  245. })
  246. }
  247. }
  248. if mw.LoginResponse == nil {
  249. mw.LoginResponse = func(c *gin.Context, code int, token string, expire time.Time) {
  250. c.JSON(http.StatusOK, gin.H{
  251. "code": http.StatusOK,
  252. "token": token,
  253. "expire": expire.Format(time.RFC3339),
  254. })
  255. }
  256. }
  257. if mw.RefreshResponse == nil {
  258. mw.RefreshResponse = func(c *gin.Context, code int, token string, expire time.Time) {
  259. c.JSON(http.StatusOK, gin.H{
  260. "code": http.StatusOK,
  261. "token": token,
  262. "expire": expire.Format(time.RFC3339),
  263. })
  264. }
  265. }
  266. if mw.IdentityKey == "" {
  267. mw.IdentityKey = IdentityKey
  268. }
  269. if mw.IdentityHandler == nil {
  270. mw.IdentityHandler = func(c *gin.Context) interface{} {
  271. claims := ExtractClaims(c)
  272. return claims
  273. }
  274. }
  275. if mw.HTTPStatusMessageFunc == nil {
  276. mw.HTTPStatusMessageFunc = func(e error, c *gin.Context) string {
  277. return e.Error()
  278. }
  279. }
  280. if mw.Realm == "" {
  281. mw.Realm = "gin jwt"
  282. }
  283. if mw.CookieName == "" {
  284. mw.CookieName = "jwt"
  285. }
  286. if mw.usingPublicKeyAlgo() {
  287. return mw.readKeys()
  288. }
  289. if mw.Key == nil {
  290. return ErrMissingSecretKey
  291. }
  292. return nil
  293. }
  294. // MiddlewareFunc makes GinJWTMiddleware implement the Middleware interface.
  295. func (mw *GinJWTMiddleware) MiddlewareFunc() gin.HandlerFunc {
  296. return func(c *gin.Context) {
  297. mw.middlewareImpl(c)
  298. }
  299. }
  300. func (mw *GinJWTMiddleware) middlewareImpl(c *gin.Context) {
  301. claims, err := mw.GetClaimsFromJWT(c)
  302. if err != nil {
  303. mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(err, c))
  304. return
  305. }
  306. if claims["exp"] == nil {
  307. mw.unauthorized(c, http.StatusBadRequest, mw.HTTPStatusMessageFunc(ErrMissingExpField, c))
  308. return
  309. }
  310. if _, ok := claims["exp"].(float64); !ok {
  311. mw.unauthorized(c, http.StatusBadRequest, mw.HTTPStatusMessageFunc(ErrWrongFormatOfExp, c))
  312. return
  313. }
  314. if int64(claims["exp"].(float64)) < mw.TimeFunc().Unix() {
  315. mw.unauthorized(c, 6401, mw.HTTPStatusMessageFunc(ErrExpiredToken, c))
  316. return
  317. }
  318. c.Set(JwtPayloadKey, claims)
  319. identity := mw.IdentityHandler(c)
  320. if identity != nil {
  321. c.Set(mw.IdentityKey, identity)
  322. }
  323. if !mw.Authorizator(identity, c) {
  324. mw.unauthorized(c, http.StatusForbidden, mw.HTTPStatusMessageFunc(ErrForbidden, c))
  325. return
  326. }
  327. if err = mw.CheckUserAccount(int64(claims["identity"].(float64)), c); err != nil {
  328. mw.unauthorized(c, http.StatusBadRequest, mw.HTTPStatusMessageFunc(err, c))
  329. return
  330. }
  331. if flag, _ := mw.SingleLogin(c); flag == true {
  332. token, err := mw.GetTokenToCache(c, int64(claims["identity"].(float64)), mw.TokenCachekey)
  333. if err != nil && errors.Is(err, redis.Nil) {
  334. mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrExpiredToken, c))
  335. return
  336. }
  337. if token != GetToken(c) {
  338. mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrExpiredToken, c))
  339. return
  340. }
  341. }
  342. c.Next()
  343. }
  344. // GetClaimsFromJWT get claims from JWT token
  345. func (mw *GinJWTMiddleware) GetClaimsFromJWT(c *gin.Context) (MapClaims, error) {
  346. token, err := mw.ParseToken(c)
  347. if err != nil {
  348. return nil, err
  349. }
  350. if mw.SendAuthorization {
  351. if v, ok := c.Get("JWT_TOKEN"); ok {
  352. c.Header("Authorization", mw.TokenHeadName+" "+v.(string))
  353. }
  354. }
  355. claims := MapClaims{}
  356. for key, value := range token.Claims.(jwt.MapClaims) {
  357. claims[key] = value
  358. }
  359. return claims, nil
  360. }
  361. // LoginHandler can be used by clients to get a jwt token.
  362. // Payload needs to be json in the form of {"username": "USERNAME", "password": "PASSWORD"}.
  363. // Reply will be of the form {"token": "TOKEN"}.
  364. func (mw *GinJWTMiddleware) LoginHandler(c *gin.Context) {
  365. if mw.Authenticator == nil {
  366. mw.unauthorized(c, http.StatusInternalServerError, mw.HTTPStatusMessageFunc(ErrMissingAuthenticatorFunc, c))
  367. return
  368. }
  369. data, err := mw.Authenticator(c)
  370. if err != nil {
  371. mw.unauthorized(c, 400, mw.HTTPStatusMessageFunc(err, c))
  372. return
  373. }
  374. // Create the token
  375. token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))
  376. claims := token.Claims.(jwt.MapClaims)
  377. if mw.PayloadFunc != nil {
  378. for key, value := range mw.PayloadFunc(data) {
  379. claims[key] = value
  380. }
  381. }
  382. expire := mw.TimeFunc().Add(mw.Timeout)
  383. claims["exp"] = expire.Unix()
  384. claims["orig_iat"] = mw.TimeFunc().Unix()
  385. tokenString, err := mw.signedString(token)
  386. if err != nil {
  387. mw.unauthorized(c, http.StatusInternalServerError, mw.HTTPStatusMessageFunc(ErrFailedTokenCreation, c))
  388. return
  389. }
  390. // set cookie
  391. if mw.SendCookie {
  392. maxage := int(expire.Unix() - time.Now().Unix())
  393. c.SetCookie(
  394. mw.CookieName,
  395. tokenString,
  396. maxage,
  397. "/",
  398. mw.CookieDomain,
  399. mw.SecureCookie,
  400. mw.CookieHTTPOnly,
  401. )
  402. }
  403. if flag, _ := mw.SingleLogin(c); flag == true {
  404. _ = mw.SaveTokenToCache(c, int64(claims["identity"].(int)), mw.TokenCachekey, tokenString, int64(mw.Timeout)/3600)
  405. }
  406. mw.LoginResponse(c, http.StatusOK, tokenString, expire)
  407. }
  408. func (mw *GinJWTMiddleware) signedString(token *jwt.Token) (string, error) {
  409. var tokenString string
  410. var err error
  411. if mw.usingPublicKeyAlgo() {
  412. tokenString, err = token.SignedString(mw.privKey)
  413. } else {
  414. tokenString, err = token.SignedString(mw.Key)
  415. }
  416. return tokenString, err
  417. }
  418. // RefreshHandler can be used to refresh a token. The token still needs to be valid on refresh.
  419. // Shall be put under an endpoint that is using the GinJWTMiddleware.
  420. // Reply will be of the form {"token": "TOKEN"}.
  421. func (mw *GinJWTMiddleware) RefreshHandler(c *gin.Context) {
  422. tokenString, expire, err := mw.RefreshToken(c)
  423. if err != nil {
  424. mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(err, c))
  425. return
  426. }
  427. mw.RefreshResponse(c, http.StatusOK, tokenString, expire)
  428. }
  429. // RefreshToken refresh token and check if token is expired
  430. func (mw *GinJWTMiddleware) RefreshToken(c *gin.Context) (string, time.Time, error) {
  431. claims, err := mw.CheckIfTokenExpire(c)
  432. if err != nil {
  433. return "", time.Now(), err
  434. }
  435. // Create the token
  436. newToken := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))
  437. newClaims := newToken.Claims.(jwt.MapClaims)
  438. for key := range claims {
  439. newClaims[key] = claims[key]
  440. }
  441. expire := mw.TimeFunc().Add(mw.Timeout)
  442. newClaims["exp"] = expire.Unix()
  443. newClaims["orig_iat"] = mw.TimeFunc().Unix()
  444. tokenString, err := mw.signedString(newToken)
  445. if err != nil {
  446. return "", time.Now(), err
  447. }
  448. // set cookie
  449. if mw.SendCookie {
  450. maxage := int(expire.Unix() - time.Now().Unix())
  451. c.SetCookie(
  452. mw.CookieName,
  453. tokenString,
  454. maxage,
  455. "/",
  456. mw.CookieDomain,
  457. mw.SecureCookie,
  458. mw.CookieHTTPOnly,
  459. )
  460. }
  461. if flag, _ := mw.SingleLogin(c); flag == true {
  462. _ = mw.SaveTokenToCache(c, int64(claims["identity"].(int)), mw.TokenCachekey, tokenString, int64(mw.Timeout)/3600)
  463. }
  464. return tokenString, expire, nil
  465. }
  466. // CheckIfTokenExpire check if token expire
  467. func (mw *GinJWTMiddleware) CheckIfTokenExpire(c *gin.Context) (jwt.MapClaims, error) {
  468. token, err := mw.ParseToken(c)
  469. if err != nil {
  470. // If we receive an error, and the error is anything other than a single
  471. // ValidationErrorExpired, we want to return the error.
  472. // If the error is just ValidationErrorExpired, we want to continue, as we can still
  473. // refresh the token if it's within the MaxRefresh time.
  474. // (see https://github.com/appleboy/gin-jwt/issues/176)
  475. validationErr, ok := err.(*jwt.ValidationError)
  476. if !ok || validationErr.Errors != jwt.ValidationErrorExpired {
  477. return nil, err
  478. }
  479. }
  480. claims := token.Claims.(jwt.MapClaims)
  481. origIat := int64(claims["orig_iat"].(float64))
  482. if origIat < mw.TimeFunc().Add(-mw.MaxRefresh).Unix() {
  483. return nil, ErrExpiredToken
  484. }
  485. return claims, nil
  486. }
  487. // TokenGenerator method that clients can use to get a jwt token.
  488. func (mw *GinJWTMiddleware) TokenGenerator(data interface{}) (string, time.Time, error) {
  489. token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))
  490. claims := token.Claims.(jwt.MapClaims)
  491. if mw.PayloadFunc != nil {
  492. for key, value := range mw.PayloadFunc(data) {
  493. claims[key] = value
  494. }
  495. }
  496. expire := mw.TimeFunc().UTC().Add(mw.Timeout)
  497. claims["exp"] = expire.Unix()
  498. claims["orig_iat"] = mw.TimeFunc().Unix()
  499. tokenString, err := mw.signedString(token)
  500. if err != nil {
  501. return "", time.Time{}, err
  502. }
  503. return tokenString, expire, nil
  504. }
  505. func (mw *GinJWTMiddleware) jwtFromHeader(c *gin.Context, key string) (string, error) {
  506. authHeader := c.Request.Header.Get(key)
  507. if authHeader == "" {
  508. return "", ErrEmptyAuthHeader
  509. }
  510. parts := strings.SplitN(authHeader, " ", 2)
  511. if !(len(parts) == 2 && parts[0] == mw.TokenHeadName) {
  512. return "", ErrInvalidAuthHeader
  513. }
  514. return parts[1], nil
  515. }
  516. func (mw *GinJWTMiddleware) jwtFromQuery(c *gin.Context, key string) (string, error) {
  517. token := c.Query(key)
  518. if token == "" {
  519. return "", ErrEmptyQueryToken
  520. }
  521. return token, nil
  522. }
  523. func (mw *GinJWTMiddleware) jwtFromCookie(c *gin.Context, key string) (string, error) {
  524. cookie, _ := c.Cookie(key)
  525. if cookie == "" {
  526. return "", ErrEmptyCookieToken
  527. }
  528. return cookie, nil
  529. }
  530. func (mw *GinJWTMiddleware) jwtFromParam(c *gin.Context, key string) (string, error) {
  531. token := c.Param(key)
  532. if token == "" {
  533. return "", ErrEmptyParamToken
  534. }
  535. return token, nil
  536. }
  537. // ParseToken parse jwt token from gin context
  538. func (mw *GinJWTMiddleware) ParseToken(c *gin.Context) (*jwt.Token, error) {
  539. var token string
  540. var err error
  541. methods := strings.Split(mw.TokenLookup, ",")
  542. for _, method := range methods {
  543. if len(token) > 0 {
  544. break
  545. }
  546. parts := strings.Split(strings.TrimSpace(method), ":")
  547. k := strings.TrimSpace(parts[0])
  548. v := strings.TrimSpace(parts[1])
  549. switch k {
  550. case "header":
  551. token, err = mw.jwtFromHeader(c, v)
  552. case "query":
  553. token, err = mw.jwtFromQuery(c, v)
  554. case "cookie":
  555. token, err = mw.jwtFromCookie(c, v)
  556. case "param":
  557. token, err = mw.jwtFromParam(c, v)
  558. }
  559. }
  560. if err != nil {
  561. return nil, err
  562. }
  563. return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
  564. if jwt.GetSigningMethod(mw.SigningAlgorithm) != t.Method {
  565. return nil, ErrInvalidSigningAlgorithm
  566. }
  567. if mw.usingPublicKeyAlgo() {
  568. return mw.pubKey, nil
  569. }
  570. c.Set("JWT_TOKEN", token)
  571. return mw.Key, nil
  572. })
  573. }
  574. // ParseTokenString parse jwt token string
  575. func (mw *GinJWTMiddleware) ParseTokenString(token string) (*jwt.Token, error) {
  576. return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
  577. if jwt.GetSigningMethod(mw.SigningAlgorithm) != t.Method {
  578. return nil, ErrInvalidSigningAlgorithm
  579. }
  580. if mw.usingPublicKeyAlgo() {
  581. return mw.pubKey, nil
  582. }
  583. return mw.Key, nil
  584. })
  585. }
  586. func (mw *GinJWTMiddleware) unauthorized(c *gin.Context, code int, message string) {
  587. c.Header("WWW-Authenticate", "JWT realm="+mw.Realm)
  588. if !mw.DisabledAbort {
  589. c.Abort()
  590. }
  591. mw.Unauthorized(c, code, message)
  592. }
  593. // ExtractClaims help to extract the JWT claims
  594. func ExtractClaims(c *gin.Context) MapClaims {
  595. claims, exists := c.Get(JwtPayloadKey)
  596. if !exists {
  597. return make(MapClaims)
  598. }
  599. return claims.(MapClaims)
  600. }
  601. // ExtractClaimsFromToken help to extract the JWT claims from token
  602. func ExtractClaimsFromToken(token *jwt.Token) MapClaims {
  603. if token == nil {
  604. return make(MapClaims)
  605. }
  606. claims := MapClaims{}
  607. for key, value := range token.Claims.(jwt.MapClaims) {
  608. claims[key] = value
  609. }
  610. return claims
  611. }
  612. // GetToken help to get the JWT token string
  613. func GetToken(c *gin.Context) string {
  614. token, exists := c.Get("JWT_TOKEN")
  615. if !exists {
  616. return ""
  617. }
  618. return token.(string)
  619. }