// RegisterUsingToken calls the auth service API to register a new node using a registration token
// which was previously issued via GenerateToken.
194170
func (c *Client) RegisterUsingToken(req RegisterUsingTokenRequest) (*PackedKeys, error) {
	if err := req.CheckAndSetDefaults(); err != nil {
		return nil, trace.Wrap(err)
	}
	out, err := c.PostJSON(c.Endpoint("tokens", "register"), req)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	var keys PackedKeys
	if err := json.Unmarshal(out.Bytes(), &keys); err != nil {
		return nil, trace.Wrap(err)
	}
	return &keys, nil
}
1241681
func (s *RemoveResourcePermissionInput) SetAuthenticationToken(v string) *RemoveResourcePermissionInput {
	s.AuthenticationToken = &v
	return s
}
1144076
func WithToken(ctx context.Context, token *AuthorizationToken) context.Context {
	return context.WithValue(ctx, tokenIndex, token)
}
174009
func (t *Store) UserToken() string {
	t.l.RLock()
	defer t.l.RUnlock()

	return t.userToken
}
451120
func (h *CSRFHandler) RegenerateToken(w http.ResponseWriter, r *http.Request) string {
	token := generateToken()
	h.setTokenCookie(w, r, token)

	return Token(r)
}
770737
func (authy *Authy) VerifyToken(userID string, token string, params url.Values) (*TokenVerification, error) {
	path := "/protected/json/verify/" + url.QueryEscape(token) + "/" + url.QueryEscape(userID)

	response, err := authy.DoRequest("GET", path, params)

	if err != nil {
		Logger.Println("Error while contacting the API:", err)
		return nil, err
	}

	defer closeResponseBody(response)

	tokenVerification, err := NewTokenVerification(response)
	return tokenVerification, err
}
353575
func (t *Token) SigningString() (string, error) {
	var err error
	parts := make([]string, 2)
	for i, _ := range parts {
		var jsonValue []byte
		if i == 0 {
			if jsonValue, err = json.Marshal(t.Header); err != nil {
				return "", err
			}
		} else {
			if jsonValue, err = json.Marshal(t.Claims); err != nil {
				return "", err
			}
		}

		parts[i] = EncodeSegment(jsonValue)
	}
	return strings.Join(parts, "."), nil
}
1277317
func (ldt *LogplexDrainToken) AddToken(token string) {
	ldt.Lock()
	ldt.tokens[token] = struct{}{}
	ldt.Unlock()
}
769841
func (s *GetCurrentUserInput) SetAuthenticationToken(v string) *GetCurrentUserInput {
	s.AuthenticationToken = &v
	return s
}
233792
func (s *DeleteCommentInput) SetAuthenticationToken(v string) *DeleteCommentInput {
	s.AuthenticationToken = &v
	return s
}
1305699
func (c *client) Register(s *Service) error {
	if s.Path[len(s.Path)-1] != '/' {
		s.Path += "/"
	}
	path := s.Path + s.Name
	if err := c.CreateParentNodes(path); err != nil {
		return err
	}
	if path[len(path)-1] != '/' {
		path += "/"
	}
	node, err := c.CreateProtectedEphemeralSequential(path, s.Data, c.acl)
	if err != nil {
		return err
	}
	s.node = node
	return nil
}
987753
func (s *UpdateFolderInput) SetAuthenticationToken(v string) *UpdateFolderInput {
	s.AuthenticationToken = &v
	return s
}
949316
func (c *Catalog) Register(args *structs.RegisterRequest, reply *struct{}) error {
	if done, err := c.srv.forward("Catalog.Register", args, args, reply); done {
		return err
	}
	defer metrics.MeasureSince([]string{"catalog", "register"}, time.Now())

	// Fetch the ACL token, if any.
	rule, err := c.srv.ResolveToken(args.Token)
	if err != nil {
		return err
	}

	// Verify the args.
	if err := nodePreApply(args.Node, string(args.ID)); err != nil {
		return err
	}
	if args.Address == "" && !args.SkipNodeUpdate {
		return fmt.Errorf("Must provide address if SkipNodeUpdate is not set")
	}

	// Handle a service registration.
	if args.Service != nil {
		if err := servicePreApply(args.Service, rule); err != nil {
			return err
		}
	}

	// Move the old format single check into the slice, and fixup IDs.
	if args.Check != nil {
		args.Checks = append(args.Checks, args.Check)
		args.Check = nil
	}
	for _, check := range args.Checks {
		if check.Node == "" {
			check.Node = args.Node
		}
		checkPreApply(check)
	}

	// Check the complete register request against the given ACL policy.
	if rule != nil && c.srv.config.ACLEnforceVersion8 {
		state := c.srv.fsm.State()
		_, ns, err := state.NodeServices(nil, args.Node)
		if err != nil {
			return fmt.Errorf("Node lookup failed: %v", err)
		}
		if err := vetRegisterWithACL(rule, args, ns); err != nil {
			return err
		}
	}

	resp, err := c.srv.raftApply(structs.RegisterRequestType, args)
	if err != nil {
		return err
	}
	if respErr, ok := resp.(error); ok {
		return respErr
	}
	return nil
}
924462
func (s *DescribeRootFoldersInput) SetAuthenticationToken(v string) *DescribeRootFoldersInput {
	s.AuthenticationToken = &v
	return s
}
658567
func (c *Core) ValidateWrappingToken(ctx context.Context, req *logical.Request) (bool, error) {
	if req == nil {
		return false, fmt.Errorf("invalid request")
	}

	var err error

	var token string
	var thirdParty bool
	if req.Data != nil && req.Data["token"] != nil {
		thirdParty = true
		if tokenStr, ok := req.Data["token"].(string); !ok {
			return false, fmt.Errorf("could not decode token in request body")
		} else if tokenStr == "" {
			return false, fmt.Errorf("empty token in request body")
		} else {
			token = tokenStr
		}
	} else {
		token = req.ClientToken
	}

	// Check for it being a JWT. If it is, and it is valid, we extract the
	// internal client token from it and use that during lookup. The second
	// check is a quick check to verify that we don't consider a namespaced
	// token to be a JWT -- namespaced tokens have two dots too, but Vault
	// token types (for now at least) begin with a letter representing a type
	// and then a dot.
	if strings.Count(token, ".") == 2 && token[1] != '.' {
		// Implement the jose library way
		parsedJWT, err := squarejwt.ParseSigned(token)
		if err != nil {
			return false, errwrap.Wrapf("wrapping token could not be parsed: {{err}}", err)
		}
		var claims squarejwt.Claims
		var allClaims = make(map[string]interface{})
		if err = parsedJWT.Claims(&c.wrappingJWTKey.PublicKey, &claims, &allClaims); err != nil {
			return false, errwrap.Wrapf("wrapping token signature could not be validated: {{err}}", err)
		}
		typeClaimRaw, ok := allClaims["type"]
		if !ok {
			return false, errors.New("could not validate type claim")
		}
		typeClaim, ok := typeClaimRaw.(string)
		if !ok {
			return false, errors.New("could not parse type claim")
		}
		if typeClaim != "wrapping" {
			return false, errors.New("unexpected type claim")
		}
		if !thirdParty {
			req.ClientToken = claims.ID
		} else {
			req.Data["token"] = claims.ID
		}
		token = claims.ID
	}

	if token == "" {
		return false, fmt.Errorf("token is empty")
	}

	if c.Sealed() {
		return false, consts.ErrSealed
	}

	c.stateLock.RLock()
	defer c.stateLock.RUnlock()
	if c.standby && !c.perfStandby {
		return false, consts.ErrStandby
	}

	te, err := c.tokenStore.Lookup(ctx, token)
	if err != nil {
		return false, err
	}
	if te == nil {
		return false, nil
	}

	if len(te.Policies) != 1 {
		return false, nil
	}

	if te.Policies[0] != responseWrappingPolicyName && te.Policies[0] != controlGroupPolicyName {
		return false, nil
	}

	if !thirdParty {
		req.ClientTokenAccessor = te.Accessor
		req.ClientTokenRemainingUses = te.NumUses
		req.SetTokenEntry(te)
	}

	return true, nil
}
972927
func (s *AuthServer) GenerateToken(req GenerateTokenRequest) (string, error) {
	if err := req.CheckAndSetDefaults(); err != nil {
		return "", trace.Wrap(err)
	}
	token, err := services.NewProvisionToken(req.Token, req.Roles, s.clock.Now().UTC().Add(req.TTL))
	if err != nil {
		return "", trace.Wrap(err)
	}
	if err := s.Provisioner.UpsertToken(token); err != nil {
		return "", trace.Wrap(err)
	}
	return req.Token, nil
}
71592
func (c *LeaseCache) RegisterAutoAuthToken(token string) error {
	// Get the token from the cache
	oldIndex, err := c.db.Get(cachememdb.IndexNameToken, token)
	if err != nil {
		return err
	}

	// If the index is found, defer its cancelFunc
	if oldIndex != nil {
		defer oldIndex.RenewCtxInfo.CancelFunc()
	}

	// The following randomly generated values are required for index stored by
	// the cache, but are not actually used. We use random values to prevent
	// accidental access.
	id, err := base62.Random(5)
	if err != nil {
		return err
	}
	namespace, err := base62.Random(5)
	if err != nil {
		return err
	}
	requestPath, err := base62.Random(5)
	if err != nil {
		return err
	}

	index := &cachememdb.Index{
		ID:          id,
		Token:       token,
		Namespace:   namespace,
		RequestPath: requestPath,
	}

	// Derive a context off of the lease cache's base context
	ctxInfo := c.createCtxInfo(nil)

	index.RenewCtxInfo = &cachememdb.ContextInfo{
		Ctx:        ctxInfo.Ctx,
		CancelFunc: ctxInfo.CancelFunc,
		DoneCh:     ctxInfo.DoneCh,
	}

	// Store the index in the cache
	c.logger.Debug("storing auto-auth token into the cache")
	err = c.db.Set(index)
	if err != nil {
		c.logger.Error("failed to cache the auto-auth token", "error", err)
		return err
	}

	return nil
}