当前位置: 首页>>代码示例>>Golang>>正文


Golang jwt-go.ParseFromRequest函数代码示例

本文整理汇总了Golang中github.com/dgrijalva/jwt-go.ParseFromRequest函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseFromRequest函数的具体用法?Golang ParseFromRequest怎么用?Golang ParseFromRequest使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了ParseFromRequest函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: jwtWrap

// 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)
	}
}
开发者ID:Lanzafame,项目名称:tiedot,代码行数:26,代码来源:jwt.go

示例2: ServeHTTP

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)
	}
}
开发者ID:yolofy,项目名称:BulbTransit,代码行数:35,代码来源:JWTFilter.go

示例3: RequireTokenAuthentication

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
}
开发者ID:simoyang0704,项目名称:cubar.com,代码行数:27,代码来源:midwares.go

示例4: RequireLogin

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()
	}
}
开发者ID:jeff235255,项目名称:forum,代码行数:29,代码来源:authen.go

示例5: ValidateTokenAuthentication

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)
	}
}
开发者ID:malloc-fi,项目名称:vantaa,代码行数:30,代码来源:jwt_middlewares.go

示例6: getAndValidateJwtTokenFromRequest

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"))
	}
}
开发者ID:francoishill,项目名称:golang-common-ddd,代码行数:34,代码来源:service.go

示例7: Auth

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)
		}
	}
}
开发者ID:kotokz,项目名称:yocal-cljs,代码行数:33,代码来源:auth.go

示例8: AuthRequest

// 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)
		}

	}
}
开发者ID:ngaut,项目名称:beego,代码行数:26,代码来源:jwt.go

示例9: RequireTokenAuthentication

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)
	}
}
开发者ID:malloc-fi,项目名称:vantaa,代码行数:35,代码来源:jwt_middlewares.go

示例10: Logout

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)
}
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:11,代码来源:auth_service.go

示例11: AuthMiddleware

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")
	}
}
开发者ID:greatontime,项目名称:golangtut,代码行数:11,代码来源:auth.go

示例12: Logout

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)
}
开发者ID:giovanni-liboni,项目名称:golang-jwt-authentication-api-sample,代码行数:11,代码来源:auth_service.go

示例13: authMiddleware

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")
	}
}
开发者ID:yourchanges,项目名称:go-web,代码行数:12,代码来源:jwtmiddleware.go

示例14: Auth

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)
		}
	}
}
开发者ID:doubledutch,项目名称:dd-vote,代码行数:12,代码来源:jwt.go

示例15: Authorize

// 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,
		)
	}
}
开发者ID:yourchanges,项目名称:go-web,代码行数:54,代码来源:auth.go


注:本文中的github.com/dgrijalva/jwt-go.ParseFromRequest函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。