authhandler.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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. AuthorizeOptions struct {
  27. PrevSecret string
  28. Callback UnauthorizedCallback
  29. }
  30. UnauthorizedCallback func(w http.ResponseWriter, r *http.Request, err error)
  31. AuthorizeOption func(opts *AuthorizeOptions)
  32. )
  33. func Authorize(secret string, opts ...AuthorizeOption) func(http.Handler) http.Handler {
  34. var authOpts AuthorizeOptions
  35. for _, opt := range opts {
  36. opt(&authOpts)
  37. }
  38. parser := token.NewTokenParser()
  39. return func(next http.Handler) http.Handler {
  40. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  41. tok, err := parser.ParseToken(r, secret, authOpts.PrevSecret)
  42. if err != nil {
  43. unauthorized(w, r, err, authOpts.Callback)
  44. return
  45. }
  46. if !tok.Valid {
  47. unauthorized(w, r, errInvalidToken, authOpts.Callback)
  48. return
  49. }
  50. claims, ok := tok.Claims.(jwt.MapClaims)
  51. if !ok {
  52. unauthorized(w, r, errNoClaims, authOpts.Callback)
  53. return
  54. }
  55. ctx := r.Context()
  56. for k, v := range claims {
  57. switch k {
  58. case jwtAudience, jwtExpire, jwtId, jwtIssueAt, jwtIssuer, jwtNotBefore, jwtSubject:
  59. // ignore the standard claims
  60. default:
  61. ctx = context.WithValue(ctx, k, v)
  62. }
  63. }
  64. next.ServeHTTP(w, r.WithContext(ctx))
  65. })
  66. }
  67. }
  68. func WithPrevSecret(secret string) AuthorizeOption {
  69. return func(opts *AuthorizeOptions) {
  70. opts.PrevSecret = secret
  71. }
  72. }
  73. func WithUnauthorizedCallback(callback UnauthorizedCallback) AuthorizeOption {
  74. return func(opts *AuthorizeOptions) {
  75. opts.Callback = callback
  76. }
  77. }
  78. func detailAuthLog(r *http.Request, reason string) {
  79. // discard dump error, only for debug purpose
  80. details, _ := httputil.DumpRequest(r, true)
  81. logx.Errorf("authorize failed: %s\n=> %+v", reason, string(details))
  82. }
  83. func unauthorized(w http.ResponseWriter, r *http.Request, err error, callback UnauthorizedCallback) {
  84. writer := newGuardedResponseWriter(w)
  85. if err != nil {
  86. detailAuthLog(r, err.Error())
  87. } else {
  88. detailAuthLog(r, noDetailReason)
  89. }
  90. if callback != nil {
  91. callback(writer, r, err)
  92. }
  93. writer.WriteHeader(http.StatusUnauthorized)
  94. }
  95. type guardedResponseWriter struct {
  96. writer http.ResponseWriter
  97. wroteHeader bool
  98. }
  99. func newGuardedResponseWriter(w http.ResponseWriter) *guardedResponseWriter {
  100. return &guardedResponseWriter{
  101. writer: w,
  102. }
  103. }
  104. func (grw *guardedResponseWriter) Flush() {
  105. if flusher, ok := grw.writer.(http.Flusher); ok {
  106. flusher.Flush()
  107. }
  108. }
  109. func (grw *guardedResponseWriter) Header() http.Header {
  110. return grw.writer.Header()
  111. }
  112. func (grw *guardedResponseWriter) Write(body []byte) (int, error) {
  113. return grw.writer.Write(body)
  114. }
  115. func (grw *guardedResponseWriter) WriteHeader(statusCode int) {
  116. if grw.wroteHeader {
  117. return
  118. }
  119. grw.wroteHeader = true
  120. grw.writer.WriteHeader(statusCode)
  121. }