// ByToken returns an authenticated user if the given token is valid for the
// given user id. Tokens are used for API access.
175477
func (auth *Auth) ByToken(id int64, key string) (user User) {
	// Do not query the database directly for the token key because that could
	// leak information through a timing attack - B-trees, yo
	for _, token := range auth.tokens.All(id) {
		if len(key) != len(token.Key) {
			continue
		}
		if subtle.ConstantTimeCompare([]byte(key), []byte(token.Key)) != 1 {
			continue
		}
		// Expires is optional, check if it exists before checking if expired
		if token.Expires != nil && token.Expires.After(auth.now()) {
			continue
		}
		user, _ = auth.users.GetByID(token.UserID)
		break
	}
	return
}
785123
func (c *Client) SetToken(v string) {
	c.modifyLock.Lock()
	defer c.modifyLock.Unlock()

	c.token = v
}
146293
func (auth *Auth) BySession(key string) (user User) {
	session := auth.sessions.Get(key)
	if !session.Exists() {
		return
	}
	if !session.Expires.After(auth.now()) {
		return
	}
	user, _ = auth.users.GetByID(session.UserID)
	return
}
295489
func (st *State) RemoteApplicationByToken(token string) (_ *RemoteApplication, err error) {
	apps, closer := st.db().GetCollection(remoteApplicationsC)
	defer closer()

	appDoc := &remoteApplicationDoc{}
	err = apps.Find(bson.D{{"token", token}}).One(appDoc)
	if err == mgo.ErrNotFound {
		return nil, errors.NotFoundf("remote application with token %q", token)
	}
	if err != nil {
		return nil, errors.Annotatef(err, "cannot get remote application with token %q", token)
	}
	return newRemoteApplication(st, appDoc), nil
}
770433
func SetToken(token string, req *http.Request) {
	req.Header.Set("Authorization", fmt.Sprintf("%s%s", tokenScheme, 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)
}
433045
func (authHandler *unionAuthTokenHandler) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) {
	var errlist []error
	for _, currAuthRequestHandler := range authHandler.Handlers {
		info, ok, err := currAuthRequestHandler.AuthenticateToken(ctx, token)
		if err != nil {
			if authHandler.FailOnError {
				return info, ok, err
			}
			errlist = append(errlist, err)
			continue
		}

		if ok {
			return info, ok, err
		}
	}

	return nil, false, utilerrors.NewAggregate(errlist)
}
112894
func (o *IntrospectOAuth2TokenParams) WithToken(token string) *IntrospectOAuth2TokenParams {
	o.SetToken(token)
	return o
}
363790
func (t *TokenSource) Token() (*oauth2.Token, error) {
	token := &oauth2.Token{
		AccessToken: t.AccessToken,
	}
	return token, nil
}
55309
func (c *csrf) ValidToken(t string) bool {
	return xsrftoken.Valid(t, c.Secret, c.ID, "POST")
}
578045
func (spt *ServicePrincipalToken) OAuthToken() string {
	spt.refreshLock.RLock()
	defer spt.refreshLock.RUnlock()
	return spt.inner.Token.OAuthToken()
}
960887
func HasAuthorizedToken(auth oauth2.Authenticator, r *http.Request) (oauth2.Principal, error) {
	ctx := r.Context()
	return auth.Validate(ctx, r)
}
753055
func (w *WebhookTokenAuthenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) {
	// We take implicit audiences of the API server at WebhookTokenAuthenticator
	// construction time. The outline of how we validate audience here is:
	//
	// * if the ctx is not audience limited, don't do any audience validation.
	// * if ctx is audience-limited, add the audiences to the tokenreview spec
	//   * if the tokenreview returns with audiences in the status that intersect
	//     with the audiences in the ctx, copy into the response and return success
	//   * if the tokenreview returns without an audience in the status, ensure
	//     the ctx audiences intersect with the implicit audiences, and set the
	//     intersection in the response.
	//   * otherwise return unauthenticated.
	wantAuds, checkAuds := authenticator.AudiencesFrom(ctx)
	r := &authentication.TokenReview{
		Spec: authentication.TokenReviewSpec{
			Token:     token,
			Audiences: wantAuds,
		},
	}
	var (
		result *authentication.TokenReview
		err    error
		auds   authenticator.Audiences
	)
	webhook.WithExponentialBackoff(w.initialBackoff, func() error {
		result, err = w.tokenReview.Create(r)
		return err
	})
	if err != nil {
		// An error here indicates bad configuration or an outage. Log for debugging.
		klog.Errorf("Failed to make webhook authenticator request: %v", err)
		return nil, false, err
	}

	if checkAuds {
		gotAuds := w.implicitAuds
		if len(result.Status.Audiences) > 0 {
			gotAuds = result.Status.Audiences
		}
		auds = wantAuds.Intersect(gotAuds)
		if len(auds) == 0 {
			return nil, false, nil
		}
	}

	r.Status = result.Status
	if !r.Status.Authenticated {
		var err error
		if len(r.Status.Error) != 0 {
			err = errors.New(r.Status.Error)
		}
		return nil, false, err
	}

	var extra map[string][]string
	if r.Status.User.Extra != nil {
		extra = map[string][]string{}
		for k, v := range r.Status.User.Extra {
			extra[k] = v
		}
	}

	return &authenticator.Response{
		User: &user.DefaultInfo{
			Name:   r.Status.User.Username,
			UID:    r.Status.User.UID,
			Groups: r.Status.User.Groups,
			Extra:  extra,
		},
		Audiences: auds,
	}, true, nil
}
412520
func (c *Config) PasswordCredentialsToken(username, password string) (*oauth2.Token, error) {
	config := c.getConfig()
	token, err := config.PasswordCredentialsToken(c.getContext(), username, password)
	return token, fromError(err)
}
223952
func (t AccessToken) Token() *adal.Token {
	return &adal.Token{
		AccessToken: t.AccessToken,
		Type:        t.TokenType,
	}
}
1060527
func GetToken(ctx context.Context) (string, error) {
	a, ok := ctx.Value(authorizerCtxKey).(platform.Authorizer)
	if !ok {
		return "", &platform.Error{
			Msg:  "authorizer not found on context",
			Code: platform.EInternal,
		}
	}

	auth, ok := a.(*platform.Authorization)
	if !ok {
		return "", &platform.Error{
			Msg:  fmt.Sprintf("authorizer not an authorization but a %T", a),
			Code: platform.EInternal,
		}
	}

	return auth.Token, nil
}
389041
func (s *FileSystemAPIServer) validateToken(t string) (string, error) {
	var tData TokenRef
	var aData AcctPayLoad
	var tDataByte []byte
	var aDataByte []byte
	var err error

	// Read Token
	pKeyA, pKeyB := murmur3.Sum128([]byte("/token"))
	cKeyA, cKeyB := murmur3.Sum128([]byte(t))
	_, tDataByte, err = s.gstore.Read(context.Background(), pKeyA, pKeyB, cKeyA, cKeyB, nil)
	if store.IsNotFound(err) {
		return "", errors.New("Not Found")
	}
	err = json.Unmarshal(tDataByte, &tData)
	if err != nil {
		log.Printf("TOKEN FAILED %v\n", err)
		return "", err
	}

	// Read Account
	pKeyA, pKeyB = murmur3.Sum128([]byte("/acct"))
	cKeyA, cKeyB = murmur3.Sum128([]byte(tData.AcctID))
	_, aDataByte, err = s.gstore.Read(context.Background(), pKeyA, pKeyB, cKeyA, cKeyB, nil)
	if store.IsNotFound(err) {
		return "", errors.New("Not Found")
	}
	err = json.Unmarshal(aDataByte, &aData)
	if err != nil {
		log.Printf("TOKEN FAILED %v\n", err)
		return "", err
	}

	if tData.TokenID != aData.Token {
		// Log Failed Operation
		log.Printf("TOKEN FAIL %s\n", t)
		return "", errors.New("Invalid Token")
	}

	// Return Account UUID
	// Log Operation
	log.Printf("TOKEN SUCCESS %s\n", tData.AcctID)
	return tData.AcctID, nil
}