// jwtFromHeader returns a `jwtExtractor` that extracts token from the request header.
343234
func jwtFromHeader(header string, authScheme string) jwtExtractor {
	return func(c echo.Context) (string, error) {
		auth := c.Request().Header.Get(header)
		l := len(authScheme)
		if len(auth) > l+1 && auth[:l] == authScheme {
			return auth[l+1:], nil
		}
		return "", ErrJWTMissing
	}
}
720003
func isRequestJWT(r *http.Request) bool {
	return strings.HasPrefix(r.Header.Get("Authorization"), jwtAlgorithm)
}
624461
func ParseRequestHeader(header string) (*Auth, error) {
	auth := &Auth{ActualTimestamp: Now()}
	err := auth.ParseHeader(header, AuthHeader)
	if err != nil {
		return nil, err
	}

	if auth.Credentials.ID == "" {
		return nil, AuthFormatError{"id", "missing or empty"}
	}
	if auth.Timestamp.IsZero() {
		return nil, AuthFormatError{"ts", "missing, empty, or zero"}
	}
	if auth.Nonce == "" {
		return nil, AuthFormatError{"nonce", "missing or empty"}
	}
	auth.ReqHash = true

	return auth, nil
}
1022568
func (auth *Auth) RequestHeader() string {
	auth.MAC = auth.mac(AuthHeader)

	h := `Hawk id="` + auth.Credentials.ID +
		`", mac="` + base64.StdEncoding.EncodeToString(auth.MAC) +
		`", ts="` + strconv.FormatInt(auth.Timestamp.Unix(), 10) +
		`", nonce="` + auth.Nonce + `"`

	if len(auth.Hash) > 0 {
		h += `, hash="` + base64.StdEncoding.EncodeToString(auth.Hash) + `"`
	}
	if auth.Ext != "" {
		h += `, ext="` + auth.Ext + `"`
	}
	if auth.Credentials.App != "" {
		h += `, app="` + auth.Credentials.App + `"`
	}
	if auth.Credentials.Delegate != "" {
		h += `, dlg="` + auth.Credentials.Delegate + `"`
	}

	return h
}
1223915
func (auth *Auth) ResponseHeader(ext string) string {
	auth.Ext = ext
	if auth.ReqHash {
		auth.Hash = nil
	}

	h := `Hawk mac="` + base64.StdEncoding.EncodeToString(auth.mac(AuthResponse)) + `"`
	if auth.Ext != "" {
		h += `, ext="` + auth.Ext + `"`
	}
	if auth.Hash != nil {
		h += `, hash="` + base64.StdEncoding.EncodeToString(auth.Hash) + `"`
	}

	return h
}
413474
func (a *authenticator) getTokenStringFromRequest(req *http.Request) (result string, errCode int, err error) {
	// Try to read header, validate it if exists.
	authHeader := req.Header.Get(AuthHeaderKey)
	if authHeader != "" {
		bearerToken := strings.Split(authHeader, " ")
		if len(bearerToken) != 2 {
			return "", http.StatusUnauthorized, fmt.Errorf("401 Unauthorized: invalid authorization token")
		}
		// Parse token header constant
		if bearerToken[0] != "Bearer" {
			return "", http.StatusUnauthorized, fmt.Errorf("401 Unauthorized: invalid authorization header")
		}
		return bearerToken[1], 0, nil
	}
	a.log.Debugf("Authentication header not found (err: %v)", err)

	// Otherwise read cookie
	cookie, err := req.Cookie(cookieName)
	if err == nil && cookie != nil {
		return cookie.Value, 0, nil
	}
	a.log.Debugf("Authentication cookie not found (err: %v)", err)

	return "", http.StatusUnauthorized, fmt.Errorf("401 Unauthorized: authorization required")
}
43680
func (r *Request) AddHeader(name, value string) *Request {
	r.Use(headers.Add(name, value))
	return r
}
709247
func (c *Context) RequestHeader(key string) string {
	return c.Request.Header.Get(key)
}
436999
func (m *tokenManager) KeyFunction(ctx context.Context) jwt.Keyfunc {
	return func(token *jwt.Token) (interface{}, error) {
		kid := token.Header["kid"]
		if kid == nil {
			log.Error(ctx, map[string]interface{}{}, "There is no 'kid' header in the token")
			return nil, errors.New("There is no 'kid' header in the token")
		}
		key := m.PublicKey(fmt.Sprintf("%s", kid))
		if key == nil {
			log.Error(ctx, map[string]interface{}{
				"kid": kid,
			}, "There is no public key with such ID")
			return nil, errors.New(fmt.Sprintf("There is no public key with such ID: %s", kid))
		}
		return key, nil
	}
}
910760
func JWt(opts ...*SignOpts) fibre.MiddlewareFunc {
	return func(h fibre.HandlerFunc) fibre.HandlerFunc {
		return func(c *fibre.Context) error {

			var config *SignOpts

			switch len(opts) {
			case 0:
				return h(c)
			default:
				config = opts[0]
			}

			// This is a socket
			if c.IsSocket() {
				return h(c)
			}

			// No config has been set
			if len(config.Key) == 0 {
				return h(c)
			}

			head := c.Request().Header().Get(fibre.HeaderAuthorization)

			if head != "" && head[:6] == "Bearer" {

				token, err := jwt.Parse(head[7:], 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 config.Key, nil

				})

				if err == nil && token.Valid {
					if config.Fnc != nil {
						if err := config.Fnc(c, token.Header, token.Claims.(jwt.MapClaims)); err != nil {
							return fibre.NewHTTPError(401)
						}
					}
					return h(c)
				}

			}

			return fibre.NewHTTPError(401)

		}
	}
}
1097515
func decodeJWT(a ast.Value) (*JSONWebToken, error) {
	// Parse the JSON Web Token
	astEncode, err := builtins.StringOperand(a, 1)
	if err != nil {
		return nil, err
	}

	encoding := string(astEncode)
	if !strings.Contains(encoding, ".") {
		return nil, errors.New("encoded JWT had no period separators")
	}

	parts := strings.Split(encoding, ".")
	if len(parts) != 3 {
		return nil, fmt.Errorf("encoded JWT must have 3 sections, found %d", len(parts))
	}

	return &JSONWebToken{header: parts[0], payload: parts[1], signature: parts[2]}, nil
}
1151351
func jwtFromCookie(name string) jwtExtractor {
	return func(c echo.Context) (string, error) {
		cookie, err := c.Cookie(name)
		if err != nil {
			return "", ErrJWTMissing
		}
		return cookie.Value, nil
	}
}
133784
func (k *Kite) AuthenticateFromToken(r *Request) error {
	k.verifyOnce.Do(k.verifyInit)

	token, err := jwt.ParseWithClaims(r.Auth.Key, &kitekey.KiteClaims{}, r.LocalKite.RSAKey)

	if e, ok := err.(*jwt.ValidationError); ok {
		// Translate public key mismatch errors to token-is-expired one.
		// This is to signal remote client the key pairs have been
		// updated on kontrol and it should invalidate all tokens.
		if (e.Errors & jwt.ValidationErrorSignatureInvalid) != 0 {
			return errors.New("token is expired")
		}
	}

	if err != nil {
		return err
	}

	if !token.Valid {
		return errors.New("Invalid signature in token")
	}

	claims, ok := token.Claims.(*kitekey.KiteClaims)
	if !ok {
		return errors.New("token does not have valid claims")
	}

	if claims.Audience == "" {
		return errors.New("token has no audience")
	}

	if claims.Subject == "" {
		return errors.New("token has no username")
	}

	// check if we have an audience and it matches our own signature
	if err := k.verifyAudienceFunc(k.Kite(), claims.Audience); err != nil {
		return err
	}

	// We don't check for exp and nbf claims here because jwt-go package
	// already checks them.

	// replace the requester username so we reflect the validated
	r.Username = claims.Subject

	return nil
}
1341599
func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalToken) (string, error) {
	hasher := sha1.New()
	_, err := hasher.Write(secret.Certificate.Raw)
	if err != nil {
		return "", err
	}

	thumbprint := base64.URLEncoding.EncodeToString(hasher.Sum(nil))

	// The jti (JWT ID) claim provides a unique identifier for the JWT.
	jti := make([]byte, 20)
	_, err = rand.Read(jti)
	if err != nil {
		return "", err
	}

	token := jwt.New(jwt.SigningMethodRS256)
	token.Header["x5t"] = thumbprint
	x5c := []string{base64.StdEncoding.EncodeToString(secret.Certificate.Raw)}
	token.Header["x5c"] = x5c
	token.Claims = jwt.MapClaims{
		"aud": spt.inner.OauthConfig.TokenEndpoint.String(),
		"iss": spt.inner.ClientID,
		"sub": spt.inner.ClientID,
		"jti": base64.URLEncoding.EncodeToString(jti),
		"nbf": time.Now().Unix(),
		"exp": time.Now().Add(time.Hour * 24).Unix(),
	}

	signedString, err := token.SignedString(secret.PrivateKey)
	return signedString, err
}
631462
func (c *Client) GetBlockHeader(blockHash *chainhash.Hash) (*wire.BlockHeader, error) {
	return c.GetBlockHeaderAsync(blockHash).Receive()
}
877549
func HeaderExtractor(headers []string) func(*http.Request) string {
	return func(r *http.Request) string {
		for _, h := range headers {
			v := r.Header.Get(h)
			if v != "" {
				return v
			}
		}

		return ""
	}
}
391198
func (r *Response) AddHeader(key, value string) *Response {
	r.Header.Add(key, value)
	return r
}