Skip to content

Commit

Permalink
README autogen - update JWT example
Browse files Browse the repository at this point in the history
  • Loading branch information
ant0ine committed Mar 30, 2015
1 parent fd981c6 commit fc0d6ba
Showing 1 changed file with 18 additions and 21 deletions.
39 changes: 18 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
Expand All @@ -942,47 +942,44 @@ 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) {
w.WriteJson(map[string]string{"authed": r.Env["REMOTE_USER"].(string)})
}

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))
}
Expand Down

0 comments on commit fc0d6ba

Please sign in to comment.