optionaljwtmiddleware.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. ctx := r.Context()
  33. if len(tokenString) > 0 {
  34. // 如果提供了 JWT 令牌,则验证它
  35. tokenValue := strings.Split(tokenString, " ")
  36. if len(tokenValue) == 2 {
  37. parsedToken, err := jwt.Parse(tokenValue[1], func(token *jwt.Token) (interface{}, error) {
  38. if _, ok := token.Method.(*jwt.SigningMethodHMAC); ok {
  39. return []byte(m.Secret), nil
  40. }
  41. return nil, errors.New("failed to parse token")
  42. })
  43. if err == nil {
  44. if claims, ok := parsedToken.Claims.(jwt.MapClaims); ok && parsedToken.Valid {
  45. // 将解析到的 claims 添加到请求上下文中
  46. for k, v := range claims {
  47. switch k {
  48. case jwtAudience, jwtExpire, jwtId, jwtIssueAt, jwtIssuer, jwtNotBefore, jwtSubject:
  49. // ignore the standard claims
  50. default:
  51. ctx = context.WithValue(ctx, k, v)
  52. }
  53. }
  54. fmt.Println("vvvvvvvv: ")
  55. }
  56. }
  57. }
  58. }
  59. newReq := r.WithContext(ctx)
  60. next(w, newReq)
  61. }
  62. }