-
Notifications
You must be signed in to change notification settings - Fork 24
/
jwt.go
142 lines (120 loc) · 3.85 KB
/
jwt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package auth
import (
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/rs/zerolog/log"
"github.com/zibbp/ganymede/internal/user"
"github.com/zibbp/ganymede/internal/utils"
"net/http"
"os"
"time"
)
const (
accessTokenCookieName = "access-token"
refreshTokenCookieName = "refresh-token"
)
type Claims struct {
UserID uuid.UUID `json:"user_id"`
Username string `json:"username"`
Role utils.Role `json:"role"`
jwt.RegisteredClaims
}
func GetJWTSecret() string {
jwtSecret := os.Getenv("JWT_SECRET")
// Exit if JWT_SECRET is not set
if jwtSecret == "" {
log.Fatal().Msg("JWT_SECRET is not set")
}
return jwtSecret
}
func GetJWTRefreshSecret() string {
jwtRefreshSecret := os.Getenv("JWT_REFRESH_SECRET")
// Exit if JWT_REFRESH_SECRET is not set
if jwtRefreshSecret == "" {
log.Fatal().Msg("JWT_REFRESH_SECRET is not set")
}
return jwtRefreshSecret
}
// GenerateTokensAndSetCookies generates jwt token and saves it to the http-only cookie.
func GenerateTokensAndSetCookies(user *user.User, c echo.Context) error {
accessToken, exp, err := generateAccessToken(user)
if err != nil {
return err
}
setTokenCookie(accessTokenCookieName, accessToken, exp, c)
// Refresh
refreshToken, exp, err := generateRefreshToken(user)
if err != nil {
return err
}
setTokenCookie(refreshTokenCookieName, refreshToken, exp, c)
return nil
}
func generateAccessToken(user *user.User) (string, time.Time, error) {
// Declare the expiration time of the token (1h).
expirationTime := time.Now().Add(1 * time.Hour)
return generateToken(user, expirationTime, []byte(GetJWTSecret()))
}
func generateRefreshToken(user *user.User) (string, time.Time, error) {
// Declare the expiration time of the token - 24 hours.
expirationTime := time.Now().Add(30 * 24 * time.Hour)
return generateToken(user, expirationTime, []byte(GetJWTRefreshSecret()))
}
func generateToken(user *user.User, expirationTime time.Time, secret []byte) (string, time.Time, error) {
// Create the JWT claims, which includes the username and expiry time.
claims := &Claims{
UserID: user.ID,
Username: user.Username,
Role: user.Role,
RegisteredClaims: jwt.RegisteredClaims{
// In JWT, the expiry time is expressed as unix milliseconds.
ExpiresAt: jwt.NewNumericDate(expirationTime),
},
}
// Declare the token with the HS256 algorithm used for signing, and the claims.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Create the JWT string.
tokenString, err := token.SignedString(secret)
if err != nil {
return "", time.Now(), err
}
return tokenString, expirationTime, nil
}
// Here we are creating a new cookie, which will store the valid JWT token.
func setTokenCookie(name, token string, expiration time.Time, c echo.Context) {
// Get optional cookie domain name
cookieDomain := os.Getenv("COOKIE_DOMAIN")
cookie := new(http.Cookie)
cookie.Name = name
cookie.Value = token
cookie.Expires = expiration
cookie.Path = "/"
// Http-only helps mitigate the risk of client side script accessing the protected cookie.
cookie.HttpOnly = false
cookie.SameSite = http.SameSiteLaxMode
if cookieDomain != "" {
cookie.Domain = cookieDomain
}
c.SetCookie(cookie)
}
func checkAccessToken(accessToken string) (*Claims, error) {
// Parse the token.
token, err := jwt.ParseWithClaims(accessToken, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(GetJWTSecret()), nil
})
if err != nil {
return nil, err
}
// Validate the token and return the custom claims.
claims, ok := token.Claims.(*Claims)
if !ok || !token.Valid {
return nil, err
}
return claims, nil
}
// JWTErrorChecker will be executed when user try to access a protected path.
func JWTErrorChecker(err error, c echo.Context) error {
// Redirects to the signIn form.
return echo.NewHTTPError(http.StatusUnauthorized, "unauthorized")
}