// fromToken parser a token given the tokenkey provider into the desired claims
// structure
335011
func fromToken(provider tokenkey.Provider, token string, claims WithIssuer) error {
	parsed, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (key interface{}, err error) {
		if provider == nil {
			return nil, errors.New("No token provider configured")
		}

		k, err := provider.Get(claims.GetIssuer(), false)
		if err != nil {
			return nil, err
		}

		if k.Algorithm != token.Header["alg"] {
			return nil, fmt.Errorf("expected algorithm %v but got %v", k.Algorithm, token.Header["alg"])
		}

		switch k.Algorithm {
		case "RS256":
			key, err = jwt.ParseRSAPublicKeyFromPEM([]byte(k.Key))
		case "ES256":
			key, err = jwt.ParseECPublicKeyFromPEM([]byte(k.Key))
		default:
			err = fmt.Errorf("Token provider returned public key with unknown algorithm %s", k.Algorithm)
		}
		if err != nil {
			return nil, err
		}

		return key, nil
	})

	if err != nil {
		return fmt.Errorf("unable to parse token: %s", err)
	}

	if !parsed.Valid {
		return fmt.Errorf("token not valid or expired")
	}

	return nil
}
1060527
func GetToken(ctx context.Context) (string, error) {
	a, ok := ctx.Value(authorizerCtxKey).(platform.Authorizer)
	if !ok {
		return "", &platform.Error{
			Msg:  "authorizer not found on context",
			Code: platform.EInternal,
		}
	}

	auth, ok := a.(*platform.Authorization)
	if !ok {
		return "", &platform.Error{
			Msg:  fmt.Sprintf("authorizer not an authorization but a %T", a),
			Code: platform.EInternal,
		}
	}

	return auth.Token, nil
}
689165
func (a *cachedTokenAuthenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) {
	auds, _ := authenticator.AudiencesFrom(ctx)

	key := keyFunc(auds, token)
	if record, ok := a.cache.get(key); ok {
		return record.resp, record.ok, record.err
	}

	resp, ok, err := a.authenticator.AuthenticateToken(ctx, token)
	if !a.cacheErrs && err != nil {
		return resp, ok, err
	}

	switch {
	case ok && a.successTTL > 0:
		a.cache.set(key, &cacheRecord{resp: resp, ok: ok, err: err}, a.successTTL)
	case !ok && a.failureTTL > 0:
		a.cache.set(key, &cacheRecord{resp: resp, ok: ok, err: err}, a.failureTTL)
	}

	return resp, ok, err
}
1370795
func BearerToken(token string) runtime.ClientAuthInfoWriter {
	return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
		return r.SetHeaderParam("Authorization", "Bearer "+token)
	})
}
342467
func (c *MemoryTokenCache) PutToken(key *CacheKey, tok *Token) error {
	k := key.ToMapKey()
	c.lock.Lock()
	if c.cache == nil {
		c.cache = make(map[string]Token, 1)
	}
	c.cache[k] = *tok
	c.lock.Unlock()
	return nil
}
1142768
func (p *tokenManager) CreateTokenFromCertificate(cert *x509.Certificate, tags []string) ([]byte, error) {

	// Combine the application claims with the standard claims
	claims := &verifierClaims{
		X:    cert.PublicKey.(*ecdsa.PublicKey).X,
		Y:    cert.PublicKey.(*ecdsa.PublicKey).Y,
		Tags: tags,
	}
	claims.ExpiresAt = cert.NotAfter.Unix()

	// Create the token and sign with our key
	strtoken, err := jwt.NewWithClaims(p.signMethod, claims).SignedString(p.privateKey)
	if err != nil {
		return []byte{}, err
	}

	return []byte(strtoken), nil
}
1112132
func nextToken(s string) (token, rest string) {
	i := 0
	for ; i < len(s); i++ {
		if !isTokenOctet[s[i]] {
			break
		}
	}
	return s[:i], s[i:]
}
678527
func (s *Signer) SignToken(c context.Context, body proto.Message) (string, error) {
	info, err := s.Signer.ServiceInfo(c)
	if err != nil {
		return "", transient.Tag.Apply(err)
	}
	blob, err := proto.Marshal(body)
	if err != nil {
		return "", err
	}
	withCtx := prependSigningContext(blob, s.SigningContext)
	keyID, sig, err := s.Signer.SignBytes(c, withCtx)
	if err != nil {
		return "", transient.Tag.Apply(err)
	}
	tok, err := proto.Marshal(s.Wrap(&Unwrapped{
		Body:         blob,
		RsaSHA256Sig: sig,
		SignerID:     info.ServiceAccountName,
		KeyID:        keyID,
	}))
	if err != nil {
		return "", err
	}
	enc := s.Encoding
	if enc == nil {
		enc = base64.RawURLEncoding
	}
	return enc.EncodeToString(tok), nil
}
1177663
func (c *Client) AuthToken() (string, error) {
	var authToken string
	err := c.doGet("auth-token", func(r io.Reader) error {
		authTokenraw, err := ioutil.ReadAll(r)
		authToken = string(authTokenraw)
		return err
	})
	return authToken, err
}
961308
func (c *DiskTokenCache) GetToken(key *CacheKey) (*Token, error) {
	cache, err := c.readCacheFile()
	if err != nil {
		return nil, err
	}
	for _, entry := range cache.Cache {
		if EqualCacheKeys(&entry.Key, key) {
			return &Token{
				Token: entry.Token,
				Email: entry.Email,
			}, nil
		}
	}
	return nil, nil
}
242467
func SignToken(c context.Context, signer signing.Signer, subtok *messages.Subtoken) (string, error) {
	s := tokensigning.Signer{
		Signer:         signer,
		SigningContext: tokenSigningContext,
		Wrap: func(w *tokensigning.Unwrapped) proto.Message {
			return &messages.DelegationToken{
				SerializedSubtoken: w.Body,
				Pkcs1Sha256Sig:     w.RsaSHA256Sig,
				SignerId:           "user:" + w.SignerID,
				SigningKeyId:       w.KeyID,
			}
		},
	}
	return s.SignToken(c, subtok)
}
1022797
func (us UsersService) GetToken(username, password string, client Client) (string, error) {
	req := network.Request{
		Method:        "POST",
		Path:          "/oauth/token",
		Authorization: network.NewBasicAuthorization(client.ID, ""),
		Body: network.NewFormRequestBody(url.Values{
			"username":      []string{username},
			"password":      []string{password},
			"grant_type":    []string{"password"},
			"response_type": []string{"token"},
		}),
		AcceptableStatusCodes: []int{http.StatusOK},
	}

	resp, err := newNetworkClient(us.config).MakeRequest(req)
	if err != nil {
		return "", translateError(err)
	}

	var responseBody struct {
		AccessToken string `json:"access_token"`
	}
	err = json.Unmarshal(resp.Body, &responseBody)
	if err != nil {
		return "", MalformedResponseError{err}
	}

	return responseBody.AccessToken, nil
}
29436
func (t *tokenAccessor) ParseAckToken(auth *connection.AuthInfo, data []byte) (*tokens.ConnectionClaims, error) {

	gt := t.getToken()
	if gt == nil {
		return nil, errors.New("token is nil")
	}
	if auth == nil {
		return nil, errors.New("auth is nil")
	}
	// Validate the certificate and parse the token
	claims, _, _, err := t.getToken().Decode(true, data, auth.RemotePublicKey)
	if err != nil {
		return nil, err
	}

	// Compare the incoming random context with the stored context
	matchLocal := bytes.Compare(claims.RMT, auth.LocalContext)
	matchRemote := bytes.Compare(claims.LCL, auth.RemoteContext)
	if matchLocal != 0 || matchRemote != 0 {
		return nil, errors.New("failed to match context in ack packet")
	}

	return claims, nil
}
496140
func (c *Client) GetToken(tokenID string, args Arguments) (token *Token, err error) {
	path := fmt.Sprintf("tokens/%s", tokenID)
	err = c.Get(path, args, &token)
	if token != nil {
		token.client = c
	}
	return
}
421935
func (s *ProvisioningService) GetToken(token string) (services.ProvisionToken, error) {
	if token == "" {
		return nil, trace.BadParameter("missing parameter token")
	}
	item, err := s.Get(context.TODO(), backend.Key(tokensPrefix, token))
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return services.UnmarshalProvisionToken(item.Value, services.SkipValidation(),
		services.WithResourceID(item.ID), services.WithExpires(item.Expires))
}
944228
func (c *Cache) GetToken(token string) (services.ProvisionToken, error) {
	return c.provisionerCache.GetToken(token)
}
828852
func (c *JWTClaims) FromMap(m map[string]interface{}) {
	c.Extra = make(map[string]interface{})
	for k, v := range m {
		switch k {
		case "jti":
			if s, ok := v.(string); ok {
				c.JTI = s
			}
		case "sub":
			if s, ok := v.(string); ok {
				c.Subject = s
			}
		case "iss":
			if s, ok := v.(string); ok {
				c.Issuer = s
			}
		case "aud":
			if s, ok := v.(string); ok {
				c.Audience = []string{s}
			} else if s, ok := v.([]string); ok {
				c.Audience = s
			}
		case "iat":
			switch v.(type) {
			case float64:
				c.IssuedAt = time.Unix(int64(v.(float64)), 0).UTC()
			case int64:
				c.IssuedAt = time.Unix(v.(int64), 0).UTC()
			}
		case "nbf":
			switch v.(type) {
			case float64:
				c.NotBefore = time.Unix(int64(v.(float64)), 0).UTC()
			case int64:
				c.NotBefore = time.Unix(v.(int64), 0).UTC()
			}
		case "exp":
			switch v.(type) {
			case float64:
				c.ExpiresAt = time.Unix(int64(v.(float64)), 0).UTC()
			case int64:
				c.ExpiresAt = time.Unix(v.(int64), 0).UTC()
			}
		case "scp":
			switch v.(type) {
			case []string:
				c.Scope = v.([]string)
			case []interface{}:
				c.Scope = make([]string, len(v.([]interface{})))
				for i, vi := range v.([]interface{}) {
					if s, ok := vi.(string); ok {
						c.Scope[i] = s
					}
				}
			}
		default:
			c.Extra[k] = v
		}
	}
}