...
1 package main
2
3 import (
4 "time"
5
6 jwt_lib "github.com/dgrijalva/jwt-go"
7 "github.com/gin-gonic/contrib/jwt"
8 "github.com/gin-gonic/gin"
9 )
10
11 var (
12 mysupersecretpassword = "unicornsAreAwesome"
13 )
14
15 func main() {
16 r := gin.Default()
17
18 public := r.Group("/api")
19
20 public.GET("/", func(c *gin.Context) {
21
22 token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256"))
23
24 token.Claims = jwt_lib.MapClaims{
25 "Id": "Christopher",
26 "exp": time.Now().Add(time.Hour * 1).Unix(),
27 }
28
29 tokenString, err := token.SignedString([]byte(mysupersecretpassword))
30 if err != nil {
31 c.JSON(500, gin.H{"message": "Could not generate token"})
32 }
33 c.JSON(200, gin.H{"token": tokenString})
34 })
35
36 private := r.Group("/api/private")
37 private.Use(jwt.Auth(mysupersecretpassword))
38
39
43
44 private.GET("/", func(c *gin.Context) {
45 c.JSON(200, gin.H{"message": "Hello from private"})
46 })
47
48 r.Run("localhost:8080")
49 }
50
View as plain text