-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
49 lines (41 loc) · 1.23 KB
/
auth.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
package middleware
import (
"fmt"
"net/http"
"os"
"strings"
"github.com/dgrijalva/jwt-go"
)
func TokenVerifyMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
secretKey := os.Getenv("SECRET_KEY")
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Authorization header is missing", http.StatusForbidden)
return
}
// First part is Bearer, second has to token
// TODO: Bearer is not required, any string is okay. Check this later.
parts := strings.Split(authHeader, " ")
if len(parts) != 2 {
http.Error(w, "Wrong token", http.StatusForbidden)
return
}
tokenPart := parts[1]
token, err := jwt.Parse(tokenPart, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) //alg: HS256 //jwt.SigningMethodHS256
}
return []byte(secretKey), nil
})
if err != nil {
http.Error(w, "Invalid token", http.StatusForbidden)
return
}
if _, ok := token.Claims.(jwt.Claims); !ok && !token.Valid {
http.Error(w, "Token is not valid", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
}
}