diff --git a/README.md b/README.md index e2ae9fe..ebd8620 100644 --- a/README.md +++ b/README.md @@ -932,7 +932,7 @@ Demonstrates how to use the [Json Web Token Auth Middleware](https://github.com/ curl demo: ``` sh -curl -d '{"username": "admin", "password": "admin"}' -H "Content-Type:application/json" http://localhost:8080/login +curl -d '{"username": "admin", "password": "admin"}' -H "Content-Type:application/json" http://localhost:8080/api/login curl -H "Authorization:Bearer TOKEN_RETURNED_FROM_ABOVE" http://localhost:8080/api/auth_test curl -H "Authorization:Bearer TOKEN_RETURNED_FROM_ABOVE" http://localhost:8080/api/refresh_token ``` @@ -942,11 +942,12 @@ code: package main import ( - "github.com/StephanDollberg/go-json-rest-middleware-jwt" - "github.com/ant0ine/go-json-rest/rest" "log" "net/http" "time" + + "github.com/StephanDollberg/go-json-rest-middleware-jwt" + "github.com/ant0ine/go-json-rest/rest" ) func handle_auth(w rest.ResponseWriter, r *rest.Request) { @@ -954,35 +955,31 @@ func handle_auth(w rest.ResponseWriter, r *rest.Request) { } func main() { - jwt_middleware := jwt.JWTMiddleware{ + jwt_middleware := &jwt.JWTMiddleware{ Key: []byte("secret key"), Realm: "jwt auth", Timeout: time.Hour, MaxRefresh: time.Hour * 24, Authenticator: func(userId string, password string) bool { - if userId == "admin" && password == "admin" { - return true - } - return false + return userId == "admin" && password == "admin" }} - login_api := rest.NewApi() - login_api.Use(rest.DefaultDevStack...) - login_router, _ := rest.MakeRouter( + api := rest.NewApi() + api.Use(rest.DefaultDevStack...) + // we use the IfMiddleware to remove certain paths from needing authentication + api.Use(&rest.IfMiddleware{ + Condition: func(request *rest.Request) bool { + return request.URL.Path != "/login" + }, + IfTrue: jwt_middleware, + }) + api_router, _ := rest.MakeRouter( &rest.Route{"POST", "/login", jwt_middleware.LoginHandler}, - ) - login_api.SetApp(login_router) - - main_api := rest.NewApi() - main_api.Use(&jwt_middleware) - main_api.Use(rest.DefaultDevStack...) - main_api_router, _ := rest.MakeRouter( &rest.Route{"GET", "/auth_test", handle_auth}, &rest.Route{"GET", "/refresh_token", jwt_middleware.RefreshHandler}) - main_api.SetApp(main_api_router) + api.SetApp(api_router) - http.Handle("/", login_api.MakeHandler()) - http.Handle("/api/", http.StripPrefix("/api", main_api.MakeHandler())) + http.Handle("/api/", http.StripPrefix("/api", api.MakeHandler())) log.Fatal(http.ListenAndServe(":8080", nil)) }