-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerateToken.go
More file actions
75 lines (63 loc) · 1.73 KB
/
Copy pathgenerateToken.go
File metadata and controls
75 lines (63 loc) · 1.73 KB
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
package main
import (
"github.com/gbrlsnchs/jwt"
"io"
"log"
"math/rand"
"net/http"
"time"
)
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func randSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
type CustomPayload struct {
jwt.Payload
RandSeq string `json:"foo,omitempty"`
}
var hs = jwt.NewHS256([]byte("lgg3d5sf8v3"))
func GenerateToken() []byte {
now := time.Now()
pl := CustomPayload{
Payload: jwt.Payload{
Issuer: "theinsect",
Subject: "transmission",
Audience: jwt.Audience{"https://golang.org", "https://jwt.io"},
ExpirationTime: jwt.NumericDate(now.Add(24 * 30 * 12 * time.Hour)),
NotBefore: jwt.NumericDate(now.Add(30 * time.Minute)),
IssuedAt: jwt.NumericDate(now),
JWTID: "f5rek432",
},
RandSeq: randSeq(20),
}
token, err := jwt.Sign(pl, hs)
if err != nil {
log.Fatal(err)
}
return token
}
func main() {
rand.Seed(time.Now().UnixNano())
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
token := GenerateToken()
io.WriteString(w, string(token))
})
http.HandleFunc("/verify", func(w http.ResponseWriter, req *http.Request) {
tokenCorrect := verifyToken([]byte(req.URL.Query()["token"][0]))
if tokenCorrect {
io.WriteString(w, "Token OK")
} else {
io.WriteString(w, "Token Faulty")
}
})
// One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/")
err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
//err := http.ListenAndServe(":8443", nil)
log.Fatal(err)
//localhost:8080/?key=hello%20golangcode.com
}