You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

jwt.go 1.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright © 2023 OpenIM open source community. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package utils
  15. import (
  16. "time"
  17. "github.com/golang-jwt/jwt/v4"
  18. "github.com/OpenIMSDK/OpenKF/server/internal/config"
  19. )
  20. type JwtClaims struct {
  21. jwt.StandardClaims
  22. }
  23. var _secret []byte
  24. var _issuer string
  25. var _expireDays int
  26. func init() {
  27. _secret = []byte(config.GetString("jwt.secret"))
  28. _issuer = config.GetString("jwt.issuer")
  29. _expireDays = config.GetInt("jwt.expire_days")
  30. }
  31. func GenerateJwtToken(claims *JwtClaims) (string, error) {
  32. claims.Issuer = _issuer
  33. claims.NotBefore = int64(time.Now().Unix())
  34. claims.ExpiresAt = int64(time.Now().AddDate(0, 0, _expireDays).Unix())
  35. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  36. return token.SignedString(_secret)
  37. }
  38. func ParseJwtToken(tokenString string) (*JwtClaims, error) {
  39. token, err := jwt.ParseWithClaims(tokenString, &JwtClaims{}, func(token *jwt.Token) (interface{}, error) {
  40. return _secret, nil
  41. })
  42. if err != nil {
  43. return nil, err
  44. }
  45. if claims, ok := token.Claims.(*JwtClaims); ok && token.Valid {
  46. return claims, nil
  47. } else {
  48. return nil, err
  49. }
  50. }