-
Notifications
You must be signed in to change notification settings - Fork 0
/
authtut.go
63 lines (48 loc) · 1.18 KB
/
authtut.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
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
var mySigningKey = []byte("captainjacksparrowsayshi")
func homePage(w http.ResponseWriter, r *http.Request) {
validToken, err := GenerateJWT()
if err != nil {
fmt.Println("Failed to generate token")
}
client := &http.Client{}
req, _ := http.NewRequest("GET", "http://localhost:9000/", nil)
req.Header.Set("Token", validToken)
res, err := client.Do(req)
if err != nil {
fmt.Fprintf(w, "Error: %s", err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
}
fmt.Fprintf(w, string(body))
}
func GenerateJWT() (string, error) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["authorized"] = true
claims["client"] = "Elliot Forbes"
claims["exp"] = time.Now().Add(time.Minute * 30).Unix()
tokenString, err := token.SignedString(mySigningKey)
if err != nil {
fmt.Errorf("Something Went Wrong: %s", err.Error())
return "", err
}
return tokenString, nil
}
func handleRequests() {
http.HandleFunc("/", homePage)
log.Fatal(http.ListenAndServe(":9001", nil))
}
func main() {
handleRequests()
}