jwtauth.go 19 KB

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