mirror of
https://github.com/kataras/iris.git
synced 2025-01-24 03:01:03 +01:00
3945fa68d1
We have to do the same on iris-contrib/examples, iris-contrib/middleware and e.t.c. Former-commit-id: 0860688158f374bc137bc934b81b26dcd0e10964
57 lines
1.7 KiB
Go
57 lines
1.7 KiB
Go
// iris provides some basic middleware, most for your learning curve.
|
|
// You can use any net/http compatible middleware with iris.FromStd wrapper.
|
|
//
|
|
// JWT net/http video tutorial for golang newcomers: https://www.youtube.com/watch?v=dgJFeqeXVKw
|
|
//
|
|
// This middleware is the only one cloned from external source: https://github.com/auth0/go-jwt-middleware
|
|
// (because it used "context" to define the user but we don't need that so a simple iris.FromStd wouldn't work as expected.)
|
|
package main
|
|
|
|
import (
|
|
"github.com/kataras/iris/v12"
|
|
|
|
"github.com/iris-contrib/middleware/jwt"
|
|
)
|
|
|
|
func getTokenHandler(ctx iris.Context) {
|
|
token := jwt.NewTokenWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
|
"foo": "bar",
|
|
})
|
|
|
|
// Sign and get the complete encoded token as a string using the secret
|
|
tokenString, _ := token.SignedString([]byte("My Secret"))
|
|
|
|
ctx.HTML(`Token: ` + tokenString + `<br/><br/>
|
|
<a href="/secured?token=` + tokenString + `">/secured?token=` + tokenString + `</a>`)
|
|
}
|
|
|
|
func myAuthenticatedHandler(ctx iris.Context) {
|
|
user := ctx.Values().Get("jwt").(*jwt.Token)
|
|
|
|
ctx.Writef("This is an authenticated request\n")
|
|
ctx.Writef("Claim content:\n")
|
|
|
|
foobar := user.Claims.(jwt.MapClaims)
|
|
for key, value := range foobar {
|
|
ctx.Writef("%s = %s", key, value)
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
app := iris.New()
|
|
|
|
j := jwt.New(jwt.Config{
|
|
// Extract by "token" url parameter.
|
|
Extractor: jwt.FromParameter("token"),
|
|
|
|
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
|
|
return []byte("My Secret"), nil
|
|
},
|
|
SigningMethod: jwt.SigningMethodHS256,
|
|
})
|
|
|
|
app.Get("/", getTokenHandler)
|
|
app.Get("/secured", j.Serve, myAuthenticatedHandler)
|
|
app.Run(iris.Addr(":8080"))
|
|
}
|