-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
57 lines (45 loc) · 1.55 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
50
51
52
53
54
55
56
57
package auth
import (
"fmt"
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
)
var tag = "[Auth]"
// isValidJwtToken checks the structure of the jwt token is present
// this function is necessary as passing a non-jwt string to jwt package panics the whole
// thread which is awful but we have to live by it anyway
func isValidJwtToken(token string) bool {
return !(len(token) <= 0 || strings.Count(token, ".") != 2)
}
// getjwtToken extracts the jwt token from the request header
func getjwtToken(headers http.Header) string {
authStringSlices := strings.Split(headers.Get("Authorization"), "bearer ")
if len(authStringSlices) < 2 {
return ""
}
return authStringSlices[1]
}
// verifyTokenSignature verfies the token passed is a valid jwt token signed by the same secret
func verifyTokenSignature(token string) bool {
var jwtKey = []byte(jwtSecret)
claims := &Claims{}
if !isValidJwtToken(token) {
fmt.Println(fmt.Sprintf("%s invalid jwt token format, auth rejected", tag))
return false
}
tkn, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if err != nil || !tkn.Valid {
fmt.Println(fmt.Sprintf("%s invalid token, auth rejected", tag))
return false
}
fmt.Println(fmt.Sprintf("%s token verified for author %s", tag, claims.Author))
return true
}
// Authenticate verifies the caller comes trusted authority using jwt
func Authenticate(headers http.Header) bool {
fmt.Println(fmt.Sprintf("%s Started Authentication Flow ....", tag))
return verifyTokenSignature(getjwtToken(headers))
}