-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
61 lines (47 loc) · 1.4 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
package jwt
import (
"io/ioutil"
"net/http"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/efrenfuentes/go-authentication/core/settings"
"github.com/efrenfuentes/go-authentication/models"
)
type APIToken struct {
Token string `json:"token"`
}
func CreateToken(user models.User) string {
token := jwt.New(jwt.GetSigningMethod("RS256"))
// Create a Token that will be signed with RSA 256.
/*
{
"typ":"JWT",
"alg":"RS256"
}
*/
token.Claims["email"] = user.Email
token.Claims["name"] = user.Name
token.Claims["exp"] = time.Now().Unix() + 36000
jwtSettings := settings.Get()["jwt"].(map[string]interface{})
keyfile := jwtSettings["privateKey"].(string)
privateKey, _ := ioutil.ReadFile(keyfile)
// The claims object allows you to store information in the actual token.
tokenString, _ := token.SignedString(privateKey)
return tokenString
}
func JWTTokenAuthentication(inner http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
jwtSettings := settings.Get()["jwt"].(map[string]interface{})
keyfile := jwtSettings["publicKey"].(string)
publicKey, _ := ioutil.ReadFile(keyfile)
token, err := jwt.ParseFromRequest(r,
func(token *jwt.Token) (interface{}, error) {
return publicKey, nil
})
if err == nil && token.Valid {
inner.ServeHTTP(w, r)
} else {
w.WriteHeader(http.StatusUnauthorized)
}
})
}