forked from kataras/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
70 lines (56 loc) · 1.56 KB
/
main.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
package main
import (
"time"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/jwt"
)
func main() {
app := iris.New()
app.ConfigureContainer(register)
// http://localhost:8080/authenticate
// http://localhost:8080/restricted (Header: Authorization = Bearer $token)
app.Listen(":8080")
}
var secret = []byte("secret")
func register(api *iris.APIContainer) {
api.RegisterDependency(func(ctx iris.Context) (claims userClaims) {
/* Using the middleware:
if ctx.Proceed(verify) {
// ^ the "verify" middleware will stop the execution if it's failed to verify the request.
// Map the input parameter of "restricted" function with the claims.
return jwt.Get(ctx).(*userClaims)
}*/
token := jwt.FromHeader(ctx)
if token == "" {
ctx.StopWithError(iris.StatusUnauthorized, jwt.ErrMissing)
return
}
verifiedToken, err := jwt.Verify(jwt.HS256, secret, []byte(token))
if err != nil {
ctx.StopWithError(iris.StatusUnauthorized, err)
return
}
verifiedToken.Claims(&claims)
return
})
api.Get("/authenticate", writeToken)
api.Get("/restricted", restrictedPage)
}
type userClaims struct {
Username string `json:"username"`
}
func writeToken(ctx iris.Context) {
claims := userClaims{
Username: "kataras",
}
token, err := jwt.Sign(jwt.HS256, secret, claims, jwt.MaxAge(1*time.Minute))
if err != nil {
ctx.StopWithError(iris.StatusInternalServerError, err)
return
}
ctx.Write(token)
}
func restrictedPage(claims userClaims) string {
// userClaims.Username: kataras
return "userClaims.Username: " + claims.Username
}