Ejemplo n.º 1
0
// Enable JWT authorization check on the HTTP handler function.
func jwtWrap(originalHandler http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		addCommonJwtRespHeaders(w, r)
		t, _ := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
			return publicKey, nil
		})
		if t == nil || !t.Valid {
			http.Error(w, "", http.StatusUnauthorized)
			return
		} else if t.Claims[JWT_USER_ATTR] == JWT_USER_ADMIN {
			originalHandler(w, r)
			return
		}
		var url = strings.TrimPrefix(r.URL.Path, "/")
		var col = r.FormValue("col")
		if !sliceContainsStr(t.Claims[JWT_ENDPOINTS_ATTR], url) {
			http.Error(w, "", http.StatusUnauthorized)
			return
		} else if col != "" && !sliceContainsStr(t.Claims[JWT_COLLECTIONS_ATTR], col) {
			http.Error(w, "", http.StatusUnauthorized)
			return
		}
		originalHandler(w, r)
	}
}
Ejemplo n.º 2
0
func (this *JWTFilter) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	if this.excludedURLsMatcher.Match(request.URL.Path) {
		log.Debug("JWTFilter.ServeHTTP - Skipping JWT authentication, URL excluded: " + request.URL.Path)
		this.innerHandler.ServeHTTP(writer, request)
		return
	}

	authorisationHeader := request.Header.Get("Authorization")
	log.Debug("JWTFilter.ServeHTTP - Validating JWT token:" + authorisationHeader)

	if authorisationHeader == "" || len(authorisationHeader) <= 6 || strings.ToUpper(authorisationHeader[0:6]) != "BEARER" {
		log.Warn("JWTFilter.ServeHTTP - No valid authorization header found, block request")
		writer.WriteHeader(401)
		return
	}

	token, err := jwt.ParseFromRequest(request, func(token *jwt.Token) (interface{}, error) {
		return *this.publicKey, nil
	})

	if err != nil {
		log.Error(err.Error())
		writer.WriteHeader(500)
		return
	}

	if token.Valid {
		log.Debug("JWTFilter.ServeHTTP - Token is valid, setting context and continuing request")
		this.claimProvider.SetClaims(request, token)
		this.innerHandler.ServeHTTP(writer, request)
	} else {
		log.Warn("JWTFilter.ServeHTTP - invalid token")
		writer.WriteHeader(401)
	}
}
Ejemplo n.º 3
0
func RequireTokenAuthentication(rw http.ResponseWriter, req *http.Request) (bool, *model.User) {

	var loggedUser *model.User = nil
	var result bool = false
	authBackend := InitJWTAuthenticationBackend()

	token, err := jwt.ParseFromRequest(req, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		} else {
			return authBackend.PublicKey, nil
		}
	})

	if err == nil && token.Valid && !authBackend.IsInBlacklist(req.Header.Get("Authorization")) {

		// 验证通过了,设置当前登陆用户
		result = true

		account := util.ParseString(token.Claims["sub"])
		loggedUser = model.GetByAccount(account)
	} else {
		rw.WriteHeader(http.StatusUnauthorized)
	}

	return result, loggedUser
}
Ejemplo n.º 4
0
func (a *authMiddleware) RequireLogin() gin.HandlerFunc {
	return func(c *gin.Context) {
		token, err := jwt_lib.ParseFromRequest(c.Request, func(token *jwt_lib.Token) (interface{}, error) {
			b := ([]byte(config.GetSecret()))
			return b, nil
		})

		if err != nil || token == nil || (token != nil && !token.Valid) {
			c.Error(apiErrors.ThrowError(apiErrors.AccessDenied))
			c.Abort()
			return
		}

		var currentUser *models.User
		var findUserErr error

		if userId, ok := token.Claims["userId"].(string); ok {
			if currentUser, findUserErr = userResource.GetById(userId); findUserErr != nil {
				c.Error(findUserErr)
				c.Abort()
				return
			}
		} else {
			panic("Must load userId in token")
		}
		c.Set("currentUser", currentUser)
		c.Next()
	}
}
Ejemplo n.º 5
0
func ValidateTokenAuthentication(w http.ResponseWriter, req *http.Request,
	next http.HandlerFunc) {
	w.Header().Add("Access-Control-Allow-Origin", "*")

	authBackend, err := InitJwtAuthBackend()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
	}

	token, err := jwt.ParseFromRequest(
		req,
		func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
				return nil, fmt.Errorf(
					"Unexpected signing method: %v",
					token.Header["alg"],
				)
			} else {
				return authBackend.PublicKey, nil
			}
		},
	)

	if err == nil && token.Valid && !authBackend.IsTerminated(
		req.Header.Get("Authorization")) {
		w.WriteHeader(http.StatusOK)
	} else {
		w.WriteHeader(http.StatusUnauthorized)
	}
}
Ejemplo n.º 6
0
func (s *service) getAndValidateJwtTokenFromRequest(r *http.Request) *jwt.Token {
	token, err := jwt.ParseFromRequest(r, s.jwtKeyFuncGetBytes)

	switch errType := err.(type) {
	case *jwt.ValidationError:
		switch errType.Errors {
		case jwt.ValidationErrorExpired:
			panic(s.ErrorsService.CreateClientError(http.StatusUnauthorized, "Token expired"))

		default:
			s.Logger.Error("Unable to parse token: %s", err.Error())
			panic(s.ErrorsService.CreateClientError(http.StatusUnauthorized, "[1442894612] Invalid token"))
		}
	case nil:
		//This validation must match up with the one above in call to `jwt.New(jwt.GetSigningMethod(`
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			panic(s.ErrorsService.CreateClientError(http.StatusUnauthorized, "[1442894613] Invalid token"))
		}

		//TODO: We are checking this IsInLoggedOutList even when called from the `BaseLogoutHandler`
		if !token.Valid || s.JwtHelperService.IsInLoggedOutList(token.Raw) {
			panic(s.ErrorsService.CreateClientError(http.StatusUnauthorized, "[1442894611] Invalid token"))
		}

		return token
	default: // something else went wrong
		if err == jwt.ErrNoTokenInRequest {
			panic(s.ErrorsService.CreateClientError(http.StatusUnauthorized, "[1442947885] Token missing"))
		}

		s.Logger.Error("Error casting token error type: %s", errType)
		panic(s.ErrorsService.CreateClientError(http.StatusInternalServerError, "[1442936515] Invalid token"))
	}
}
Ejemplo n.º 7
0
func Auth(secret string) gin.HandlerFunc {
	return func(c *gin.Context) {

		auth := c.Request.Header.Get("Authorization")
		l := len(Bearer)

		if len(auth) > l+1 && auth[:l] == Bearer {
			token, err := jwt.ParseFromRequest(c.Request, func(token *jwt.Token) (interface{}, error) {
				b := ([]byte(secret))
				return b, nil
			})

			if err == nil && token.Valid {
				c.Set("claims", token.Claims)

				if exp, ok := token.Claims["exp"].(float64); ok {
					log.WithFields(log.Fields{
						"UserName": token.Claims["name"],
						"Exp":      (int64(exp) - time.Now().Unix()) / 60,
					}).Debug("User authorized")
				} else {
					log.Errorf("Incorrect claims, %v", token.Claims)
				}
			} else {
				c.AbortWithError(http.StatusUnauthorized, UnAuthError)
			}

		} else {
			//			c.JSON(http.StatusUnauthorized, gin.H{"code": http.StatusUnauthorized, "msg": "Sorry, you are not authorized"})
			c.AbortWithError(http.StatusUnauthorized, UnAuthError)
		}
	}
}
Ejemplo n.º 8
0
Archivo: jwt.go Proyecto: ngaut/beego
// AuthRequest retunn FilterFunc
func AuthRequest(o *Options) beego.FilterFunc {
	RSAKeys.PrivateKey, _ = ioutil.ReadFile(o.PrivateKeyPath)
	RSAKeys.PublicKey, _ = ioutil.ReadFile(o.PublicKeyPath)

	return func(ctx *context.Context) {
		// :TODO the url patterns should be considered here.
		// Shouldn't only use the string equal
		for _, method := range o.WhiteList {
			if method == ctx.Request.URL.Path {
				return
			}
		}

		parsedToken, err := goJwt.ParseFromRequest(ctx.Request, func(t *goJwt.Token) (interface{}, error) {
			return RSAKeys.PublicKey, nil
		})

		if err == nil && parsedToken.Valid {
			ctx.Output.SetStatus(http.StatusOK)
		} else {
			ctx.Output.SetStatus(http.StatusUnauthorized)
		}

	}
}
Ejemplo n.º 9
0
func RequireTokenAuthentication(w http.ResponseWriter, req *http.Request,
	next http.HandlerFunc) {

	// Preflight handling
	if req.Method == "OPTIONS" {
		return
	}

	authBackend, err := InitJwtAuthBackend()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
	}

	token, err := jwt.ParseFromRequest(
		req,
		func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
				return nil, fmt.Errorf(
					"Unexpected signing method: %v",
					token.Header["alg"],
				)
			} else {
				return authBackend.PublicKey, nil
			}
		},
	)

	if err == nil &&
		token.Valid &&
		!authBackend.IsTerminated(req.Header.Get("Authorization")) {
		next(w, req)
	} else {
		w.WriteHeader(http.StatusUnauthorized)
	}
}
Ejemplo n.º 10
0
func Logout(req *http.Request, ab backends.Authentication, secret []byte, exp int) error {
	authBackend := InitJWTAuthenticationBackend(ab, secret, exp)
	tokenRequest, err := jwt.ParseFromRequest(req, func(token *jwt.Token) (interface{}, error) {
		return authBackend.SecretKey, nil
	})
	if err != nil {
		return err
	}
	tokenString := req.Header.Get("Authorization")
	return authBackend.Logout(tokenString, tokenRequest)
}
Ejemplo n.º 11
0
func AuthMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
		return publicKey, nil
	})
	if err == nil && token.Valid {
		next(w, r)
	} else {
		w.WriteHeader(http.StatusUnauthorized)
		fmt.Fprint(w, "GO HOME")
	}
}
func Logout(req *http.Request) error {
	authBackend := authentication.InitJWTAuthenticationBackend()
	tokenRequest, err := jwt.ParseFromRequest(req, func(token *jwt.Token) (interface{}, error) {
		return authBackend.PublicKey, nil
	})
	if err != nil {
		return err
	}
	tokenString := req.Header.Get("Authorization")
	return authBackend.Logout(tokenString, tokenRequest)
}
Ejemplo n.º 13
0
func authMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	// validate the token
	token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
		return verifyKey, nil
	})
	if err == nil && token.Valid {
		next(w, r)
	} else {
		w.WriteHeader(http.StatusUnauthorized)
		fmt.Fprint(w, "Authentication failed")
	}
}
Ejemplo n.º 14
0
func Auth(secret string) gin.HandlerFunc {
	return func(c *gin.Context) {
		_, err := jwt_lib.ParseFromRequest(c.Request, func(token *jwt_lib.Token) (interface{}, error) {
			b := ([]byte(secret))
			return b, nil
		})

		if err != nil {
			c.AbortWithError(401, err)
		}
	}
}
Ejemplo n.º 15
0
// Middleware for validating JWT tokens
func Authorize(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	// validate the token
	token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {

		// Verify the token with public key, which is the counter part of private key
		return verifyKey, nil
	})

	if err != nil {
		switch err.(type) {

		case *jwt.ValidationError: // JWT validation error
			vErr := err.(*jwt.ValidationError)

			switch vErr.Errors {
			case jwt.ValidationErrorExpired: //JWT expired
				DisplayAppError(
					w,
					err,
					"Access Token is expired, get a new Token",
					401,
				)
				return

			default:
				DisplayAppError(w,
					err,
					"Error while parsing the Access Token!",
					500,
				)
				return
			}

		default:
			DisplayAppError(w,
				err,
				"Error while parsing Access Token!",
				500)
			return
		}

	}
	if token.Valid {
		next(w, r)
	} else {
		DisplayAppError(
			w,
			err,
			"Invalid Access Token",
			401,
		)
	}
}
Ejemplo n.º 16
0
// Verify user's JWT.
func checkJWT(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	addCommonJwtRespHeaders(w, r)
	t, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
		return publicKey, nil
	})
	if t == nil || !t.Valid {
		http.Error(w, fmt.Sprintf("{\"error\": \"%s %s\"}", "JWT not valid,", err), http.StatusUnauthorized)
	} else {
		w.WriteHeader(http.StatusOK)
	}
}
Ejemplo n.º 17
0
// isAuthenticated validates if any incoming request to be a valid JWT
// authenticated request.
func isAuthenticated(req *http.Request) bool {
	jwt := InitJWT()
	tokenRequest, err := jwtgo.ParseFromRequest(req, func(token *jwtgo.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwtgo.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return jwt.PublicKey, nil
	})
	if err != nil {
		return false
	}
	return tokenRequest.Valid
}
Ejemplo n.º 18
0
// isJWTReqAuthenticated validates if any incoming request to be a
// valid JWT authenticated request.
func isJWTReqAuthenticated(req *http.Request) bool {
	jwt := initJWT()
	token, e := jwtgo.ParseFromRequest(req, func(token *jwtgo.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwtgo.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(jwt.SecretAccessKey), nil
	})
	if e != nil {
		return false
	}
	return token.Valid
}
Ejemplo n.º 19
0
func AuthenticateToken(c *Context, fn HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		token, err := jwt.ParseFromRequest(r, func(parsedToken *jwt.Token) (interface{}, error) {
			if _, ok := parsedToken.Method.(*jwt.SigningMethodRSA); !ok {
				return nil, fmt.Errorf("Unrecognized signing method: %v", parsedToken.Header["alg"])

			} else {
				return settings.GetPublicKey(), nil
			}
		})

		if err == jwt.ErrNoTokenInRequest {
			fn(c, w, r)
			return
		} else if err != nil {
			http.Error(w, err.Error(), http.StatusUnauthorized)
			return
		}

		if !token.Valid {
			http.Error(w, "Invalid JWT", http.StatusUnauthorized)
			return
		}

		var ok bool

		c.UserID, ok = token.Claims["sub"].(string)
		if !ok {
			log.Fatal("The underlying type of sub is not string")
		}

		isStored, err := c.TokenStore.IsTokenStored(c.UserID)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		if isStored {
			http.Error(w, "Token is no longer valid", http.StatusUnauthorized)
			return
		}

		_, ok = token.Claims["exp"].(float64)
		if !ok {
			log.Fatal("The underlying type of exp is not float64")
		}

		fn(c, w, r)
	}
}
Ejemplo n.º 20
0
// Auth middleware returns handler that serves if the request comes in with valid JSON Web Token
//It will collect the authkey from the request and add that with GIN Context keys for future request
func Auth(secret string) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		ctx.Keys = make(map[string]interface{})
		ctx.Keys["authKey"] = authKey
		_, err := jwt.ParseFromRequest(ctx.Request, func(token *jwt.Token) (interface{}, error) {
			key := ([]byte(secret))
			return key, nil
		})
		if err != nil {
			log.Println("Error: ", err)
			ctx.AbortWithError(401, err)
		}
	}
}
Ejemplo n.º 21
0
func JWTAuth(secret string) gin.HandlerFunc {
	return func(c *gin.Context) {
		token, err := jwt_lib.ParseFromRequest(c.Request, func(token *jwt_lib.Token) (interface{}, error) {
			b := ([]byte(secret))
			return b, nil
		})

		if err != nil {
			c.AbortWithError(401, err)
			return
		}
		c.Set("userId", token.Claims["ID"])
	}
}
Ejemplo n.º 22
0
/**

	TODO:
	- Check user is login
	- If not return not login error
	- If logined set "user" in context

**/
func (a *authMiddleware) RequireLogin() gin.HandlerFunc {
	return func(c *gin.Context) {
		user, err := jwt_lib.ParseFromRequest(c.Request, func(token *jwt_lib.Token) (interface{}, error) {
			b := ([]byte(config.GetSecret()))
			return b, nil
		})

		if err != nil {
			c.Error(apiErrors.ThrowError(apiErrors.UserNotLogined))
			return
		}
		c.Set("user", user)
	}
}
Ejemplo n.º 23
0
func GetTokenFromRequest(r *http.Request, signkey []byte) (token *jwt.Token, err error) {

	if token, err = jwt.ParseFromRequest(r, func(t *jwt.Token) (interface{}, error) {
		if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Invalid signature method: %s!", t.Method)
		}
		return signkey, nil
	}); err != nil {
		return
	}

	err = validateToken(token)

	return
}
Ejemplo n.º 24
0
// Middleware checks an HTTP request to see if it
// contains a vlaid JSON web token
func Middleware(a *app.App, w http.ResponseWriter, r *http.Request) error {
	token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
		return publicKey, nil
	})
	if err != nil {
		// @TODO: Handle unauthorized properly
		w.WriteHeader(http.StatusUnauthorized)
		log.Println("Unauthorized, figure out how to handle this.")
		return err
	} else if token.Valid {
		return nil
	} else {
		log.Fatal("You shouldn't have got here...")
	}
	return nil
}
Ejemplo n.º 25
0
func RequireTokenAuthentication(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	authBackend := InitJWTAuthenticationBackend()

	token, err := jwt.ParseFromRequest(
		req,
		func(token *jwt.Token) (interface{}, error) {
			return authBackend.PublicKey, nil
		})

	if err == nil &&
		token.Valid &&
		!authBackend.IsInBlacklist(req.Header.Get("Authorization")) {
		next(rw, req)
	} else {
		rw.WriteHeader(http.StatusUnauthorized)
	}
}
Ejemplo n.º 26
0
// RequireTokenAuthentication ...
func RequireTokenAuthentication(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	authBackend := InitJWTAuthenticationBackend()
	token, err := jwt.ParseFromRequest(req, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		} else {
			return authBackend.PublicKey, nil
		}
	})
	fmt.Println(err)

	if err == nil && token.Valid && !authBackend.IsInBlacklist(req.Header.Get("Authorization")) {
		next(rw, req)
	} else {
		rw.WriteHeader(http.StatusUnauthorized)
	}
}
Ejemplo n.º 27
0
func jwtHandler(w http.ResponseWriter, r *http.Request) {
	token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
		return publicKey, nil
	})

	fmt.Println(err)
	fmt.Println(token)

	if err != nil {
		http.Error(w, "Bad request", 500)
	}

	if token.Valid {
		fmt.Fprintf(w, "Yo man! ")
	} else {
		fmt.Fprintf(w, "Bad ! ")
	}
}
Ejemplo n.º 28
0
// only accessible with a valid token
func authHandler(w http.ResponseWriter, r *http.Request) {
	// validate the token
	token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
		// since we only use one private key to sign the tokens,
		// we also only use its public counter part to verify
		return verifyKey, nil
	})

	if err != nil {
		switch err.(type) {

		case *jwt.ValidationError: // something was wrong during the validation
			vErr := err.(*jwt.ValidationError)

			switch vErr.Errors {
			case jwt.ValidationErrorExpired:
				w.WriteHeader(http.StatusUnauthorized)
				fmt.Fprintln(w, "Token Expired, get a new one.")
				return

			default:
				w.WriteHeader(http.StatusInternalServerError)
				fmt.Fprintln(w, "Error while Parsing Token!")
				log.Printf("ValidationError error: %+v\n", vErr.Errors)
				return
			}

		default: // something else went wrong
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintln(w, "Error while Parsing Token!")
			log.Printf("Token parse error: %v\n", err)
			return
		}

	}
	if token.Valid {
		response := Response{"Authorized to the system"}
		jsonResponse(response, w)
	} else {
		response := Response{"Invalid token"}
		jsonResponse(response, w)
	}

}
Ejemplo n.º 29
0
func authRequest(w http.ResponseWriter, r *http.Request) {
	token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (face interface{}, err error) {
		fmt.Println(face)
		return face, nil
		// return publicKey, nil
	})
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(token)

	// if token.Valid {
	//   //YAY!
	//   fmt.Println("token Valid")
	// } else {
	//   //Someone is being funny
	//   fmt.Println("totken Unautherized")
	// }
}
Ejemplo n.º 30
0
func Logout(req *http.Request) error {
	authBackend, err := auth.InitJwtAuthBackend()
	if err != nil {
		return err
	}

	token, err := jwt.ParseFromRequest(
		req,
		func(token *jwt.Token) (interface{}, error) {
			return authBackend.PublicKey, nil
		},
	)

	if err != nil {
		return err
	}

	tokenString := req.Header.Get("Authorization")
	return authBackend.TerminateToken(tokenString, token)
}