diff --git a/_examples/dependency-injection/jwt/main.go b/_examples/dependency-injection/jwt/main.go index 54c105cb..ff328eb9 100644 --- a/_examples/dependency-injection/jwt/main.go +++ b/_examples/dependency-injection/jwt/main.go @@ -12,30 +12,34 @@ func main() { app.ConfigureContainer(register) // http://localhost:8080/authenticate - // http://localhost:8080/restricted + // http://localhost:8080/restricted (Header: Authorization = Bearer $token) app.Listen(":8080") } -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) - }) -) +var secret = []byte("secret") 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. + 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 } - return nil + 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) @@ -50,11 +54,8 @@ func writeToken(ctx iris.Context) { claims := userClaims{ Username: "kataras", } - standardClaims := jwt.Claims{ - Issuer: "myapp", - } - token, err := signer.Sign(claims, standardClaims) + token, err := jwt.Sign(jwt.HS256, secret, claims, jwt.MaxAge(1*time.Minute)) if err != nil { ctx.StopWithError(iris.StatusInternalServerError, err) return @@ -63,7 +64,7 @@ func writeToken(ctx iris.Context) { ctx.Write(token) } -func restrictedPage(claims *userClaims) string { +func restrictedPage(claims userClaims) string { // userClaims.Username: kataras return "userClaims.Username: " + claims.Username } diff --git a/middleware/jwt/alises.go b/middleware/jwt/aliases.go similarity index 99% rename from middleware/jwt/alises.go rename to middleware/jwt/aliases.go index 81b4f94a..475d4692 100644 --- a/middleware/jwt/alises.go +++ b/middleware/jwt/aliases.go @@ -119,7 +119,7 @@ var ( // Shortcuts for Signing and Verifying. var ( - VerifyToken = jwt.Verify + Verify = jwt.Verify VerifyEncryptedToken = jwt.VerifyEncrypted Sign = jwt.Sign SignEncrypted = jwt.SignEncrypted