// GetToken is used to get a token for a single Kite.
//
// In case of calling GetToken multiple times, it usually
// returns the same token until it expires on Kontrol side.
349256
func (k *Kite) GetToken(kite *protocol.Kite) (string, error) {
	if err := k.SetupKontrolClient(); err != nil {
		return "", err
	}

	<-k.kontrol.readyConnected

	result, err := k.kontrol.TellWithTimeout("getToken", k.Config.Timeout, kite)
	if err != nil {
		return "", err
	}

	var tkn string
	err = result.Unmarshal(&tkn)
	if err != nil {
		return "", err
	}

	return tkn, nil
}
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))
}
394789
func (ts *tokenServer) getToken(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	dcontext.GetLogger(ctx).Info("getToken")

	params := r.URL.Query()
	service := params.Get("service")
	scopeSpecifiers := params["scope"]
	var offline bool
	if offlineStr := params.Get("offline_token"); offlineStr != "" {
		var err error
		offline, err = strconv.ParseBool(offlineStr)
		if err != nil {
			handleError(ctx, ErrorBadTokenOption.WithDetail(err), w)
			return
		}
	}

	requestedAccessList := ResolveScopeSpecifiers(ctx, scopeSpecifiers)

	authorizedCtx, err := ts.accessController.Authorized(ctx, requestedAccessList...)
	if err != nil {
		challenge, ok := err.(auth.Challenge)
		if !ok {
			handleError(ctx, err, w)
			return
		}

		// Get response context.
		ctx, w = dcontext.WithResponseWriter(ctx, w)

		challenge.SetHeaders(r, w)
		handleError(ctx, errcode.ErrorCodeUnauthorized.WithDetail(challenge.Error()), w)

		dcontext.GetResponseLogger(ctx).Info("get token authentication challenge")

		return
	}
	ctx = authorizedCtx

	username := dcontext.GetStringValue(ctx, "auth.user.name")

	ctx = context.WithValue(ctx, acctSubject{}, username)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, acctSubject{}))

	dcontext.GetLogger(ctx).Info("authenticated client")

	ctx = context.WithValue(ctx, requestedAccess{}, requestedAccessList)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, requestedAccess{}))

	grantedAccessList := filterAccessList(ctx, username, requestedAccessList)
	ctx = context.WithValue(ctx, grantedAccess{}, grantedAccessList)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, grantedAccess{}))

	token, err := ts.issuer.CreateJWT(username, service, grantedAccessList)
	if err != nil {
		handleError(ctx, err, w)
		return
	}

	dcontext.GetLogger(ctx).Info("authorized client")

	response := tokenResponse{
		Token:     token,
		ExpiresIn: int(ts.issuer.Expiration.Seconds()),
	}

	if offline {
		response.RefreshToken = newRefreshToken()
		ts.refreshCache[response.RefreshToken] = refreshToken{
			subject: username,
			service: service,
		}
	}

	ctx, w = dcontext.WithResponseWriter(ctx, w)

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)

	dcontext.GetResponseLogger(ctx).Info("get token complete")
}
1316287
func (a *authenticator) getTokenFor(credentials *credentials) (string, int, error) {
	name, errCode, err := a.validateCredentials(credentials)
	if err != nil {
		return "", errCode, err
	}
	claims := jwt.StandardClaims{
		Audience:  name,
		ExpiresAt: a.expTime.Nanoseconds(),
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString([]byte(signature))
	if err != nil {
		return "", http.StatusInternalServerError, fmt.Errorf("500 internal server error: failed to sign token: %v", err)
	}
	a.userDb.SetLoginTime(name)
	a.log.Debugf("user %s was logged in", name)

	return tokenString, 0, nil
}
114564
func GetForToken(document interface{}, decodedToken string) (interface{}, reflect.Kind, error) {
	return getSingleImpl(document, decodedToken, swag.DefaultJSONNameProvider)
}
285839
func (s *ClusterPairServer) GetToken(
	ctx context.Context,
	req *api.SdkClusterPairGetTokenRequest,
) (*api.SdkClusterPairGetTokenResponse, error) {
	if s.cluster() == nil {
		return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
	}

	// Check if admin user - only system.admin can get cluster pair tokens
	if userInfo, ok := auth.NewUserInfoFromContext(ctx); ok {
		o := api.Ownership{}
		if !o.IsAdminByUser(userInfo) {
			return nil, status.Error(codes.Unauthenticated, "Must be system admin to get pair token")
		}
	}

	resp, err := s.cluster().GetPairToken(false)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "Cannot generate token: %v", err)
	}
	return &api.SdkClusterPairGetTokenResponse{
		Result: resp,
	}, nil
}
1298937
func (n *Node) Kite() (*protocol.KiteWithToken, error) {
	kite, err := n.KiteFromKey()
	if err != nil {
		return nil, err
	}

	val, err := n.Value()
	if err != nil {
		return nil, err
	}

	return &protocol.KiteWithToken{
		Kite:  *kite,
		URL:   val.URL,
		KeyID: val.KeyID,
	}, nil
}
489611
func (s *IdentityService) GetSignupToken(token string) (*services.SignupToken, error) {
	if token == "" {
		return nil, trace.BadParameter("missing token")
	}
	item, err := s.Get(context.TODO(), backend.Key(userTokensPrefix, token))
	if err != nil {
		return nil, trace.Wrap(err)
	}
	var signupToken services.SignupToken
	err = json.Unmarshal(item.Value, &signupToken)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return &signupToken, nil
}
904662
func (c *UserConfig) GetToken() (string, string) {
	if c.AccessTokenKey != "" {
		return c.AccessTokenKey, c.AccessTokenSecret
	}
	if c.RequestTokenKey != "" {
		return c.RequestTokenKey, c.RequestTokenSecret
	}
	return "", ""
}
432081
func (oauther *OAuther) ObtainToken() (err error) {
	oauther.codeChannel = make(chan string)
	oauther.errorChannel = make(chan error)

	oauther.runServerIfNecessary()

	transport := oauther.Transport()

	// Get an authorization code from the data provider.
	// ("Please ask the user if I can access this resource.")
	authCodeUrl, _ := url.QueryUnescape(oauther.config.AuthCodeURL(""))
	webbrowser.Open(authCodeUrl)

	select {
	case authCode := <-oauther.codeChannel:
		// Exchange the authorization code for an access token.
		// ("Here's the code you gave the user, now give me a token!")
		oauther.Token, err = transport.Exchange(authCode)
		return
	case err = <-oauther.errorChannel:
		return
	}
}
739328
func (h *ExternalTokenHelper) Get() (string, error) {
	var buf, stderr bytes.Buffer
	cmd, err := h.cmd("get")
	if err != nil {
		return "", err
	}
	cmd.Stdout = &buf
	cmd.Stderr = &stderr
	if err := cmd.Run(); err != nil {
		return "", errwrap.Wrapf(fmt.Sprintf("%q: {{err}}", stderr.String()), err)
	}

	return buf.String(), nil
}
666984
func (s *tokenReviewLister) Get(name string) (*v1.TokenReview, error) {
	obj, exists, err := s.indexer.GetByKey(name)
	if err != nil {
		return nil, err
	}
	if !exists {
		return nil, errors.NewNotFound(v1.Resource("tokenreview"), name)
	}
	return obj.(*v1.TokenReview), nil
}
377373
func (a *API) GetToken(token int) (*Token, error) {
	dst := new(Token)
	url := a.BuildURL("/v2/agent/token/%d", token)
	err := a.Get(url, Params{}, dst)
	return dst, err
}
1259369
func (m *TokenManager) Get(key string) (token Token) {
	stmt := Tokens.Select().Where(Tokens.C("key").Equals(key))
	m.conn.Query(stmt, &token)
	return
}
1236989
func (idp *IDP) getChallengeToken(challengeString string) (*jwt.Token, error) {
	token, err := jwt.Parse(challengeString, func(token *jwt.Token) (interface{}, error) {
		_, ok := token.Method.(*jwt.SigningMethodRSA)
		if !ok {
			return nil, ErrorBadSigningMethod
		}

		return idp.getVerificationKey()
	})

	if err != nil {
		return nil, err
	}

	if !token.Valid {
		return nil, ErrorInvalidToken
	}

	return token, nil
}
1000919
func NetGenerateToken(args ...interface{}) string {

	session := args[1].(*sessions.Session)
	return GenerateToken(args[0].(string), session.Values["formtoken"].(string))

}
875393
func (t *TokenProvider) GetToken(audience string) (*auth.Token, error) {
	signature, expiry := t.signer.SignWithDuration(audience, 2*time.Hour)
	return auth.NewToken(auth.CBSTokenTypeSAS, signature, expiry), nil
}