2020-05-18 19:21:00 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2020-06-07 14:26:06 +02:00
|
|
|
"time"
|
2020-05-18 19:21:00 +02:00
|
|
|
|
2020-06-07 14:26:06 +02:00
|
|
|
"github.com/kataras/iris/v12"
|
|
|
|
"github.com/kataras/iris/v12/middleware/jwt"
|
2020-05-18 19:21:00 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
app := iris.New()
|
|
|
|
app.ConfigureContainer(register)
|
|
|
|
|
2020-11-05 09:47:56 +01:00
|
|
|
// http://localhost:8080/authenticate
|
|
|
|
// http://localhost:8080/restricted
|
2020-05-18 19:21:00 +02:00
|
|
|
app.Listen(":8080")
|
|
|
|
}
|
|
|
|
|
2020-11-05 09:47:56 +01:00
|
|
|
var (
|
|
|
|
secret = []byte("secret")
|
|
|
|
signer = jwt.NewSigner(jwt.HS256, secret, 15*time.Minute)
|
|
|
|
verify = jwt.NewVerifier(jwt.HS256, secret, jwt.Expected{Issuer: "myapp"}).Verify(func() interface{} {
|
|
|
|
return new(userClaims)
|
|
|
|
})
|
|
|
|
)
|
2020-05-18 19:21:00 +02:00
|
|
|
|
2020-11-05 09:47:56 +01:00
|
|
|
func register(api *iris.APIContainer) {
|
|
|
|
// To register the middleware in the whole api container:
|
|
|
|
// api.Use(verify)
|
|
|
|
// Otherwise, protect routes when userClaims is expected on the functions input
|
|
|
|
// by calling the middleware manually, see below.
|
|
|
|
api.RegisterDependency(func(ctx iris.Context) (claims *userClaims) {
|
|
|
|
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)
|
2020-06-07 14:26:06 +02:00
|
|
|
}
|
2020-05-18 19:21:00 +02:00
|
|
|
|
2020-11-05 09:47:56 +01:00
|
|
|
return nil
|
2020-05-18 19:21:00 +02:00
|
|
|
})
|
|
|
|
|
2020-11-05 09:47:56 +01:00
|
|
|
api.Get("/authenticate", writeToken)
|
2020-06-07 14:26:06 +02:00
|
|
|
api.Get("/restricted", restrictedPage)
|
|
|
|
}
|
|
|
|
|
|
|
|
type userClaims struct {
|
2020-11-05 09:47:56 +01:00
|
|
|
Username string `json:"username"`
|
2020-05-18 19:21:00 +02:00
|
|
|
}
|
|
|
|
|
2020-11-05 09:47:56 +01:00
|
|
|
func writeToken(ctx iris.Context) {
|
|
|
|
claims := userClaims{
|
|
|
|
Username: "kataras",
|
2020-06-07 14:26:06 +02:00
|
|
|
}
|
2020-11-05 09:47:56 +01:00
|
|
|
standardClaims := jwt.Claims{
|
|
|
|
Issuer: "myapp",
|
|
|
|
}
|
|
|
|
|
|
|
|
token, err := signer.Sign(claims, standardClaims)
|
|
|
|
if err != nil {
|
|
|
|
ctx.StopWithError(iris.StatusInternalServerError, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx.Write(token)
|
2020-05-18 19:21:00 +02:00
|
|
|
}
|
|
|
|
|
2020-11-05 09:47:56 +01:00
|
|
|
func restrictedPage(claims *userClaims) string {
|
2020-06-07 14:26:06 +02:00
|
|
|
// userClaims.Username: kataras
|
|
|
|
return "userClaims.Username: " + claims.Username
|
2020-05-18 19:21:00 +02:00
|
|
|
}
|