2019-08-16 15:57:03 +02:00
|
|
|
// 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 (
|
2019-10-25 00:27:02 +02:00
|
|
|
"github.com/kataras/iris/v12"
|
2019-08-16 15:57:03 +02:00
|
|
|
|
2019-08-16 16:02:20 +02:00
|
|
|
"github.com/iris-contrib/middleware/jwt"
|
2019-08-16 15:57:03 +02:00
|
|
|
)
|
|
|
|
|
2019-08-16 16:02:20 +02:00
|
|
|
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) {
|
2019-08-16 15:57:03 +02:00
|
|
|
user := ctx.Values().Get("jwt").(*jwt.Token)
|
|
|
|
|
|
|
|
ctx.Writef("This is an authenticated request\n")
|
|
|
|
ctx.Writef("Claim content:\n")
|
|
|
|
|
2019-08-16 16:02:20 +02:00
|
|
|
foobar := user.Claims.(jwt.MapClaims)
|
|
|
|
for key, value := range foobar {
|
|
|
|
ctx.Writef("%s = %s", key, value)
|
|
|
|
}
|
2019-08-16 15:57:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
app := iris.New()
|
|
|
|
|
2019-08-16 16:02:20 +02:00
|
|
|
j := jwt.New(jwt.Config{
|
|
|
|
// Extract by "token" url parameter.
|
|
|
|
Extractor: jwt.FromParameter("token"),
|
|
|
|
|
2019-08-16 15:57:03 +02:00
|
|
|
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
|
|
|
|
return []byte("My Secret"), nil
|
|
|
|
},
|
|
|
|
SigningMethod: jwt.SigningMethodHS256,
|
|
|
|
})
|
|
|
|
|
2019-08-16 16:02:20 +02:00
|
|
|
app.Get("/", getTokenHandler)
|
|
|
|
app.Get("/secured", j.Serve, myAuthenticatedHandler)
|
|
|
|
app.Run(iris.Addr(":8080"))
|
|
|
|
}
|