// Exchanges the verifier for an OAuth2 Access Token.
772936
func (self *OAuth2Mixin) GetAccessToken(r *http.Request) (*oauth2.Token, error) {

	code := r.URL.Query().Get("code")
	if len(code) == 0 {
		return nil, errors.New("No Access Code in the Request URL")
	}

	accessToken, err := self.Client.GrantToken(code)
	if err != nil {
		return nil, err
	}

	return accessToken, err
}
959893
func (s *Secret) TokenAccessor() (string, error) {
	if s == nil {
		return "", nil
	}

	if s.Auth != nil && len(s.Auth.Accessor) > 0 {
		return s.Auth.Accessor, nil
	}

	if s.Data == nil || s.Data["accessor"] == nil {
		return "", nil
	}

	accessor, ok := s.Data["accessor"].(string)
	if !ok {
		return "", fmt.Errorf("token found but in the wrong format")
	}

	return accessor, nil
}
527086
func (c *Config) ExchangeAppKeyForToken(appID, accessKey string) (*oauth2.Token, error) {
	// application Access Token
	config := c.getKeyConfig()

	token, err := getTokenFromCache(c.cache, appID, accessKey)
	if err != nil {
		return nil, err
	}

	if token != nil {
		return token, nil
	}

	token, err = config.PasswordCredentialsToken(c.getContext(), appID, accessKey)
	if err != nil {
		return nil, fromError(err)
	}

	// ignore errors when saving to cache
	_ = saveTokenToCache(c.cache, appID, accessKey, token)

	return token, nil
}
257051
func (ctx *Context) GetAuthrAccessToken(appid string) (string, error) {
	authrTokenKey := "authorizer_access_token_" + appid
	val := ctx.Cache.Get(authrTokenKey)
	if val == nil {
		return "", fmt.Errorf("cannot get authorizer %s access token", appid)
	}
	return val.(string), nil
}
698446
func NewOauth2Client(clientID, label, callbackURL string, clientCredentialsGrantType bool) *Oauth2Client {
	c := &Oauth2Client{
		ClientID:                   clientID,
		Label:                      label,
		CallbackURL:                callbackURL,
		ClientCredentialsGrantType: clientCredentialsGrantType,
	}

	randombytes := make([]byte, 39) //Multiple of 3 to make sure no padding is added
	rand.Read(randombytes)
	c.Secret = base64.URLEncoding.EncodeToString(randombytes)
	return c
}
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
}
245500
func (a *authenticator) validateToken(token *jwt.Token, url, method string) error {
	var userName string
	// Read audience from the token
	switch v := token.Claims.(type) {
	case jwt.MapClaims:
		var ok bool
		if userName, ok = v["aud"].(string); !ok {
			return fmt.Errorf("failed to validate token claims audience")
		}
	case jwt.StandardClaims:
		userName = v.Audience
	default:
		return fmt.Errorf("failed to validate token claims")
	}
	loggedOut, err := a.userDb.IsLoggedOut(userName)
	if err != nil {
		return fmt.Errorf("failed to validate token: %v", err)
	}
	if loggedOut {
		// User logged out
		token.Valid = false
		return fmt.Errorf("invalid token")
	}
	user, err := a.userDb.GetUser(userName)
	if err != nil {
		return fmt.Errorf("failed to validate token: %v", err)
	}
	// Do not check for permissions if user is admin
	if userIsAdmin(user) {
		return nil
	}
	perms := a.getPermissionsForURL(url, method)
	for _, userPerm := range user.Permissions {
		for _, perm := range perms {
			if userPerm == perm {
				return nil
			}
		}
	}

	return fmt.Errorf("not permitted")
}
133784
func (k *Kite) AuthenticateFromToken(r *Request) error {
	k.verifyOnce.Do(k.verifyInit)

	token, err := jwt.ParseWithClaims(r.Auth.Key, &kitekey.KiteClaims{}, r.LocalKite.RSAKey)

	if e, ok := err.(*jwt.ValidationError); ok {
		// Translate public key mismatch errors to token-is-expired one.
		// This is to signal remote client the key pairs have been
		// updated on kontrol and it should invalidate all tokens.
		if (e.Errors & jwt.ValidationErrorSignatureInvalid) != 0 {
			return errors.New("token is expired")
		}
	}

	if err != nil {
		return err
	}

	if !token.Valid {
		return errors.New("Invalid signature in token")
	}

	claims, ok := token.Claims.(*kitekey.KiteClaims)
	if !ok {
		return errors.New("token does not have valid claims")
	}

	if claims.Audience == "" {
		return errors.New("token has no audience")
	}

	if claims.Subject == "" {
		return errors.New("token has no username")
	}

	// check if we have an audience and it matches our own signature
	if err := k.verifyAudienceFunc(k.Kite(), claims.Audience); err != nil {
		return err
	}

	// We don't check for exp and nbf claims here because jwt-go package
	// already checks them.

	// replace the requester username so we reflect the validated
	r.Username = claims.Subject

	return nil
}
1296360
func (p *Provider) Verifier(config *Config) *IDTokenVerifier {
	return NewVerifier(p.issuer, p.remoteKeySet, config)
}
620390
func (a *auther) setAccessTokenAuthHeader(req *http.Request, requestToken, requestSecret, verifier string) error {
	oauthParams := a.commonOAuthParams()
	oauthParams[oauthTokenParam] = requestToken
	oauthParams[oauthVerifierParam] = verifier
	params, err := collectParameters(req, oauthParams)
	if err != nil {
		return err
	}
	signatureBase := signatureBase(req, params)
	signature, err := a.signer().Sign(requestSecret, signatureBase)
	if err != nil {
		return err
	}
	oauthParams[oauthSignatureParam] = signature
	req.Header.Set(authorizationHeaderParam, authHeaderValue(oauthParams))
	return nil
}
246748
func (u UAA) Exchange(authCode string) (Token, error) {
	return u.ExchangeCommand(u, authCode)
}
1351666
func NewECDSAVerifier() Verifier {
	return verifyFn(func(checksum, signature []byte, hash crypto.Hash, publicKey crypto.PublicKey) error {
		key, ok := publicKey.(*ecdsa.PublicKey)
		if !ok {
			return errors.New("not a valid ECDSA public key")
		}
		var rs rsDER
		if _, err := asn1.Unmarshal(signature, &rs); err != nil {
			return err
		}
		if !ecdsa.Verify(key, checksum, rs.R, rs.S) {
			return errors.New("failed to verify ecsda signature")
		}
		return nil
	})
}
164155
func (self *GoogleProvider) GetAuthenticatedUser(w http.ResponseWriter, r *http.Request) (User, Token, error) {
	// Get the OAuth2 Access Token
	token, err := self.GetAccessToken(r)
	if err != nil {
		return nil, nil, err
	}

	user := GoogleUser{}
	err = self.OAuth2Mixin.GetAuthenticatedUser("https://www.googleapis.com/oauth2/v2/userinfo", token.AccessToken, &user)
	return &user, token, err
}
379653
func (v *TokenVerifier) Callback(r *http.Request) (string, string, int, error) {

	// We first validate that the callback state matches the original redirect
	// state. We clean up the cache once it is validated. During this process
	// we recover the original URL that initiated the protocol. This allows
	// us to redirect the client to their original request.
	receivedState := r.URL.Query().Get("state")
	originURL, err := stateCache.Get(receivedState)
	if err != nil {
		return "", "", http.StatusBadRequest, fmt.Errorf("bad state")
	}
	stateCache.Remove(receivedState)

	// We exchange the authorization code with an OAUTH token. This is the main
	// step where the OAUTH provider will match the code to the token.
	oauth2Token, err := v.clientConfig.Exchange(r.Context(), r.URL.Query().Get("code"), oauth2.AccessTypeOffline)
	if err != nil {
		return "", "", http.StatusInternalServerError, fmt.Errorf("bad code: %s", err)
	}

	// We extract the rawID token.
	rawIDToken, ok := oauth2Token.Extra("id_token").(string)
	if !ok {
		return "", "", http.StatusInternalServerError, fmt.Errorf("bad ID")
	}

	if err := tokenCache.SetWithExpire(
		rawIDToken,
		&clientData{
			tokenSource: v.clientConfig.TokenSource(context.Background(), oauth2Token),
			expiry:      oauth2Token.Expiry,
		},
		time.Until(oauth2Token.Expiry.Add(3600*time.Second)),
	); err != nil {
		return "", "", http.StatusInternalServerError, fmt.Errorf("failed to insert token in the cache: %s", err)
	}

	return rawIDToken, originURL.(string), http.StatusTemporaryRedirect, nil
}
1174835
func GoogleToken(file, clientID, clientSecret, scope string) (*oauth.Transport, error) {
	cfg := &oauth.Config{
		ClientId:     clientID,
		ClientSecret: clientSecret,
		Scope:        scope,
		AuthURL:      "https://accounts.google.com/o/oauth2/auth",
		TokenURL:     "https://accounts.google.com/o/oauth2/token",
	}
	return Token(file, cfg)
}
1270999
func NewAuthenticator(subscriptionKey, authURL string) _http.Authenticator {
	// make buffered accessToken channel and pre-fill it with an expired token
	tokenChan := make(chan *accessToken, 1)
	tokenChan <- new(accessToken)

	// return new authenticator that uses the above accessToken channel
	return &authenticator{
		accessTokenProvider: newAccessTokenProvider(subscriptionKey, authURL),
		accessTokenChan:     tokenChan,
	}
}
689165
func (a *cachedTokenAuthenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) {
	auds, _ := authenticator.AudiencesFrom(ctx)

	key := keyFunc(auds, token)
	if record, ok := a.cache.get(key); ok {
		return record.resp, record.ok, record.err
	}

	resp, ok, err := a.authenticator.AuthenticateToken(ctx, token)
	if !a.cacheErrs && err != nil {
		return resp, ok, err
	}

	switch {
	case ok && a.successTTL > 0:
		a.cache.set(key, &cacheRecord{resp: resp, ok: ok, err: err}, a.successTTL)
	case !ok && a.failureTTL > 0:
		a.cache.set(key, &cacheRecord{resp: resp, ok: ok, err: err}, a.failureTTL)
	}

	return resp, ok, err
}