// ResolveToken is used to translate an ACL Token Secret ID into
// an ACL object, nil if ACLs are disabled, or an error.
517374
func (c *Client) ResolveToken(secretID string) (*acl.ACL, error) {
	// Fast-path if ACLs are disabled
	if !c.config.ACLEnabled {
		return nil, nil
	}
	defer metrics.MeasureSince([]string{"client", "acl", "resolve_token"}, time.Now())

	// Resolve the token value
	token, err := c.resolveTokenValue(secretID)
	if err != nil {
		return nil, err
	}
	if token == nil {
		return nil, structs.ErrTokenNotFound
	}

	// Check if this is a management token
	if token.Type == structs.ACLManagementToken {
		return acl.ManagementACL, nil
	}

	// Resolve the policies
	policies, err := c.resolvePolicies(token.SecretID, token.Policies)
	if err != nil {
		return nil, err
	}

	// Resolve the ACL object
	aclObj, err := structs.CompileACLObject(c.aclCache, policies)
	if err != nil {
		return nil, err
	}
	return aclObj, nil
}
768237
func (l *Lexer) NextToken() Token {
	for {
		//u.Debugf("token: start=%v  pos=%v  peek5=%s", l.start, l.pos, l.PeekX(5))
		select {
		case token := <-l.tokens:
			return token
		default:
			if l.state == nil && len(l.stack) > 0 {
				l.state = l.pop()
			} else if l.state == nil {
				return Token{T: TokenEOF, V: ""}
			}
			l.state = l.state(l)
		}
	}
}
446453
func (c *Client) RefreshToken(refreshToken string) (*Token, error) {
	params := make(url.Values)
	params.Set("grant_type", GrantTypeRefreshToken)
	params.Set("refresh_token", refreshToken)
	params.Set("scope", "")
	return c.grantToken(params)
}
268934
func (a *Account) BrokerToken(id string) (token string, err error) {
	return a.ComponentToken("broker", id)
}
888316
func (s *AuthServer) ValidateToken(token string) (roles teleport.Roles, e error) {
	tkns, err := s.GetCache().GetStaticTokens()
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// First check if the token is a static token. If it is, return right away.
	// Static tokens have no expiration.
	for _, st := range tkns.GetStaticTokens() {
		if st.GetName() == token {
			return st.GetRoles(), nil
		}
	}

	// If it's not a static token, check if it's a ephemeral token in the backend.
	// If a ephemeral token is found, make sure it's still valid.
	tok, err := s.GetCache().GetToken(token)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	if !s.checkTokenTTL(tok) {
		return nil, trace.AccessDenied("token expired")
	}

	return tok.GetRoles(), nil
}
1120142
func (s *DefaultCookieProtector) DecodeToken(p []byte) ([]byte, error) {
	if len(p) < cookieNonceSize {
		return nil, fmt.Errorf("Token too short: %d", len(p))
	}
	nonce := p[:cookieNonceSize]
	aead, aeadNonce, err := s.createAEAD(nonce)
	if err != nil {
		return nil, err
	}
	return aead.Open(nil, aeadNonce, p[cookieNonceSize:], nil)
}
1367996
func ParseAccessToken(reader io.ReadCloser) (*AccessToken, error) {
	body, err := ioutil.ReadAll(reader)
	reader.Close()
	if err != nil {
		return nil, err
	}

	return ParseAccessTokenStr(string(body))
}
1197003
func Token(ctx context.Context) *AuthorizationToken {
	v := ctx.Value(tokenIndex)
	if v == nil {
		return nil
	}
	return v.(*AuthorizationToken)
}
1300132
func (t *TokenProvider) GetToken(audience string) (*auth.Token, error) {
	token := t.tokenProvider.Token()
	expireTicks, err := strconv.ParseInt(string(token.ExpiresOn), 10, 64)
	if err != nil {
		return nil, err
	}
	expires := time.Unix(expireTicks, 0)

	if expires.Before(time.Now()) {
		if err := t.tokenProvider.Refresh(); err != nil {
			return nil, err
		}
		token = t.tokenProvider.Token()
	}

	return auth.NewToken(auth.CBSTokenTypeJWT, token.AccessToken, string(token.ExpiresOn)), nil
}
549095
func AuthToken(cloud environs.CloudSpec, sender autorest.Sender) (*adal.ServicePrincipalToken, error) {
	if authType := cloud.Credential.AuthType(); authType != clientCredentialsAuthType {
		// We currently only support a single auth-type for
		// non-interactive authentication. Interactive auth
		// is used only to generate a service-principal.
		return nil, errors.NotSupportedf("auth-type %q", authType)
	}

	resourceId, err := azureauth.ResourceManagerResourceId(cloud.StorageEndpoint)
	if err != nil {
		return nil, errors.Trace(err)
	}

	credAttrs := cloud.Credential.Attributes()
	subscriptionId := credAttrs[credAttrSubscriptionId]
	appId := credAttrs[credAttrAppId]
	appPassword := credAttrs[credAttrAppPassword]
	client := subscriptions.Client{subscriptions.NewWithBaseURI(cloud.Endpoint)}
	useragent.UpdateClient(&client.Client)
	client.Sender = sender
	sdkCtx := context.Background()
	oauthConfig, _, err := azureauth.OAuthConfig(sdkCtx, client, cloud.Endpoint, subscriptionId)
	if err != nil {
		return nil, errors.Trace(err)
	}

	token, err := adal.NewServicePrincipalToken(
		*oauthConfig,
		appId,
		appPassword,
		resourceId,
	)
	if err != nil {
		return nil, errors.Annotate(err, "constructing service principal token")
	}
	tokenClient := autorest.NewClientWithUserAgent("")
	useragent.UpdateClient(&tokenClient)
	tokenClient.Sender = sender
	token.SetSender(&tokenClient)
	return token, nil
}
1172764
func (i *InstallationToken) GetToken() string {
	if i == nil || i.Token == nil {
		return ""
	}
	return *i.Token
}
785123
func (c *Client) SetToken(v string) {
	c.modifyLock.Lock()
	defer c.modifyLock.Unlock()

	c.token = v
}
1219938
func signToken(secret []byte, token *AccessToken) (string, error) {
	t := accessTokenToJwt(token)
	return t.SignedString(secret)
}
1252271
func (c *UserConfig) parseRequestToken(response *http.Response) error {
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	params, err := url.ParseQuery(string(body))
	tokenKey := params.Get("oauth_token")
	tokenSecret := params.Get("oauth_token_secret")
	if tokenKey == "" || tokenSecret == "" {
		return fmt.Errorf("No token or secret found")
	}
	c.RequestTokenKey = tokenKey
	c.RequestTokenSecret = tokenSecret
	if params.Get("oauth_callback_confirmed") == "false" {
		return fmt.Errorf("OAuth callback not confirmed")
	}
	return nil
}
1059376
func CheckToken(c context.Context, params CheckTokenParams) (identity.Identity, error) {
	// base64-encoded token -> DelegationToken proto (with signed serialized
	// subtoken).
	tok, err := deserializeToken(params.Token)
	if err != nil {
		logging.Warningf(c, "auth: Failed to deserialize delegation token - %s", err)
		return "", ErrMalformedDelegationToken
	}

	// Signed serialized subtoken -> Subtoken proto.
	subtoken, err := unsealToken(c, tok, params.CertificatesProvider)
	if err != nil {
		if transient.Tag.In(err) {
			logging.Warningf(c, "auth: Transient error when checking delegation token signature - %s", err)
			return "", err
		}
		logging.Warningf(c, "auth: Failed to check delegation token signature - %s", err)
		return "", ErrUnsignedDelegationToken
	}

	// Validate all constrains encoded in the token and derive the delegated
	// identity.
	return checkSubtoken(c, subtoken, &params)
}
454279
func (a *ACL) UpsertTokens(args *structs.ACLTokenUpsertRequest, reply *structs.ACLTokenUpsertResponse) error {
	// Ensure ACLs are enabled, and always flow modification requests to the authoritative region
	if !a.srv.config.ACLEnabled {
		return aclDisabled
	}

	// Validate non-zero set of tokens
	if len(args.Tokens) == 0 {
		return fmt.Errorf("must specify as least one token")
	}

	// Force the request to the authoritative region if we are creating global tokens
	hasGlobal := false
	allGlobal := true
	for _, token := range args.Tokens {
		if token.Global {
			hasGlobal = true
		} else {
			allGlobal = false
		}
	}

	// Disallow mixed requests with global and non-global tokens since we forward
	// the entire request as a single batch.
	if hasGlobal {
		if !allGlobal {
			return fmt.Errorf("cannot upsert mixed global and non-global tokens")
		}

		// Force the request to the authoritative region if it has global
		args.Region = a.srv.config.AuthoritativeRegion
	}

	if done, err := a.srv.forward("ACL.UpsertTokens", args, args, reply); done {
		return err
	}
	defer metrics.MeasureSince([]string{"nomad", "acl", "upsert_tokens"}, time.Now())

	// Check management level permissions
	if acl, err := a.srv.ResolveToken(args.AuthToken); err != nil {
		return err
	} else if acl == nil || !acl.IsManagement() {
		return structs.ErrPermissionDenied
	}

	// Snapshot the state
	state, err := a.srv.State().Snapshot()
	if err != nil {
		return err
	}

	// Validate each token
	for idx, token := range args.Tokens {
		if err := token.Validate(); err != nil {
			return fmt.Errorf("token %d invalid: %v", idx, err)
		}

		// Generate an accessor and secret ID if new
		if token.AccessorID == "" {
			token.AccessorID = uuid.Generate()
			token.SecretID = uuid.Generate()
			token.CreateTime = time.Now().UTC()

		} else {
			// Verify the token exists
			out, err := state.ACLTokenByAccessorID(nil, token.AccessorID)
			if err != nil {
				return fmt.Errorf("token lookup failed: %v", err)
			}
			if out == nil {
				return fmt.Errorf("cannot find token %s", token.AccessorID)
			}

			// Cannot toggle the "Global" mode
			if token.Global != out.Global {
				return fmt.Errorf("cannot toggle global mode of %s", token.AccessorID)
			}
		}

		// Compute the token hash
		token.SetHash()
	}

	// Update via Raft
	_, index, err := a.srv.raftApply(structs.ACLTokenUpsertRequestType, args)
	if err != nil {
		return err
	}

	// Populate the response. We do a lookup against the state to
	// pickup the proper create / modify times.
	state, err = a.srv.State().Snapshot()
	if err != nil {
		return err
	}
	for _, token := range args.Tokens {
		out, err := state.ACLTokenByAccessorID(nil, token.AccessorID)
		if err != nil {
			return fmt.Errorf("token lookup failed: %v", err)
		}
		reply.Tokens = append(reply.Tokens, out)
	}

	// Update the index
	reply.Index = index
	return 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
}