-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
88 lines (69 loc) · 1.71 KB
/
main.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
84
85
86
87
88
package main
import (
"errors"
"fmt"
"log"
"net/http"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
var mySigningKey = []byte("supersecretkey")
func getToken(w http.ResponseWriter, r *http.Request) {
validToken, err := GenerateJWT()
if err != nil {
fmt.Println("Failed to generate token")
}
fmt.Fprintf(w, validToken)
}
func authroizedPage(w http.ResponseWriter, r *http.Request) {
err := isAuthorized(w, r)
if err != nil {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, err.Error())
}
fmt.Fprintf(w, "Hello you are authorized!")
fmt.Println("Endpoint Hit: homePage")
}
// GenerateJWT token
func GenerateJWT() (string, error) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["authorized"] = true
claims["client"] = "Kiril"
claims["exp"] = time.Now().Add(time.Minute * 30).Unix()
tokenString, err := token.SignedString(mySigningKey)
if err != nil {
err = fmt.Errorf("Something Went Wrong: %s", err.Error())
return "", err
}
return tokenString, nil
}
func isAuthorized(w http.ResponseWriter, r *http.Request) error {
if r.Header["Token"] != nil {
token, err := jwt.Parse(r.Header["Token"][0], func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("There was an error")
}
return mySigningKey, nil
})
if err != nil {
return err
}
if token.Valid {
return nil
}
}
return errors.New("Not Authorized")
}
func handler() http.Handler {
r := http.NewServeMux()
r.HandleFunc("/isAuthorized", authroizedPage)
r.HandleFunc("/getToken", getToken)
return r
}
func main() {
err := http.ListenAndServe(":8081", handler())
if err != nil {
log.Fatal(err)
}
}