// NewTokenVerification creates an instance of a TokenVerification
488751
func NewTokenVerification(response *http.Response) (*TokenVerification, error) {
	tokenVerification := &TokenVerification{HTTPResponse: response}
	body, err := ioutil.ReadAll(response.Body)

	if err != nil {
		Logger.Println("Error reading from API:", err)
		return tokenVerification, err
	}

	err = json.Unmarshal(body, &tokenVerification)
	if err != nil {
		Logger.Println("Error parsing JSON:", err)
		return tokenVerification, err
	}

	return tokenVerification, nil
}
561628
func newTokenBucket(rate *rate, clock timetools.TimeProvider) *tokenBucket {
	return &tokenBucket{
		period:          rate.period,
		timePerToken:    time.Duration(int64(rate.period) / rate.average),
		burst:           rate.burst,
		clock:           clock,
		lastRefresh:     clock.UtcNow(),
		availableTokens: rate.burst,
	}
}
113842
func ParseJWTIdentity(token string) (Identity, error) {
	claims := &jwtIdentity{}
	parsed, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
		// Validate the algorithm matches the key
		if _, ok := token.Method.(*jwt.SigningMethodRSAPSS); !ok {
			return nil, ErrInvalidSigningMethod
		}
		return GetMasterPublicKey()
	})
	if err != nil {
		if verr, ok := err.(*jwt.ValidationError); ok {
			if verr.Errors&jwt.ValidationErrorExpired != 0 {
				return nil, ErrIdentityTokenExpired
			}
			if verr.Errors&(jwt.ValidationErrorNotValidYet|jwt.ValidationErrorIssuedAt) != 0 {
				return nil, ErrIdentityTokenNotValidYet
			}
			if verr.Errors&(jwt.ValidationErrorSignatureInvalid|jwt.ValidationErrorUnverifiable) != 0 {
				return nil, ErrIdentityTokenBadSig
			}
			return nil, verr.Inner
		}
		return nil, err
	}
	if claims, ok := parsed.Claims.(*jwtIdentity); ok && parsed.Valid {
		return claims, nil
	}
	return nil, ErrIdentityTokenInvalid
}
417722
func NewTokenHandlerWithOptions(options TokenHandlerOptions) AuthenticationHandler {
	handler := &tokenHandler{
		transport:     options.Transport,
		creds:         options.Credentials,
		offlineAccess: options.OfflineAccess,
		forceOAuth:    options.ForceOAuth,
		clientID:      options.ClientID,
		scopes:        options.Scopes,
		clock:         realClock{},
		logger:        options.Logger,
	}

	return handler
}
978460
func NewTokenCleaner(cl clientset.Interface, secrets coreinformers.SecretInformer, options TokenCleanerOptions) (*TokenCleaner, error) {
	e := &TokenCleaner{
		client:               cl,
		secretLister:         secrets.Lister(),
		secretSynced:         secrets.Informer().HasSynced,
		tokenSecretNamespace: options.TokenSecretNamespace,
		queue:                workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "token_cleaner"),
	}

	if cl.CoreV1().RESTClient().GetRateLimiter() != nil {
		if err := metrics.RegisterMetricAndTrackRateLimiterUsage("token_cleaner", cl.CoreV1().RESTClient().GetRateLimiter()); err != nil {
			return nil, err
		}
	}

	secrets.Informer().AddEventHandlerWithResyncPeriod(
		cache.FilteringResourceEventHandler{
			FilterFunc: func(obj interface{}) bool {
				switch t := obj.(type) {
				case *v1.Secret:
					return t.Type == bootstrapapi.SecretTypeBootstrapToken && t.Namespace == e.tokenSecretNamespace
				default:
					utilruntime.HandleError(fmt.Errorf("object passed to %T that is not expected: %T", e, obj))
					return false
				}
			},
			Handler: cache.ResourceEventHandlerFuncs{
				AddFunc:    e.enqueueSecrets,
				UpdateFunc: func(oldSecret, newSecret interface{}) { e.enqueueSecrets(newSecret) },
			},
		},
		options.SecretResync,
	)

	return e, nil
}
666660
func (n *Tokenize) NewToken(start, end int) *Token {
  return &Token { n, start, end }
}
846733
func NewTokenStore(ctx context.Context, logger log.Logger, core *Core, config *logical.BackendConfig) (*TokenStore, error) {
	// Create a sub-view
	view := core.systemBarrierView.SubView(tokenSubPath)

	// Initialize the store
	t := &TokenStore{
		activeContext:         ctx,
		core:                  core,
		batchTokenEncryptor:   core.barrier,
		baseBarrierView:       view,
		idBarrierView:         view.SubView(idPrefix),
		accessorBarrierView:   view.SubView(accessorPrefix),
		parentBarrierView:     view.SubView(parentPrefix),
		rolesBarrierView:      view.SubView(rolesPrefix),
		cubbyholeDestroyer:    destroyCubbyhole,
		logger:                logger,
		tokenLocks:            locksutil.CreateLocks(),
		tokensPendingDeletion: &sync.Map{},
		saltLock:              sync.RWMutex{},
		tidyLock:              new(uint32),
		quitContext:           core.activeContext,
		salts:                 make(map[string]*salt.Salt),
	}

	// Setup the framework endpoints
	t.Backend = &framework.Backend{
		AuthRenew: t.authRenew,

		PathsSpecial: &logical.Paths{
			Root: []string{
				"revoke-orphan/*",
				"accessors*",
			},

			// Most token store items are local since tokens are local, but a
			// notable exception is roles
			LocalStorage: []string{
				idPrefix,
				accessorPrefix,
				parentPrefix,
				salt.DefaultLocation,
			},
		},
		BackendType: logical.TypeCredential,
	}

	t.Backend.Paths = append(t.Backend.Paths, t.paths()...)

	t.Backend.Setup(ctx, config)

	return t, nil
}
1069929
func NewTokenizer(r io.Reader) (*Tokenizer, error) {
	input := bufio.NewReader(r)
	classifier := NewDefaultClassifier()
	tokenizer := &Tokenizer{
		input:      input,
		classifier: classifier}
	return tokenizer, nil
}
1189475
func NewToken(t TokenType, word []rune, pos Position) *Token {
	// ensure the type is valid
	if t < ILLEGAL || t > BAD {
		t = BAD
	}

	// return the token
	return &Token{Type: t, Word: word, Position: pos}
}
780966
func BenchmarkVerification(b *testing.B, priv crypto.PrivKey) {
	pub := priv.PubKey()
	// use a short message, so this time doesn't get dominated by hashing.
	message := []byte("Hello, world!")
	signature, err := priv.Sign(message)
	if err != nil {
		b.Fatal(err)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		pub.VerifyBytes(message, signature)
	}
}
1247382
func (s *VerifyDomainIdentityOutput) SetVerificationToken(v string) *VerifyDomainIdentityOutput {
	s.VerificationToken = &v
	return s
}
698868
func NewTokenGenerator(s string, err error) TokenGenerator {
	return TokenGenerator{
		TokenFn: func() (string, error) {
			return s, err
		},
	}
}
886648
func newTokenManager(expiredAfter time.Duration, dht *DHT) *tokenManager {
	return &tokenManager{
		syncedMap:    newSyncedMap(),
		expiredAfter: expiredAfter,
		dht:          dht,
	}
}
1155119
func NewTokenStreamWith(input *util.AttributeSource) *TokenStreamImpl {
	return &TokenStreamImpl{
		atts: util.NewAttributeSourceFrom(input),
	}
}
426071
func verifyToken() error {
	// get the token
	tokData, err := loadData(*flagVerify)
	if err != nil {
		return fmt.Errorf("Couldn't read token: %v", err)
	}

	// trim possible whitespace from token
	tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
	if *flagDebug {
		fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
	}

	// Parse the token.  Load the key from command line option
	token, err := jwt.Parse(string(tokData), func(t *jwt.Token) (interface{}, error) {
		data, err := loadData(*flagKey)
		if err != nil {
			return nil, err
		}
		if isEs() {
			return jwt.ParseECPublicKeyFromPEM(data)
		} else if isRs() {
			return jwt.ParseRSAPublicKeyFromPEM(data)
		}
		return data, nil
	})

	// Print some debug data
	if *flagDebug && token != nil {
		fmt.Fprintf(os.Stderr, "Header:\n%v\n", token.Header)
		fmt.Fprintf(os.Stderr, "Claims:\n%v\n", token.Claims)
	}

	// Print an error if we can't parse for some reason
	if err != nil {
		return fmt.Errorf("Couldn't parse token: %v", err)
	}

	// Is token invalid?
	if !token.Valid {
		return fmt.Errorf("Token is invalid")
	}

	// Print the token details
	if err := printJSON(token.Claims); err != nil {
		return fmt.Errorf("Failed to output claims: %v", err)
	}

	return nil
}
775607
func newVerifyHandler(token string) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.FormValue("hub.verify_token") == token {
			fmt.Fprintln(w, r.FormValue("hub.challenge"))
			return
		}
		fmt.Fprintln(w, "Incorrect verify token.")
	}
}
1161121
func (o *OIDCAuthenticator) AuthenticateToken(ctx context.Context, rawtoken string) (*Claims, error) {
	idToken, err := o.verifier.Verify(ctx, rawtoken)
	if err != nil {
		return nil, fmt.Errorf("Token failed validation: %v", err)
	}

	// Check for required claims
	var claims map[string]interface{}
	if err := idToken.Claims(&claims); err != nil {
		return nil, fmt.Errorf("Unable to get claim map from token: %v", err)
	}
	for _, requiredClaim := range requiredClaims {
		if _, ok := claims[requiredClaim]; !ok {
			// Claim missing
			return nil, fmt.Errorf("Required claim %v missing from token", requiredClaim)
		}
	}

	return o.parseClaims(claims)
}