// ------ Outgoing Requests ---------- //
// GoogleAuth authenticates using the given Google OAuth token and retrieves a JWT token.
// This also announces availability to the server, so server can start sending us pending messages.
341427
func (c *Client) GoogleAuth(oauthToken string, handler func(jwtToken string) error) error {
	_, err := c.conn.SendRequest("auth.google", map[string]string{"token": oauthToken}, func(ctx *neptulon.ResCtx) error {
		var jwtToken map[string]string
		if err := ctx.Result(&jwtToken); err != nil {
			return fmt.Errorf("client: auth.google: error reading response: %v", err)
		}
		return handler(jwtToken["token"])
	})

	if err != nil {
		return fmt.Errorf("client: auth.google: error sending request: %v", err)
	}

	return nil
}
910607
func (a *OAuthStrategy) Refresh() error {
	refreshToken := a.RefreshToken()

	if refreshToken == "" {
		return a.requestToken()
	}

	var accessToken string
	var err error

	if a.ClientCredentialRefresh {
		accessToken, err = a.OAuthClient.ClientCredentialGrant(a.ClientId, a.ClientSecret)
	} else {
		accessToken, refreshToken, err = a.OAuthClient.RefreshTokenGrant(a.ClientId, a.ClientSecret, refreshToken)
	}

	if err != nil {
		if strings.Contains(err.Error(), "invalid_token") {
			return errors.New("You are not currently authenticated. Please log in to continue.")
		}
		return err
	}

	a.SetTokens(accessToken, refreshToken)

	return nil
}
274781
func (self *OauthAuthenticator) Callback(w http.ResponseWriter, req *http.Request) {
	sid := httputil.Q(req, `state`)
	code := httputil.Q(req, `code`)

	if sessionI, ok := oauthSessions.Load(sid); ok {
		if session, ok := sessionI.(*oauthSession); ok {
			if session.State == sid {
				if token, err := self.oauth2config.Exchange(oauth2.NoContext, code); err == nil {
					session.Code = code
					session.Token = token

					// give the client their session ID
					cookie := &http.Cookie{
						Name:     self.cookieName,
						Value:    session.State,
						Path:     `/`,
						Domain:   session.Domain,
						Secure:   (session.Scheme == `https`),
						HttpOnly: true,
						SameSite: http.SameSiteStrictMode,
					}

					log.Noticef("oauth token %v", token)

					if self.sessionDuration > 0 {
						cookie.Expires = time.Now().Add(self.sessionDuration)
					}

					http.SetCookie(w, cookie)
					http.Redirect(w, req, session.Path, http.StatusTemporaryRedirect)
				} else {
					http.Error(w, err.Error(), http.StatusBadRequest)
				}
			} else {
				http.Error(w, "Invalid OAuth2 session returned for callback", http.StatusBadRequest)
			}
		} else {
			http.Error(w, "Invalid OAuth2 session object", http.StatusBadRequest)
		}
	} else {
		http.Error(w, "OAuth2 session does not exist exists", http.StatusBadRequest)
	}
}
1169604
func (b *BearerJWT) Token(username string) (string, error) {
	if b.Now == nil {
		b.Now = time.Now
	}
	return JWT(username, b.SharedSecret, b.Now)
}
554405
func (fb *Firebase) Auth(token string) {
	fb.paramsMtx.Lock()
	fb.params.Set(authParam, token)
	fb.paramsMtx.Unlock()
}
148716
func (s Server) getClientAuth(w *Response, r *http.Request, allowQueryParams bool) *BasicAuth {

	if allowQueryParams {
		// Allow for auth without password
		if _, hasSecret := r.Form["client_secret"]; hasSecret {
			auth := &BasicAuth{
				Username: r.FormValue("client_id"),
				Password: r.FormValue("client_secret"),
			}
			if auth.Username != "" {
				return auth
			}
		}
	}

	auth, err := CheckBasicAuth(r)
	if err != nil {
		s.setErrorAndLog(w, E_INVALID_REQUEST, err, "get_client_auth=%s", "check auth error")
		return nil
	}
	if auth == nil {
		s.setErrorAndLog(w, E_INVALID_REQUEST, errors.New("Client authentication not sent"), "get_client_auth=%s", "client authentication not sent")
		return nil
	}
	return auth
}
548631
func (server *HTTPServer) GetUserAuthTokens(c *models.ReqContext) Response {
	return server.getUserAuthTokensInternal(c, c.UserId)
}
279028
func (ga *GoogleAuth) doGoogleAuthCreateToken(rw http.ResponseWriter, code string) {
	resp, err := ga.client.PostForm(
		"https://www.googleapis.com/oauth2/v3/token",
		url.Values{
			"code":          []string{string(code)},
			"client_id":     []string{ga.config.ClientId},
			"client_secret": []string{ga.config.ClientSecret},
			"redirect_uri":  []string{"postmessage"},
			"grant_type":    []string{"authorization_code"},
		})
	if err != nil {
		http.Error(rw, fmt.Sprintf("Error talking to Google auth backend: %s", err), http.StatusServiceUnavailable)
		return
	}
	codeResp, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	glog.V(2).Infof("Code to token resp: %s", strings.Replace(string(codeResp), "\n", " ", -1))

	var c2t CodeToTokenResponse
	err = json.Unmarshal(codeResp, &c2t)
	if err != nil || c2t.Error != "" || c2t.ErrorDescription != "" {
		var et string
		if err != nil {
			et = err.Error()
		} else {
			et = fmt.Sprintf("%s: %s", c2t.Error, c2t.ErrorDescription)
		}
		http.Error(rw, fmt.Sprintf("Failed to get token: %s", et), http.StatusBadRequest)
		return
	}

	if c2t.RefreshToken == "" {
		http.Error(rw, "Google did not return refresh token, please sign out and sign in again.", http.StatusBadRequest)
		return
	}

	if c2t.ExpiresIn < 60 {
		http.Error(rw, "New token is too short-lived", http.StatusInternalServerError)
		return
	}

	ti, err := ga.getIDTokenInfo(c2t.IDToken)
	if err != nil {
		glog.Errorf("Newly-acquired token is invalid: %+v %s", c2t, err)
		http.Error(rw, "Newly-acquired token is invalid", http.StatusInternalServerError)
		return
	}
	user := ti.Email

	glog.Infof("New Google auth token for %s (exp %d)", user, c2t.ExpiresIn)

	v := &TokenDBValue{
		TokenType:    c2t.TokenType,
		AccessToken:  c2t.AccessToken,
		RefreshToken: c2t.RefreshToken,
		ValidUntil:   time.Now().Add(time.Duration(c2t.ExpiresIn-30) * time.Second),
	}
	dp, err := ga.db.StoreToken(user, v, true)
	if err != nil {
		glog.Errorf("Failed to record server token: %s", err)
		http.Error(rw, "Failed to record server token: %s", http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(rw, `Server logged in; now run "docker login YOUR_REGISTRY_FQDN", use %s as login and %s as password.`, user, dp)
}
982084
func AuthUser(auth Auth) (Auth, error) {
	// TODO: Stop using package log, package httptest.
	config := &oauth.Config{
		ClientId:     auth.APIClientID,
		ClientSecret: auth.APIClientSecret,
		Scope:        "https://www.googleapis.com/auth/cloudprint https://www.googleapis.com/auth/googletalk",
		AuthURL:      "https://accounts.google.com/o/oauth2/auth",
		TokenURL:     "https://accounts.google.com/o/oauth2/token",
	}
	ch := make(chan string)
	randState, err := RandomID()
	if err != nil {
		return Auth{}, err
	}
	ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		if req.URL.Path == "/favicon.ico" {
			http.Error(rw, "", 404)
			return
		}
		if req.FormValue("state") != randState {
			log.Printf("State doesn't match: req = %#v", req)
			http.Error(rw, "", 500)
			return
		}
		if code := req.FormValue("code"); code != "" {
			fmt.Fprintf(rw, "<h1>Success</h1>Authorized.")
			rw.(http.Flusher).Flush()
			ch <- code
			return
		}
		log.Printf("no code")
		http.Error(rw, "", 500)
	}))
	defer ts.Close()

	config.RedirectURL = ts.URL
	authURL := config.AuthCodeURL(randState)
	go openURL(authURL)
	log.Printf("Authorize this app at: %s", authURL)
	code := <-ch
	log.Printf("Got code: %s", code)

	t := &oauth.Transport{
		Config:    config,
		Transport: http.DefaultTransport,
	}
	_, err = t.Exchange(code)
	if err != nil {
		log.Fatalf("Token exchange error: %v", err)
	}

	auth.Token = *t.Token
	return auth, nil
}
390777
func GetAuth(accessKey string, secretKey, token string, expiration time.Time) (auth Auth, err error) {
	// First try passed in credentials
	if accessKey != "" && secretKey != "" {
		return Auth{accessKey, secretKey, token, expiration}, nil
	}

	// Next try to get auth from the environment
	auth, err = EnvAuth()
	if err == nil {
		// Found auth, return
		return
	}

	err = fmt.Errorf("No valid KS3 authentication found: %s", err)
	return auth, err
}
434295
func (c *client) awaitingAuth() bool {
	return !c.flags.isSet(connectReceived) && c.atmr != nil
}
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)
}
350099
func (c *tokenSource) Token() (*oauth2.Token, error) {
	v := url.Values{
		"grant_type": {"client_credentials"},
	}
	if len(c.conf.Scopes) > 0 {
		v.Set("scope", strings.Join(c.conf.Scopes, " "))
	}
	for k, p := range c.conf.EndpointParams {
		// Allow grant_type to be overridden to allow interoperability with
		// non-compliant implementations.
		if _, ok := v[k]; ok && k != "grant_type" {
			return nil, fmt.Errorf("oauth2: cannot overwrite parameter %q", k)
		}
		v[k] = p
	}

	tk, err := internal.RetrieveToken(c.ctx, c.conf.ClientID, c.conf.ClientSecret, c.conf.TokenURL, v, internal.AuthStyle(c.conf.AuthStyle))
	if err != nil {
		if rErr, ok := err.(*internal.RetrieveError); ok {
			return nil, (*oauth2.RetrieveError)(rErr)
		}
		return nil, err
	}
	t := &oauth2.Token{
		AccessToken:  tk.AccessToken,
		TokenType:    tk.TokenType,
		RefreshToken: tk.RefreshToken,
		Expiry:       tk.Expiry,
	}
	return t.WithExtra(tk.Raw), nil
}
634659
func (m *GoogleOAuth2Method) Authenticate(c context.Context, r *http.Request) (user *User, err error) {
	cfg := getConfig(c)
	if cfg == nil || cfg.AnonymousTransport == nil {
		return nil, ErrNotConfigured
	}

	// Extract the access token from the Authorization header.
	header := r.Header.Get("Authorization")
	if header == "" || len(m.Scopes) == 0 {
		return nil, nil // this method is not applicable
	}
	accessToken, err := accessTokenFromHeader(header)
	if err != nil {
		return nil, err
	}

	// Store only the token hash in the cache, so that if a memory or cache dump
	// ever occurs, the tokens themselves aren't included in it.
	h := sha256.Sum256([]byte(accessToken))
	cacheKey := hex.EncodeToString(h[:])

	// Verify the token or grab a result of previous verification. We cache both
	// good and bad tokens. Note that bad token can't turn into good with passage
	// of time, so its OK to cache it.
	//
	// TODO(vadimsh): Strictly speaking we need to store bad tokens in a separate
	// cache, so a flood of bad tokens don't evict good tokens from the process
	// cache.
	cached, err := oauthChecksCache.GetOrCreate(c, cacheKey, func() (interface{}, time.Duration, error) {
		switch user, exp, err := m.authenticateAgainstGoogle(c, cfg, accessToken); {
		case transient.Tag.In(err):
			logging.WithError(err).Errorf(c, "oauth: Transient error when checking the token")
			return nil, 0, err
		case err != nil:
			// Cache the fact that the token is bad for 30 min. No need to recheck it
			// again just to find out it is (still) bad.
			logging.WithError(err).Errorf(c, "oauth: Caching bad access token SHA256=%q", cacheKey)
			return nil, 30 * time.Minute, nil
		default:
			return user, exp, nil
		}
	})

	switch {
	case err != nil:
		return nil, err // can only be a transient error
	case cached == nil:
		logging.Errorf(c, "oauth: Bad access token SHA256=%q", cacheKey)
		return nil, ErrBadOAuthToken
	}

	user = cached.(*User)
	return
}
1074486
func AuthHTTPRequest(req *http.Request, info *Info) error {
	var tag string
	if info.Tag != nil {
		tag = info.Tag.String()
	}
	return authHTTPRequest(req, tag, info.Password, info.Nonce, info.Macaroons)
}
1366505
func (c *Client) GetAuthServers() ([]services.Server, error) {
	out, err := c.Get(c.Endpoint("authservers"), url.Values{})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	var items []json.RawMessage
	if err := json.Unmarshal(out.Bytes(), &items); err != nil {
		return nil, trace.Wrap(err)
	}
	re := make([]services.Server, len(items))
	for i, raw := range items {
		server, err := services.GetServerMarshaler().UnmarshalServer(raw, services.KindAuthServer, services.SkipValidation())
		if err != nil {
			return nil, trace.Wrap(err)
		}
		re[i] = server
	}
	return re, nil
}
1330265
func (s *sdkGrpcServer) auth(ctx context.Context) (context.Context, error) {
	// Obtain token from metadata in the context
	token, err := grpc_auth.AuthFromMD(ctx, ContextMetadataTokenKey)
	if err != nil {
		return nil, err
	}

	// Determine issuer
	issuer, err := auth.TokenIssuer(token)
	if err != nil {
		return nil, status.Errorf(codes.PermissionDenied, "Unable to obtain issuer from token: %v", err)
	}

	// Authenticate user
	if authenticator, ok := s.config.Security.Authenticators[issuer]; ok {
		var claims *auth.Claims
		claims, err = authenticator.AuthenticateToken(ctx, token)
		if err == nil {
			// Add authorization information back into the context so that other
			// functions can get access to this information.
			// If this is in the context is how functions will know that security is enabled.
			ctx = auth.ContextSaveUserInfo(ctx, &auth.UserInfo{
				Username: authenticator.Username(claims),
				Claims:   *claims,
			})
			return ctx, nil
		} else {
			return nil, status.Error(codes.PermissionDenied, err.Error())
		}
	} else {
		return nil, status.Errorf(codes.PermissionDenied, "%s is not a trusted issuer", issuer)
	}
}