forked from hyacinthus/gin-jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
76 lines (65 loc) · 1.62 KB
/
server.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
package main
import (
"net/http"
"os"
"time"
"github.com/appleboy/gin-jwt"
"gopkg.in/gin-gonic/gin.v1"
)
func helloHandler(c *gin.Context) {
c.JSON(200, gin.H{
"text": "Hello World.",
})
}
func main() {
port := os.Getenv("PORT")
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
if port == "" {
port = "8000"
}
// the jwt middleware
authMiddleware := &jwt.GinJWTMiddleware{
Realm: "test zone",
Key: []byte("secret key"),
Timeout: time.Hour,
MaxRefresh: time.Hour,
Authenticator: func(userId string, password string, c *gin.Context) (string, bool) {
if (userId == "admin" && password == "admin") || (userId == "test" && password == "test") {
return userId, true
}
return userId, false
},
Authorizator: func(userId string, c *gin.Context) bool {
if userId == "admin" {
return true
}
return false
},
Unauthorized: func(c *gin.Context, code int, message string) {
c.JSON(code, gin.H{
"code": code,
"message": message,
})
},
// TokenLookup is a string in the form of "<source>:<name>" that is used
// to extract token from the request.
// Optional. Default value "header:Authorization".
// Possible values:
// - "header:<name>"
// - "query:<name>"
// - "cookie:<name>"
TokenLookup: "header:Authorization",
// TokenLookup: "query:token",
// TokenLookup: "cookie:token",
}
r.POST("/login", authMiddleware.LoginHandler)
auth := r.Group("/auth")
auth.Use(authMiddleware.MiddlewareFunc())
{
auth.GET("/hello", helloHandler)
auth.GET("/refresh_token", authMiddleware.RefreshHandler)
}
http.ListenAndServe(":"+port, r)
}