chore: update audience name (#1484)

pull/1490/head
boojack 2 years ago committed by GitHub
parent d0ddac296f
commit 204c03e772
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -44,7 +44,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group, secret string) {
return echo.NewHTTPError(http.StatusUnauthorized, "Incorrect login credentials, please try again") return echo.NewHTTPError(http.StatusUnauthorized, "Incorrect login credentials, please try again")
} }
if err := GenerateTokensAndSetCookies(c, user, s.Profile.Mode, secret); err != nil { if err := GenerateTokensAndSetCookies(c, user, secret); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate tokens").SetInternal(err) return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate tokens").SetInternal(err)
} }
if err := s.createUserAuthSignInActivity(c, user); err != nil { if err := s.createUserAuthSignInActivity(c, user); err != nil {
@ -128,7 +128,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group, secret string) {
return echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("User has been archived with username %s", userInfo.Identifier)) return echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("User has been archived with username %s", userInfo.Identifier))
} }
if err := GenerateTokensAndSetCookies(c, user, s.Profile.Mode, secret); err != nil { if err := GenerateTokensAndSetCookies(c, user, secret); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate tokens").SetInternal(err) return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate tokens").SetInternal(err)
} }
if err := s.createUserAuthSignInActivity(c, user); err != nil { if err := s.createUserAuthSignInActivity(c, user); err != nil {
@ -196,7 +196,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group, secret string) {
if err != nil { if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create user").SetInternal(err) return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create user").SetInternal(err)
} }
if err := GenerateTokensAndSetCookies(c, user, s.Profile.Mode, secret); err != nil { if err := GenerateTokensAndSetCookies(c, user, secret); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate tokens").SetInternal(err) return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate tokens").SetInternal(err)
} }
if err := s.createUserAuthSignUpActivity(c, user); err != nil { if err := s.createUserAuthSignUpActivity(c, user); err != nil {

@ -1,7 +1,6 @@
package auth package auth
import ( import (
"fmt"
"strconv" "strconv"
"time" "time"
@ -13,13 +12,13 @@ const (
// Signing key section. For now, this is only used for signing, not for verifying since we only // Signing key section. For now, this is only used for signing, not for verifying since we only
// have 1 version. But it will be used to maintain backward compatibility if we change the signing mechanism. // have 1 version. But it will be used to maintain backward compatibility if we change the signing mechanism.
keyID = "v1" keyID = "v1"
// AccessTokenAudienceFmt is the format of the acccess token audience. // AccessTokenAudienceName is the audience name of the access token.
AccessTokenAudienceFmt = "user.access.%s" AccessTokenAudienceName = "user.access-token"
// RefreshTokenAudienceFmt is the format of the refresh token audience. // RefreshTokenAudienceName is the audience name of the refresh token.
RefreshTokenAudienceFmt = "user.refresh.%s" RefreshTokenAudienceName = "user.refresh-token"
apiTokenDuration = 2 * time.Hour apiTokenDuration = 2 * time.Hour
accessTokenDuration = 24 * time.Hour accessTokenDuration = 24 * time.Hour
refreshTokenDuration = 7 * 24 * time.Hour refreshTokenDuration = 7 * 24 * time.Hour
// RefreshThresholdDuration is the threshold duration for refreshing token. // RefreshThresholdDuration is the threshold duration for refreshing token.
RefreshThresholdDuration = 1 * time.Hour RefreshThresholdDuration = 1 * time.Hour
@ -43,21 +42,21 @@ type claimsMessage struct {
} }
// GenerateAPIToken generates an API token. // GenerateAPIToken generates an API token.
func GenerateAPIToken(userName string, userID int, mode string, secret string) (string, error) { func GenerateAPIToken(userName string, userID int, secret string) (string, error) {
expirationTime := time.Now().Add(apiTokenDuration) expirationTime := time.Now().Add(apiTokenDuration)
return generateToken(userName, userID, fmt.Sprintf(AccessTokenAudienceFmt, mode), expirationTime, []byte(secret)) return generateToken(userName, userID, AccessTokenAudienceName, expirationTime, []byte(secret))
} }
// GenerateAccessToken generates an access token for web. // GenerateAccessToken generates an access token for web.
func GenerateAccessToken(userName string, userID int, mode string, secret string) (string, error) { func GenerateAccessToken(userName string, userID int, secret string) (string, error) {
expirationTime := time.Now().Add(accessTokenDuration) expirationTime := time.Now().Add(accessTokenDuration)
return generateToken(userName, userID, fmt.Sprintf(AccessTokenAudienceFmt, mode), expirationTime, []byte(secret)) return generateToken(userName, userID, AccessTokenAudienceName, expirationTime, []byte(secret))
} }
// GenerateRefreshToken generates a refresh token for web. // GenerateRefreshToken generates a refresh token for web.
func GenerateRefreshToken(userName string, userID int, mode string, secret string) (string, error) { func GenerateRefreshToken(userName string, userID int, secret string) (string, error) {
expirationTime := time.Now().Add(refreshTokenDuration) expirationTime := time.Now().Add(refreshTokenDuration)
return generateToken(userName, userID, fmt.Sprintf(RefreshTokenAudienceFmt, mode), expirationTime, []byte(secret)) return generateToken(userName, userID, RefreshTokenAudienceName, expirationTime, []byte(secret))
} }
func generateToken(username string, userID int, aud string, expirationTime time.Time, secret []byte) (string, error) { func generateToken(username string, userID int, aud string, expirationTime time.Time, secret []byte) (string, error) {

@ -34,8 +34,8 @@ func getUserIDContextKey() string {
} }
// GenerateTokensAndSetCookies generates jwt token and saves it to the http-only cookie. // GenerateTokensAndSetCookies generates jwt token and saves it to the http-only cookie.
func GenerateTokensAndSetCookies(c echo.Context, user *api.User, mode string, secret string) error { func GenerateTokensAndSetCookies(c echo.Context, user *api.User, secret string) error {
accessToken, err := auth.GenerateAccessToken(user.Username, user.ID, mode, secret) accessToken, err := auth.GenerateAccessToken(user.Username, user.ID, secret)
if err != nil { if err != nil {
return errors.Wrap(err, "failed to generate access token") return errors.Wrap(err, "failed to generate access token")
} }
@ -44,7 +44,7 @@ func GenerateTokensAndSetCookies(c echo.Context, user *api.User, mode string, se
setTokenCookie(c, auth.AccessTokenCookieName, accessToken, cookieExp) setTokenCookie(c, auth.AccessTokenCookieName, accessToken, cookieExp)
// We generate here a new refresh token and saving it to the cookie. // We generate here a new refresh token and saving it to the cookie.
refreshToken, err := auth.GenerateRefreshToken(user.Username, user.ID, mode, secret) refreshToken, err := auth.GenerateRefreshToken(user.Username, user.ID, secret)
if err != nil { if err != nil {
return errors.Wrap(err, "failed to generate refresh token") return errors.Wrap(err, "failed to generate refresh token")
} }
@ -108,7 +108,6 @@ func JWTMiddleware(server *Server, next echo.HandlerFunc, secret string) echo.Ha
return func(c echo.Context) error { return func(c echo.Context) error {
path := c.Request().URL.Path path := c.Request().URL.Path
method := c.Request().Method method := c.Request().Method
mode := server.Profile.Mode
if server.defaultAuthSkipper(c) { if server.defaultAuthSkipper(c) {
return next(c) return next(c)
@ -145,11 +144,11 @@ func JWTMiddleware(server *Server, next echo.HandlerFunc, secret string) echo.Ha
return nil, errors.Errorf("unexpected access token kid=%v", t.Header["kid"]) return nil, errors.Errorf("unexpected access token kid=%v", t.Header["kid"])
}) })
if !audienceContains(claims.Audience, fmt.Sprintf(auth.AccessTokenAudienceFmt, mode)) { if !audienceContains(claims.Audience, auth.AccessTokenAudienceName) {
return echo.NewHTTPError(http.StatusUnauthorized, return echo.NewHTTPError(http.StatusUnauthorized,
fmt.Sprintf("Invalid access token, audience mismatch, got %q, expected %q. you may send request to the wrong environment", fmt.Sprintf("Invalid access token, audience mismatch, got %q, expected %q. you may send request to the wrong environment",
claims.Audience, claims.Audience,
fmt.Sprintf(auth.AccessTokenAudienceFmt, mode), auth.AccessTokenAudienceName,
)) ))
} }
@ -218,17 +217,17 @@ func JWTMiddleware(server *Server, next echo.HandlerFunc, secret string) echo.Ha
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to refresh expired token. User Id %d", userID)).SetInternal(err) return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to refresh expired token. User Id %d", userID)).SetInternal(err)
} }
if !audienceContains(refreshTokenClaims.Audience, fmt.Sprintf(auth.RefreshTokenAudienceFmt, mode)) { if !audienceContains(refreshTokenClaims.Audience, auth.RefreshTokenAudienceName) {
return echo.NewHTTPError(http.StatusUnauthorized, return echo.NewHTTPError(http.StatusUnauthorized,
fmt.Sprintf("Invalid refresh token, audience mismatch, got %q, expected %q. you may send request to the wrong environment", fmt.Sprintf("Invalid refresh token, audience mismatch, got %q, expected %q. you may send request to the wrong environment",
refreshTokenClaims.Audience, refreshTokenClaims.Audience,
fmt.Sprintf(auth.RefreshTokenAudienceFmt, mode), auth.RefreshTokenAudienceName,
)) ))
} }
// If we have a valid refresh token, we will generate new access token and refresh token // If we have a valid refresh token, we will generate new access token and refresh token
if refreshToken != nil && refreshToken.Valid { if refreshToken != nil && refreshToken.Valid {
if err := GenerateTokensAndSetCookies(c, user, mode, secret); err != nil { if err := GenerateTokensAndSetCookies(c, user, secret); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to refresh expired token. User Id %d", userID)).SetInternal(err) return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to refresh expired token. User Id %d", userID)).SetInternal(err)
} }
} }

Loading…
Cancel
Save