optionaljwtmiddleware.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package middleware
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. "github.com/golang-jwt/jwt/v4"
  9. )
  10. const (
  11. jwtAudience = "aud"
  12. jwtExpire = "exp"
  13. jwtId = "jti"
  14. jwtIssueAt = "iat"
  15. jwtIssuer = "iss"
  16. jwtNotBefore = "nbf"
  17. jwtSubject = "sub"
  18. noDetailReason = "no detail reason"
  19. )
  20. type OptionalJwtMiddleware struct {
  21. Secret string
  22. }
  23. func NewOptionalJwtMiddleware(secret string) *OptionalJwtMiddleware {
  24. return &OptionalJwtMiddleware{
  25. Secret: secret,
  26. }
  27. }
  28. func (m *OptionalJwtMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
  29. return func(w http.ResponseWriter, r *http.Request) {
  30. // 尝试从请求头中获取 JWT 令牌
  31. tokenString := r.Header.Get("Authorization")
  32. fmt.Println("token: ", tokenString)
  33. ctx := r.Context()
  34. if len(tokenString) > 0 {
  35. // 如果提供了 JWT 令牌,则验证它
  36. tokenValue := strings.Split(tokenString, " ")
  37. fmt.Println(tokenValue)
  38. if len(tokenValue) == 2 {
  39. parsedToken, err := jwt.Parse(tokenValue[1], func(token *jwt.Token) (interface{}, error) {
  40. if _, ok := token.Method.(*jwt.SigningMethodHMAC); ok {
  41. return []byte(m.Secret), nil
  42. }
  43. return nil, errors.New("failed to parse token")
  44. })
  45. if err == nil {
  46. if claims, ok := parsedToken.Claims.(jwt.MapClaims); ok && parsedToken.Valid {
  47. // 将解析到的 claims 添加到请求上下文中
  48. for k, v := range claims {
  49. switch k {
  50. case jwtAudience, jwtExpire, jwtId, jwtIssueAt, jwtIssuer, jwtNotBefore, jwtSubject:
  51. // ignore the standard claims
  52. default:
  53. ctx = context.WithValue(ctx, k, v)
  54. }
  55. }
  56. }
  57. }
  58. }
  59. }
  60. newReq := r.WithContext(ctx)
  61. next(w, newReq)
  62. }
  63. }