// MasterToken() generates a new token with an empty host and pool ID and the master's public key,
//  signed by the master's private key.  This will return an error if there is no master private
//  key available (i.e. if we are not the master)
186313
func MasterToken() (string, error) {
	masterpublic, err := GetMasterPublicKey()
	if err != nil {
		return "", err
	}
	keypem, err := PEMFromRSAPublicKey(masterpublic, nil)
	if err != nil {
		return "", err
	}

	signed, _, err := CreateJWTIdentity("", "", true, true, keypem, time.Hour)
	if err != nil {
		return "", err
	}

	return signed, nil
}
44209
func SignToken(c context.Context, signer signing.Signer, body *tokenserver.MachineTokenBody) (string, error) {
	s := tokensigning.Signer{
		Signer:         signer,
		SigningContext: tokenSigningContext,
		Encoding:       base64.RawStdEncoding,
		Wrap: func(w *tokensigning.Unwrapped) proto.Message {
			return &tokenserver.MachineTokenEnvelope{
				TokenBody: w.Body,
				RsaSha256: w.RsaSHA256Sig,
				KeyId:     w.KeyID,
			}
		},
	}
	return s.SignToken(c, body)
}
174009
func (t *Store) UserToken() string {
	t.l.RLock()
	defer t.l.RUnlock()

	return t.userToken
}
466115
func (c *Client) SetToken(token string, tokenSecret string) {
	c.user = oauth1.NewToken(token, tokenSecret)
	c.client = nil
}
1261756
func (mgm *tokenManager) ParseToken(ctx context.Context, tokenString string) (*TokenClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &TokenClaims{}, func(token *jwt.Token) (interface{}, error) {
		kid, ok := token.Header["kid"]
		if !ok {
			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 := mgm.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.Errorf("there is no public key with such ID: %s", kid)
		}
		return key, nil
	})
	if err != nil {
		return nil, err
	}
	claims := token.Claims.(*TokenClaims)
	if token.Valid {
		return claims, nil
	}
	return nil, errors.WithStack(errors.New("token is not valid"))
}
290207
func encodeToken(token *oauth2.Token) string {
	if token == nil {
		return ""
	}
	var seconds int64
	if !token.Expiry.IsZero() {
		seconds = token.Expiry.Unix()
	}
	return token.AccessToken + " " + token.RefreshToken + " " + strconv.FormatInt(seconds, 10)
}
685212
func (s *GetSegmentsInput) SetToken(v string) *GetSegmentsInput {
	s.Token = &v
	return s
}
56456
func generateToken(c context.Context) (string, error) {
	logging.Warningf(c, "%q is generating pprof token", auth.CurrentIdentity(c))
	return pprofToken.Generate(c, nil, nil, 0)
}
319453
func (r *Registry) Token(ctx context.Context, url string) (string, error) {
	r.Logf("registry.token url=%s", url)

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", err
	}

	client := http.DefaultClient
	if r.Opt.Insecure {
		client = &http.Client{
			Timeout: r.Opt.Timeout,
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{
					InsecureSkipVerify: true,
				},
			},
		}
	}

	resp, err := client.Do(req.WithContext(ctx))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusForbidden && gcrMatcher.MatchString(url) {
		// GCR is not sending HTTP 401 on missing credentials but a HTTP 403 without
		// any further information about why the request failed. Sending the credentials
		// from the Docker config fixes this.
		return "", ErrBasicAuth
	}

	a, err := isTokenDemand(resp)
	if err != nil {
		return "", err
	}

	if a == nil {
		r.Logf("registry.token authService=nil")
		return "", nil
	}

	authReq, err := a.Request(r.Username, r.Password)
	if err != nil {
		return "", err
	}
	resp, err = http.DefaultClient.Do(authReq.WithContext(ctx))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("getting token failed with StatusCode != StatusOK but %d", resp.StatusCode)
	}

	var authToken authToken
	if err := json.NewDecoder(resp.Body).Decode(&authToken); err != nil {
		return "", err
	}

	return authToken.String()
}
32496
func (m *Machine) EncodeToken(ctx context.Context, notifier *observer.Notifier,
	token *envelope.MachineToken) error {

	n := notifier.Notifier(2)

	n.Notify(observer.Progress, "Creating keyring memberships for token", true)

	v1members, v2members, err := createKeyringMemberships(ctx, m.engine.crypto,
		m.engine.client, m.engine.session, token.Body.OrgID, token.ID)
	if err != nil {
		return err
	}

	n.Notify(observer.Progress, "Uploading keyring memberships", true)

	if len(v1members) != 0 {
		_, err = m.engine.client.KeyringMember.Post(ctx, v1members)
		if err != nil {
			log.Printf("error uploading memberships: %s", err)
			return err
		}
	}

	for _, member := range v2members {
		err = m.engine.client.Keyring.Members.Post(ctx, member)
		if err != nil {
			log.Printf("error uploading memberships: %s", err)
			return err
		}
	}

	return nil
}
1277317
func (ldt *LogplexDrainToken) AddToken(token string) {
	ldt.Lock()
	ldt.tokens[token] = struct{}{}
	ldt.Unlock()
}
1095213
func AuthToken(ctx context.Context) (*types.AuthToken, bool) {
	if v, ok := ctx.Value(AuthTokenKey).(*types.AuthToken); ok {
		return v, ok
	}
	return nil, false
}
596661
func (c *serviceAccounts) CreateToken(name string, tr *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {
	result := &authenticationv1.TokenRequest{}
	err := c.client.Post().
		Namespace(c.ns).
		Resource("serviceaccounts").
		SubResource("token").
		Name(name).
		Body(tr).
		Do().
		Into(result)
	return result, err
}
124750
func (token *tokenRes) Token() *oauth2.Token {
	if token == nil {
		return nil
	}

	return &oauth2.Token{
		AccessToken: token.AccessToken,
		Expiry:      time.Now().Add(time.Duration(token.ExpiresIn) * time.Second),
	}
}
1059722
func (s *ImportSourceCredentialsInput) SetToken(v string) *ImportSourceCredentialsInput {
	s.Token = &v
	return s
}
1116267
func (p Standard) Token(req []byte) (token []byte, err error) {
	h := hmac.New(sha256.New, p.key)
	h.Write(req)
	h.Write(p.ad)
	return h.Sum(nil), nil
}
590507
func (t *dcosRoundtripper) GenerateToken() error {
	t.Lock()
	defer t.Unlock()

	sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: t.secret}, (&jose.SignerOptions{}).WithType("JWT"))
	if err != nil {
		return err
	}

	cl := struct {
		UID string `json:"uid"`
		Exp int64  `json:"exp"`
	}{
		t.uid,
		time.Now().Add(t.expire).Unix(),
	}
	tokenStr, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
	if err != nil {
		return err
	}

	if tokenStr == "" {
		return ErrEmptyToken
	}

	authReq := struct {
		UID   string `json:"uid"`
		Token string `json:"token,omitempty"`
		Exp   int64  `json:"exp,omitempty"`
	}{
		UID:   t.uid,
		Token: tokenStr,
		Exp:   time.Now().Add(t.expire).Unix(),
	}

	b, err := json.Marshal(authReq)
	if err != nil {
		return err
	}

	authBody := bytes.NewBuffer(b)
	req, err := http.NewRequest("POST", t.loginEndpoint, authBody)
	if err != nil {
		return err
	}

	req.Header.Add("Content-type", "application/json")
	resp, err := t.transport.RoundTrip(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return ErrTokenRefresh{
			msg: fmt.Sprintf("POST %s failed, expect response code 200. Got %d", t.loginEndpoint, resp.StatusCode),
		}
	}

	var authResp struct {
		Token string `json:"token"`
	}

	if err = json.NewDecoder(resp.Body).Decode(&authResp); err != nil {
		return err
	}

	t.token = authResp.Token
	return nil
}