forked from gin-gonic/contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.go
49 lines (39 loc) · 1.04 KB
/
example.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
package main
import (
"time"
jwt_lib "github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/contrib/jwt"
"github.com/gin-gonic/gin"
)
var (
mysupersecretpassword = "unicornsAreAwesome"
)
func main() {
r := gin.Default()
public := r.Group("/api")
public.GET("/", func(c *gin.Context) {
// Create the token
token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256"))
// Set some claims
token.Claims = jwt_lib.MapClaims{
"Id": "Christopher",
"exp": time.Now().Add(time.Hour * 1).Unix(),
}
// Sign and get the complete encoded token as a string
tokenString, err := token.SignedString([]byte(mysupersecretpassword))
if err != nil {
c.JSON(500, gin.H{"message": "Could not generate token"})
}
c.JSON(200, gin.H{"token": tokenString})
})
private := r.Group("/api/private")
private.Use(jwt.Auth(mysupersecretpassword))
/*
Set this header in your request to get here.
Authorization: Bearer `token`
*/
private.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{"message": "Hello from private"})
})
r.Run("localhost:8080")
}