jwt.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. package v1
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "github.com/golang-jwt/jwt/v4"
  7. "github.com/labstack/echo/v4"
  8. "github.com/pkg/errors"
  9. "github.com/usememos/memos/api/auth"
  10. "github.com/usememos/memos/common/util"
  11. storepb "github.com/usememos/memos/proto/gen/store"
  12. "github.com/usememos/memos/store"
  13. )
  14. const (
  15. // The key name used to store user id in the context
  16. // user id is extracted from the jwt token subject field.
  17. userIDContextKey = "user-id"
  18. )
  19. func extractTokenFromHeader(c echo.Context) (string, error) {
  20. authHeader := c.Request().Header.Get("Authorization")
  21. if authHeader == "" {
  22. return "", nil
  23. }
  24. authHeaderParts := strings.Fields(authHeader)
  25. if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
  26. return "", errors.New("Authorization header format must be Bearer {token}")
  27. }
  28. return authHeaderParts[1], nil
  29. }
  30. func findAccessToken(c echo.Context) string {
  31. // Check the HTTP request header first.
  32. accessToken, _ := extractTokenFromHeader(c)
  33. if accessToken == "" {
  34. // Check the cookie.
  35. cookie, _ := c.Cookie(auth.AccessTokenCookieName)
  36. if cookie != nil {
  37. accessToken = cookie.Value
  38. }
  39. }
  40. return accessToken
  41. }
  42. // JWTMiddleware validates the access token.
  43. func JWTMiddleware(server *APIV1Service, next echo.HandlerFunc, secret string) echo.HandlerFunc {
  44. return func(c echo.Context) error {
  45. ctx := c.Request().Context()
  46. path := c.Request().URL.Path
  47. method := c.Request().Method
  48. if server.defaultAuthSkipper(c) {
  49. return next(c)
  50. }
  51. // Skip validation for server status endpoints.
  52. if util.HasPrefixes(path, "/api/v1/ping", "/api/v1/idp", "/api/v1/status", "/api/v1/user") && path != "/api/v1/user/me" && method == http.MethodGet {
  53. return next(c)
  54. }
  55. accessToken := findAccessToken(c)
  56. if accessToken == "" {
  57. // Allow the user to access the public endpoints.
  58. if util.HasPrefixes(path, "/o") {
  59. return next(c)
  60. }
  61. // When the request is not authenticated, we allow the user to access the memo endpoints for those public memos.
  62. if util.HasPrefixes(path, "/api/v1/memo") && method == http.MethodGet {
  63. return next(c)
  64. }
  65. return echo.NewHTTPError(http.StatusUnauthorized, "Missing access token")
  66. }
  67. userID, err := getUserIDFromAccessToken(accessToken, secret)
  68. if err != nil {
  69. removeAccessTokenAndCookies(c)
  70. return echo.NewHTTPError(http.StatusUnauthorized, "Invalid or expired access token")
  71. }
  72. accessTokens, err := server.Store.GetUserAccessTokens(ctx, userID)
  73. if err != nil {
  74. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get user access tokens.").WithInternal(err)
  75. }
  76. if !validateAccessToken(accessToken, accessTokens) {
  77. removeAccessTokenAndCookies(c)
  78. return echo.NewHTTPError(http.StatusUnauthorized, "Invalid access token.")
  79. }
  80. // Even if there is no error, we still need to make sure the user still exists.
  81. user, err := server.Store.GetUser(ctx, &store.FindUser{
  82. ID: &userID,
  83. })
  84. if err != nil {
  85. return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to find user ID: %d", userID)).SetInternal(err)
  86. }
  87. if user == nil {
  88. return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Failed to find user ID: %d", userID))
  89. }
  90. // Stores userID into context.
  91. c.Set(userIDContextKey, userID)
  92. return next(c)
  93. }
  94. }
  95. func getUserIDFromAccessToken(accessToken, secret string) (int32, error) {
  96. claims := &auth.ClaimsMessage{}
  97. _, err := jwt.ParseWithClaims(accessToken, claims, func(t *jwt.Token) (any, error) {
  98. if t.Method.Alg() != jwt.SigningMethodHS256.Name {
  99. return nil, errors.Errorf("unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)
  100. }
  101. if kid, ok := t.Header["kid"].(string); ok {
  102. if kid == "v1" {
  103. return []byte(secret), nil
  104. }
  105. }
  106. return nil, errors.Errorf("unexpected access token kid=%v", t.Header["kid"])
  107. })
  108. if err != nil {
  109. return 0, errors.Wrap(err, "Invalid or expired access token")
  110. }
  111. // We either have a valid access token or we will attempt to generate new access token.
  112. userID, err := util.ConvertStringToInt32(claims.Subject)
  113. if err != nil {
  114. return 0, errors.Wrap(err, "Malformed ID in the token")
  115. }
  116. return userID, nil
  117. }
  118. func (*APIV1Service) defaultAuthSkipper(c echo.Context) bool {
  119. path := c.Path()
  120. return util.HasPrefixes(path, "/api/v1/auth")
  121. }
  122. func validateAccessToken(accessTokenString string, userAccessTokens []*storepb.AccessTokensUserSetting_AccessToken) bool {
  123. for _, userAccessToken := range userAccessTokens {
  124. if accessTokenString == userAccessToken.AccessToken {
  125. return true
  126. }
  127. }
  128. return false
  129. }