-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.go
83 lines (66 loc) · 1.56 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
package main
import (
"crypto/rand"
"fmt"
"net/http"
"os"
"time"
"github.com/golang-jwt/jwt"
)
var randomSalt = generateRandomToken(4)
// createToken creates a new token
func (s *Session) createToken() *http.Cookie {
token := jwt.NewWithClaims(jwt.SigningMethodHS256,
jwt.MapClaims{
"username": s.Name,
"exp": time.Now().Add(5 * time.Minute).Unix(),
})
tokenString, err := token.SignedString([]byte(os.Getenv("SECRET_KEY") + randomSalt))
if err != nil {
return nil
}
c := &http.Cookie{
Name: AuthTypeJWTToken,
Value: tokenString,
Secure: true, // https
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Expires: time.Now().Add(5 * time.Minute), // 5 minutes expire session removed
}
s.ID = c.Value
s.Name = c.Name
return c
}
// deleteToken method remove jwt token and reset user credentials
func (s *Session) deleteToken(w http.ResponseWriter) {
// immediately clear the token cookie
c := &http.Cookie{
Name: AuthTypeJWTToken,
Value: "",
MaxAge: -1,
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Expires: time.Now(),
}
http.SetCookie(w, c)
s.ID = ""
s.Name = ""
}
func verifyToken(rawToken string) error {
token, err := jwt.Parse(rawToken, func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("SECRET_KEY") + randomSalt), nil
})
if err != nil {
return err
}
if !token.Valid {
return fmt.Errorf("Invalid token")
}
return nil
}
func generateRandomToken(length uint) string {
b := make([]byte, length)
rand.Read(b)
return fmt.Sprintf("%x", b)
}