Skip to content

Commit

Permalink
Upgrading from v1.x → v2.0
Browse files Browse the repository at this point in the history
ref: #635

Signed-off-by: Avelino <avelinorun@gmail.com>
  • Loading branch information
avelino committed Dec 9, 2021
1 parent 45a903c commit 41d841e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 11 deletions.
16 changes: 15 additions & 1 deletion controllers/auth/models.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package auth

import "github.com/form3tech-oss/jwt-go"
import (
"context"

jwt "github.com/form3tech-oss/jwt-go"
)

// User logged in user representation
type User struct {
Expand All @@ -15,3 +19,13 @@ type Claims struct {
UserInfo User
jwt.StandardClaims
}

// Validate does nothing for this example.
func (c *Claims) Validate(ctx context.Context) error {
/**
if c.ShouldReject {
return errors.New("should reject was set to true")
}
*/
return nil
}
53 changes: 43 additions & 10 deletions middlewares/middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@ import (
"log"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"time"

jwtmiddleware "github.com/auth0/go-jwt-middleware"
jwtmiddleware "github.com/auth0/go-jwt-middleware/v2"
"github.com/auth0/go-jwt-middleware/v2/jwks"
"github.com/auth0/go-jwt-middleware/v2/validator"
"github.com/form3tech-oss/jwt-go"
"github.com/prest/prest/config"
"github.com/prest/prest/controllers/auth"
Expand Down Expand Up @@ -104,12 +108,33 @@ func AccessControl() negroni.Handler {

// JwtMiddleware check if actual request have JWT
func JwtMiddleware(key string, algo string) negroni.Handler {
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte(key), nil
},
SigningMethod: jwt.GetSigningMethod(algo),
})
issuerURL, err := url.Parse("https://127.0.0.1/")
if err != nil {
log.Fatalf("Failed to parse the issuer url: %v", err)
}
provider := jwks.NewCachingProvider(issuerURL, 5*time.Minute)
customClaims := &auth.Claims{}
jwtValidator, err := validator.New(
provider.KeyFunc,
validator.SignatureAlgorithm(algo),
issuerURL.String(),
[]string{key},
validator.WithCustomClaims(customClaims),
validator.WithAllowedClockSkew(time.Minute),
)
if err != nil {
log.Fatalf("Failed to set up the jwt validator")
}

errorHandler := func(w http.ResponseWriter, r *http.Request, err error) {
fmt.Println("error:", err)
log.Printf("Encountered error while validating JWT: %v", err)
}

middleware := jwtmiddleware.New(
jwtValidator.ValidateToken,
jwtmiddleware.WithErrorHandler(errorHandler),
)

return negroni.HandlerFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
match, err := MatchURL(r.URL.String())
Expand All @@ -121,10 +146,18 @@ func JwtMiddleware(key string, algo string) negroni.Handler {
next(w, r)
return
}
err = jwtMiddleware.CheckJWT(w, r)
if err != nil {

encounteredError := true
var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
encounteredError = false
user := r.Context().Value(jwtmiddleware.ContextKey{})
fmt.Println("user:", user)
}
middleware.CheckJWT(handler).ServeHTTP(w, r)

if encounteredError {
log.Println("check jwt error", err.Error())
w.Write([]byte(fmt.Sprintf(`{"error": "%v"}`, err.Error())))
w.Write([]byte(`{"error": "Failed to validate JWT"}`))
return
}
next(w, r)
Expand Down

0 comments on commit 41d841e

Please sign in to comment.