authhandler.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. package handler
  2. import (
  3. "context"
  4. "errors"
  5. "net/http"
  6. "net/http/httputil"
  7. "github.com/dgrijalva/jwt-go"
  8. "github.com/tal-tech/go-zero/core/logx"
  9. "github.com/tal-tech/go-zero/rest/token"
  10. )
  11. const (
  12. jwtAudience = "aud"
  13. jwtExpire = "exp"
  14. jwtId = "jti"
  15. jwtIssueAt = "iat"
  16. jwtIssuer = "iss"
  17. jwtNotBefore = "nbf"
  18. jwtSubject = "sub"
  19. noDetailReason = "no detail reason"
  20. )
  21. var (
  22. errInvalidToken = errors.New("invalid auth token")
  23. errNoClaims = errors.New("no auth params")
  24. )
  25. type (
  26. // A AuthorizeOptions is authorize options.
  27. AuthorizeOptions struct {
  28. PrevSecret string
  29. Callback UnauthorizedCallback
  30. }
  31. // UnauthorizedCallback defines the method of unauthorized callback.
  32. UnauthorizedCallback func(w http.ResponseWriter, r *http.Request, err error)
  33. // AuthorizeOption defines the method to customize an AuthorizeOptions.
  34. AuthorizeOption func(opts *AuthorizeOptions)
  35. )
  36. // Authorize returns an authorize middleware.
  37. func Authorize(secret string, opts ...AuthorizeOption) func(http.Handler) http.Handler {
  38. var authOpts AuthorizeOptions
  39. for _, opt := range opts {
  40. opt(&authOpts)
  41. }
  42. parser := token.NewTokenParser()
  43. return func(next http.Handler) http.Handler {
  44. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  45. tok, err := parser.ParseToken(r, secret, authOpts.PrevSecret)
  46. if err != nil {
  47. unauthorized(w, r, err, authOpts.Callback)
  48. return
  49. }
  50. if !tok.Valid {
  51. unauthorized(w, r, errInvalidToken, authOpts.Callback)
  52. return
  53. }
  54. claims, ok := tok.Claims.(jwt.MapClaims)
  55. if !ok {
  56. unauthorized(w, r, errNoClaims, authOpts.Callback)
  57. return
  58. }
  59. ctx := r.Context()
  60. for k, v := range claims {
  61. switch k {
  62. case jwtAudience, jwtExpire, jwtId, jwtIssueAt, jwtIssuer, jwtNotBefore, jwtSubject:
  63. // ignore the standard claims
  64. default:
  65. ctx = context.WithValue(ctx, k, v)
  66. }
  67. }
  68. next.ServeHTTP(w, r.WithContext(ctx))
  69. })
  70. }
  71. }
  72. // WithPrevSecret returns an AuthorizeOption with setting previous secret.
  73. func WithPrevSecret(secret string) AuthorizeOption {
  74. return func(opts *AuthorizeOptions) {
  75. opts.PrevSecret = secret
  76. }
  77. }
  78. // WithUnauthorizedCallback returns an AuthorizeOption with setting unauthorized callback.
  79. func WithUnauthorizedCallback(callback UnauthorizedCallback) AuthorizeOption {
  80. return func(opts *AuthorizeOptions) {
  81. opts.Callback = callback
  82. }
  83. }
  84. func detailAuthLog(r *http.Request, reason string) {
  85. // discard dump error, only for debug purpose
  86. details, _ := httputil.DumpRequest(r, true)
  87. logx.Errorf("authorize failed: %s\n=> %+v", reason, string(details))
  88. }
  89. func unauthorized(w http.ResponseWriter, r *http.Request, err error, callback UnauthorizedCallback) {
  90. writer := newGuardedResponseWriter(w)
  91. if err != nil {
  92. detailAuthLog(r, err.Error())
  93. } else {
  94. detailAuthLog(r, noDetailReason)
  95. }
  96. if callback != nil {
  97. callback(writer, r, err)
  98. }
  99. writer.WriteHeader(http.StatusUnauthorized)
  100. }
  101. type guardedResponseWriter struct {
  102. writer http.ResponseWriter
  103. wroteHeader bool
  104. }
  105. func newGuardedResponseWriter(w http.ResponseWriter) *guardedResponseWriter {
  106. return &guardedResponseWriter{
  107. writer: w,
  108. }
  109. }
  110. func (grw *guardedResponseWriter) Flush() {
  111. if flusher, ok := grw.writer.(http.Flusher); ok {
  112. flusher.Flush()
  113. }
  114. }
  115. func (grw *guardedResponseWriter) Header() http.Header {
  116. return grw.writer.Header()
  117. }
  118. func (grw *guardedResponseWriter) Write(body []byte) (int, error) {
  119. return grw.writer.Write(body)
  120. }
  121. func (grw *guardedResponseWriter) WriteHeader(statusCode int) {
  122. if grw.wroteHeader {
  123. return
  124. }
  125. grw.wroteHeader = true
  126. grw.writer.WriteHeader(statusCode)
  127. }