// Parse, validate, and return a token.
// keyFunc will receive the parsed token and should return the key for validating.
// If everything is kosher, err will be nil
497657
func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
	return new(Parser).Parse(tokenString, keyFunc)
}
243915
func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
	return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc)
}
1317411
func (mw *GinJWTMiddleware) ParseTokenString(token string) (*jwt.Token, error) {
	return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
		if jwt.GetSigningMethod(mw.SigningAlgorithm) != t.Method {
			return nil, ErrInvalidSigningAlgorithm
		}
		if mw.usingPublicKeyAlgo() {
			return mw.pubKey, nil
		}

		return mw.Key, nil
	})
}
499145
func (s *AccessTokenSession) TokenFunc(retried bool) (string, error) {
	if !s.token.IsValid() || retried {
		refreshToken, refreshable := s.token.(RefreshableAccessToken)
		if !refreshable {
			return "", errors.New("not a refresh token")
		}

		tokenResp, err := s.uaa.RefreshTokenGrant(refreshToken.RefreshValue())
		if err != nil {
			return "", bosherr.WrapError(err, "refreshing token")
		}

		s.token = tokenResp
		if err = s.saveTokenCreds(); err != nil {
			return "", err
		}
	}

	return s.token.Type() + " " + s.token.Value(), nil
}
1233
func (p *Parser) parseKeyAndInferOperator() (string, Operator, error) {
	var operator Operator
	tok, literal := p.consume(Values)
	if tok == DoesNotExistToken {
		operator = DoesNotExistOperator
		tok, literal = p.consume(Values)
	}
	if tok != IdentifierToken {
		err := fmt.Errorf("found '%s', expected: identifier", literal)
		return "", "", err
	}
	if err := validateLabelKey(literal); err != nil {
		return "", "", err
	}
	if t, _ := p.lookahead(Values); t == EndOfStringToken || t == CommaToken {
		if operator != DoesNotExistOperator {
			operator = ExistsOperator
		}
	}
	return literal, operator, nil
}
689368
func keyFromHeader(header string, authScheme string) keyExtractor {
	return func(c echo.Context) (string, error) {
		auth := c.Request().Header.Get(header)
		if auth == "" {
			return "", errors.New("missing key in request header")
		}
		if header == echo.HeaderAuthorization {
			l := len(authScheme)
			if len(auth) > l+1 && auth[:l] == authScheme {
				return auth[l+1:], nil
			}
			return "", errors.New("invalid key in the request header")
		}
		return auth, nil
	}
}
483378
func (a *authenticator) Validate(provider http.HandlerFunc) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		// Token may be accessed via cookie, or from authentication header
		tokenString, errCode, err := a.getTokenStringFromRequest(req)
		if err != nil {
			a.formatter.Text(w, errCode, err.Error())
			return
		}
		// Retrieve token object from raw string
		token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
			if _, ok := jwt.GetSigningMethod(token.Header["alg"].(string)).(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("error parsing token")
			}
			return []byte(signature), nil
		})
		if err != nil {
			errStr := fmt.Sprintf("500 internal server error: %s", err)
			a.formatter.Text(w, http.StatusInternalServerError, errStr)
			return
		}
		// Validate token claims
		if token.Claims != nil {
			if err := token.Claims.Valid(); err != nil {
				errStr := fmt.Sprintf("401 Unauthorized: %v", err)
				a.formatter.Text(w, http.StatusUnauthorized, errStr)
				return
			}
		}
		// Validate token itself
		if err := a.validateToken(token, req.URL.Path, req.Method); err != nil {
			errStr := fmt.Sprintf("401 Unauthorized: %v", err)
			a.formatter.Text(w, http.StatusUnauthorized, errStr)
			return
		}

		provider.ServeHTTP(w, req)
	})
}
214157
func (p SeparatorKeyParser) Parse(k string) Key {
	return NewKeySep(k, string(p))
}
666660
func (n *Tokenize) NewToken(start, end int) *Token {
  return &Token { n, start, end }
}
1371108
func (j *JWT) KeyFuncRS256(token *gojwt.Token) (interface{}, error) {
	// Don't forget to validate the alg is what you expect:
	if _, ok := token.Method.(*gojwt.SigningMethodRSA); !ok {
		return nil, fmt.Errorf("unsupported signing method: %v", token.Header["alg"])
	}

	// read JWKS document from key discovery service
	if j.Jwksurl == "" {
		return nil, fmt.Errorf("token JWKSURL not specified, cannot validate RS256 signature")
	}

	rr, err := http.Get(j.Jwksurl)
	if err != nil {
		return nil, err
	}
	defer rr.Body.Close()
	body, err := ioutil.ReadAll(rr.Body)
	if err != nil {
		return nil, err
	}

	// parse json to struct
	var jwks JWKS
	if err := json.Unmarshal([]byte(body), &jwks); err != nil {
		return nil, err
	}

	// extract cert when kid and alg match
	var certPkix []byte
	for _, jwk := range jwks.Keys {
		if token.Header["kid"] == jwk.Kid {
			// FIXME: optionally walk the key chain, see rfc7517 section 4.7
			certPkix, err = base64.StdEncoding.DecodeString(jwk.X5c[0])
			if err != nil {
				return nil, fmt.Errorf("base64 decode error for JWK kid %v", token.Header["kid"])
			}
		}
	}
	if certPkix == nil {
		return nil, fmt.Errorf("no signing key found for kid %v", token.Header["kid"])
	}

	// parse certificate (from PKIX format) and return signing key
	cert, err := x509.ParseCertificate(certPkix)
	if err != nil {
		return nil, err
	}
	return cert.PublicKey, nil
}
1252993
func KeyAuth(fn KeyAuthValidator) echo.MiddlewareFunc {
	c := DefaultKeyAuthConfig
	c.Validator = fn
	return KeyAuthWithConfig(c)
}
1241744
func (registry *Registry) RegisterFunc(name string, check func() error) {
	registry.Register(name, CheckFunc(check))
}
21331
func (t *Tree) parseCasingFunc(name string) (Node, error) {
	node := new(FuncNode)
	node.Param = name

	t.scanner.accept = acceptCasingFunc
	t.scanner.mode = scanIdent
	switch t.scanner.scan() {
	case tokenIdent:
		node.Name = t.scanner.string()
	default:
		return nil, ErrBadSubstitution
	}

	return node, t.consumeRbrack()
}
855196
func NewToken() (*Token, error) {
	id, err := utils.RandomBytes(tokenIDBytes)
	if err != nil {
		return nil, err
	}

	secret, err := utils.RandomBytes(tokenSecretBytes)
	if err != nil {
		return nil, err
	}

	return &Token{ID: id, Secret: secret}, nil
}
597448
func (m *tokenManager) Parse(ctx context.Context, tokenString string) (*jwt.Token, error) {
	keyFunc := m.KeyFunction(ctx)
	jwtToken, err := jwt.Parse(tokenString, keyFunc)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err": err,
		}, "unable to parse token")
		return nil, autherrors.NewUnauthorizedError(err.Error())
	}
	return jwtToken, nil
}
1272301
func (s *Statement) LitByteFunc(f func() byte) *Statement {
	t := token{
		typ:     literalByteToken,
		content: f(),
	}
	*s = append(*s, t)
	return s
}
1093509
func KeyMatchFunc(args ...interface{}) (interface{}, error) {
	name1 := args[0].(string)
	name2 := args[1].(string)

	return bool(KeyMatch(name1, name2)), nil
}