當前位置: 首頁>>代碼示例>>Golang>>正文


Golang jwt-go.Parse函數代碼示例

本文整理匯總了Golang中github.com/dgrijalva/jwt-go.Parse函數的典型用法代碼示例。如果您正苦於以下問題:Golang Parse函數的具體用法?Golang Parse怎麽用?Golang Parse使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Parse函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: readToken

func (m *defaultSessionManager) readToken(r *http.Request) (string, error) {
	tokenString := r.Header.Get(tokenHeader)
	if tokenString == "" {
		return "", nil
	}

	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return m.verifyKey, nil
	})
	switch err.(type) {
	case nil:
		if !token.Valid {
			return "", nil
		}

		claims := token.Claims.(jwt.MapClaims)
		houseID := claims["houseID"].(string)

		return houseID, nil
	case *jwt.ValidationError:
		return "", nil
	default:
		return "", errgo.Mask(err)
	}
}
開發者ID:writeas,項目名稱:htmlhouse,代碼行數:28,代碼來源:session.go

示例2: ParseToken

func (authen *Authen) ParseToken(tokenString string) (*jwt.Token, error) {
	myToken, err := jwt.Parse(tokenString, func(tokenWithin *jwt.Token) (interface{}, error) {
		if _, ok := tokenWithin.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", tokenWithin.Header["alg"])
		}
		if tokenWithin.Method.Alg() != "HS512" {
			return nil, fmt.Errorf("Unexpected signing method string: %v", tokenWithin.Header["alg"])
		}
		exp, ok := tokenWithin.Claims["exp"].(float64)
		if !ok {
			return nil, fmt.Errorf("Token does not contain expiry claim")
		}
		if exp < float64(time.Now().Unix()) {
			return nil, fmt.Errorf("Token expired")
		}
		return authen.privateKey, nil
	})
	if err != nil {
		return nil, err
	}
	if !myToken.Valid {
		return nil, fmt.Errorf("Token is invalid")
	}
	return myToken, err
}
開發者ID:tianhai82,項目名稱:gae_authen,代碼行數:25,代碼來源:auth.go

示例3: Auth

func (s *Server) Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		pubKey := s.Tables["divan"].PubKey
		if pubKey == "" {
			c.Next()
			return
		}
		token := c.Query("token")
		if token == "" {
			c.JSON(401, gin.H{"error": "missing token"})
			c.Abort()
			return
		}

		out, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
				return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
			}
			return []byte(pubKey), nil
		})
		if err != nil {
			c.JSON(400, gin.H{"error": err.Error()})
			c.Abort()
			return
		}
		if !out.Valid {
			c.JSON(403, gin.H{"error": "Token invalid"})
			c.Abort()
			return
		}

		c.Set("token", out)
		c.Next()
	}
}
開發者ID:lancecarlson,項目名稱:divan,代碼行數:35,代碼來源:server.go

示例4: Extract

func (mgm tokenManager) Extract(tokenString string) (*account.Identity, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return mgm.publicKey, nil
	})
	if err != nil {
		return nil, errors.WithStack(err)
	}

	if !token.Valid {
		return nil, errors.New("Token not valid")
	}

	claimedUUID := token.Claims.(jwt.MapClaims)["sub"]
	if claimedUUID == nil {
		return nil, errors.New("Subject can not be nil")
	}
	// in case of nil UUID, below type casting will fail hence we need above check
	id, err := uuid.FromString(token.Claims.(jwt.MapClaims)["sub"].(string))
	if err != nil {
		return nil, errors.WithStack(err)
	}

	ident := account.Identity{
		ID:       id,
		Username: token.Claims.(jwt.MapClaims)["preferred_username"].(string),
	}

	return &ident, nil
}
開發者ID:Ritsyy,項目名稱:almighty-core,代碼行數:29,代碼來源:token.go

示例5: getAuth

// returns username and boolean indicating if the token was valid
func getAuth(r *http.Request) (string, bool) {
	// check if we have a cookie with our tokenName
	tokenCookie, err := r.Cookie(tokenName)

	if err != nil {
		return "", false
	}

	// validate the token
	token, err := jwt.Parse(tokenCookie.Value, func(token *jwt.Token) (interface{}, error) {
		return verifyKey, nil
	})

	if err == nil && token.Valid {
		str, ok := token.Claims["username"].(string)
		if ok {
			return str, true
		} else {
			log.Print("token.Claims[\"username\"] Not a string.")
			return "", false
		}

	}

	return "", false
}
開發者ID:min2033,項目名稱:WebVR-Test,代碼行數:27,代碼來源:app.go

示例6: readToken

func (m *defaultSessionManager) readToken(r *http.Request) (int64, error) {
	tokenString := r.Header.Get(tokenHeader)
	if tokenString == "" {
		return 0, nil
	}
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return m.verifyKey, nil
	})
	switch err.(type) {
	case nil:
		if !token.Valid {
			return 0, nil
		}
		token := token.Claims["uid"].(string)
		userID, err := strconv.ParseInt(token, 10, 0)
		if err != nil {
			return 0, nil
		}
		return userID, nil
	case *jwt.ValidationError:
		return 0, nil
	default:
		return 0, errgo.Mask(err)
	}
}
開發者ID:sandbreaker,項目名稱:photoshare,代碼行數:25,代碼來源:session.go

示例7: Auth

func Auth(rw http.ResponseWriter, req *http.Request) bool {
	if !config.Config.Auth {
		return true
	}
	tokenString := req.URL.Query().Get("token")

	if len(tokenString) == 0 {
		return false
	}

	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return config.Config.ParsedPublicKey, nil
	})
	SetToken(req, token)

	if err != nil {
		common.CheckError(err, 2)
		return false
	}

	if !token.Valid {
		return false
	}

	if config.Config.HostUuidCheck && token.Claims["hostUuid"] != config.Config.HostUuid {
		glog.Infoln("Host UUID mismatch , authentication failed")
		return false
	}

	return true
}
開發者ID:wlan0,項目名稱:host-api,代碼行數:31,代碼來源:auth.go

示例8: getTokenData

func getTokenData(jwtSigningKey string, r *http.Request) (*TokenData, error) {
	encToken, err := r.Cookie(CookieName)
	if err != nil {
		return nil, err
	}

	token, err := jwt.Parse(encToken.Value, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(jwtSigningKey), nil
	})

	if err != nil {
		return nil, err
	}
	if !token.Valid {
		return nil, fmt.Errorf("invalid token")
	}

	userInterface, hasUser := token.Claims["user"]
	roleInterface, hasRole := token.Claims["role"]
	user, userIsStr := userInterface.(string)
	role, roleIsStr := roleInterface.(string)
	if !hasUser || !hasRole || !userIsStr || !roleIsStr {
		// we signed it: this should never happen
		return nil, fmt.Errorf("token missing claims")
	}

	return &TokenData{User: user, Role: role}, nil
}
開發者ID:CadeLaRen,項目名稱:traffic_control,代碼行數:31,代碼來源:traffic_ops_auth.go

示例9: TestJWTToken

func TestJWTToken(t *testing.T) {
	var err error
	if privateKey, err = ioutil.ReadFile("rsa-test.key"); err != nil {
		t.Fatal(err)
	}
	if publicKey, err = ioutil.ReadFile("rsa-test.pub"); err != nil {
		t.Fatal(err)
	}
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims["PERMISSION"] = "[email protected]"
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	ts, err := token.SignedString(privateKey)
	if err != nil {
		t.Fatal(err)
	}
	if token, err = jwt.Parse(ts, func(ts *jwt.Token) (interface{}, error) {
		return publicKey, nil
	}); err != nil {
		t.Fatal(err)
	}
	if token.Valid {
		t.Log(token)
	} else {
		t.Log(token)
		t.Fail()
	}
}
開發者ID:marble58,項目名稱:tiedot,代碼行數:27,代碼來源:rsa_test.go

示例10: subjectFromBearerToken

func subjectFromBearerToken(core *roll.Core, r *http.Request) (string, error) {
	//Check for header presence
	authzHeader := r.Header.Get("Authorization")
	if authzHeader == "" {
		return "", errors.New("Authorization header missing from request")
	}

	//Header format should be Bearer token
	parts := strings.SplitAfter(authzHeader, "Bearer")
	if len(parts) != 2 {
		return "", errors.New("Unexpected authorization header format - expecting bearer token")
	}

	//Parse the token
	bearerToken := strings.TrimSpace(parts[1])
	token, err := jwt.Parse(bearerToken, rolltoken.GenerateKeyExtractionFunction(core.SecretsRepo))
	if err != nil {
		return "", err
	}

	//Grab the subject from the claims
	subject, ok := token.Claims["sub"].(string)
	if !ok {
		return "", errors.New("problem with subject claim")
	}

	//Is the subject something other than an empty string?
	if subject == "" {
		return "", errors.New("empty subject claim")
	}

	return subject, nil
}
開發者ID:xtraclabs,項目名稱:roll,代碼行數:33,代碼來源:token.go

示例11: showToken

// showToken pretty-prints the token on the command line.
func showToken() error {
	// get the token
	tokData, err := loadData(*flagShow)
	if err != nil {
		return fmt.Errorf("Couldn't read token: %v", err)
	}

	// trim possible whitespace from token
	tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
	if *flagDebug {
		fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
	}

	token, err := jwt.Parse(string(tokData), nil)
	if token == nil {
		return fmt.Errorf("malformed token: %v", err)
	}

	// Print the token details
	fmt.Println("Header:")
	if err := printJSON(token.Header); err != nil {
		return fmt.Errorf("Failed to output header: %v", err)
	}

	fmt.Println("Claims:")
	if err := printJSON(token.Claims); err != nil {
		return fmt.Errorf("Failed to output claims: %v", err)
	}

	return nil
}
開發者ID:wutaizeng,項目名稱:kapacitor,代碼行數:32,代碼來源:app.go

示例12: GetUserFromToken

func GetUserFromToken(token string) (*rbac.User, error) {
	_, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		// Don't forget to validate the alg is what you expect:
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("Unexpected signing method")
		}

		expiredText, _ := token.Claims["expired"].(string)

		expiredTime, err := time.Parse(time.RFC3339, expiredText)
		if err != nil {
			log.Error("Fail to parse expired time. Token %v error %s", token, err)
			return nil, err
		}

		if expiredTime.Before(time.Now()) {
			log.Debug("Token is expired. Token %v ", token)
			return nil, errors.New("Token is expired")
		}
		return []byte(signingKey), nil
	})

	if err != nil {
		return nil, err
	} else {
		user := rbac.GetCache(token)
		if user != nil {
			return user, nil
		} else {
			log.Error("User not in the cache. Token %v", token)
			return nil, errors.New("User not in the cache")
		}
	}
}
開發者ID:cloudawan,項目名稱:cloudone,代碼行數:34,代碼來源:token.go

示例13: Download

// Download - file download handler.
func (web *webAPIHandlers) Download(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	bucket := vars["bucket"]
	object := vars["object"]
	token := r.URL.Query().Get("token")

	jwt := initJWT()
	jwttoken, e := jwtgo.Parse(token, 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 || !jwttoken.Valid {
		writeWebErrorResponse(w, errInvalidToken)
		return
	}
	// Add content disposition.
	w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filepath.Base(object)))

	objInfo, err := web.ObjectAPI.GetObjectInfo(bucket, object)
	if err != nil {
		writeWebErrorResponse(w, err)
		return
	}
	offset := int64(0)
	err = web.ObjectAPI.GetObject(bucket, object, offset, objInfo.Size, w)
	if err != nil {
		/// No need to print error, response writer already written to.
		return
	}
}
開發者ID:yrashk,項目名稱:minio,代碼行數:33,代碼來源:web-handlers.go

示例14: GetUserInfo

func GetUserInfo(res http.ResponseWriter, req *http.Request) {
	AuthKey := http.CanonicalHeaderKey("authorization")
	tokenString := strings.Replace(req.Header.Get(AuthKey), "Bearer ", "", -1)
	// fmt.Println(tokenString)

	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		fmt.Println(token)
		return loadData("demo.rsa.pub")
	})

	if err == nil && token.Valid {
		fmt.Println("Your token is valid.  I like your style.")

		rt, _ := json.Marshal(Result{http.StatusOK, "Successful", tokenString})
		res.Header().Set("Content-Type", "application/json")
		res.WriteHeader(http.StatusOK)
		res.Write(rt)
	} else {
		fmt.Println("This token is terrible!  I cannot accept this.")
		fmt.Println(err)

		rt, _ := json.Marshal(Result{http.StatusUnauthorized, "Token Unauthorized", tokenString})
		res.Header().Set("Content-Type", "application/json")
		res.WriteHeader(http.StatusUnauthorized)
		res.Write(rt)
	}
}
開發者ID:csrgxtu,項目名稱:Gosrc,代碼行數:27,代碼來源:server.go

示例15: VerifyJWTRSA

// Verify a JWT token using an RSA public key
func VerifyJWTRSA(token, publicKey string) (bool, *jwt.Token, error) {

	var parsedToken *jwt.Token

	// parse token
	state, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {

		// ensure signing method is correct
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, errors.New("unknown signing method")
		}

		parsedToken = token

		// verify
		key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(publicKey))
		if err != nil {
			return nil, err
		}

		return key, nil
	})

	if err != nil {
		return false, &jwt.Token{}, err
	}

	if !state.Valid {
		return false, &jwt.Token{}, errors.New("invalid jwt token")
	}

	return true, parsedToken, nil
}
開發者ID:stonedoc,項目名稱:stone,代碼行數:34,代碼來源:crypto.go


注:本文中的github.com/dgrijalva/jwt-go.Parse函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。