-
Notifications
You must be signed in to change notification settings - Fork 0
/
authentication_jwt.go
41 lines (34 loc) · 984 Bytes
/
authentication_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
package middlewares
import (
"fmt"
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/spf13/viper"
)
func AuthJWTMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authorizationHeader := r.Header.Get("Authorization")
if authorizationHeader == "" {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(w, "Unauthorized")
return
}
tokenString := strings.Split(authorizationHeader, " ")[1]
if tokenString == "" {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(w, "Unauthorized")
return
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Aqui você deve fornecer a chave de verificação para validar o token
return []byte(viper.GetString("JWT_SECRET_KEY")), nil
})
if err != nil || !token.Valid {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(w, "Unauthorized")
return
}
next.ServeHTTP(w, r)
})
}