// Make request with the given basic auth and ssl settings, returns reponse code and body as a byte array
167427
func (client Client) MakeRequest(method, path string, requestBody io.Reader) (int, []byte, error) {
	url := client.Host + path
	request, err := http.NewRequest(method, url, requestBody)
	if err != nil {
		return 0, nil, err
	}
	if client.BasicAuthUsername != "" {
		request.SetBasicAuth(client.BasicAuthUsername, client.BasicAuthPassword)
	} else {
		request.Header.Set("Authorization", "Bearer "+client.AccessToken)
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	httpClient := GetClient(client)
	response, err := httpClient.Do(request)
	if err != nil {
		return 0, nil, err
	}

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return response.StatusCode, body, err
	}

	return response.StatusCode, body, nil
}
386136
func createRequest() *http.Request {
	// Create HTTP request
	req := &http.Request{
		Method:     "GET",
		URL:        &url.URL{},
		Host:       "",
		ProtoMajor: 1,
		ProtoMinor: 1,
		Proto:      "HTTP/1.1",
		Header:     make(http.Header),
		Body:       utils.NopCloser(),
	}
	// Return shallow copy of Request with the new context
	return req.WithContext(emptyContext())
}
872583
func (r *request) toHTTP() (*http.Request, error) {
	// Encode the query parameters
	r.url.RawQuery = r.params.Encode()

	// Get the url sring
	urlRaw := r.url.String()

	// Check if we should encode the body
	if r.body == nil && r.obj != nil {
		if b, err := encodeBody(r.obj); err != nil {
			return nil, err
		} else {
			r.body = b
		}
	}

	// Create the HTTP request
	req, err := http.NewRequest(r.method, urlRaw, r.body)

	// Setup auth
	if err == nil && r.config.HttpAuth != nil {
		req.SetBasicAuth(r.config.HttpAuth.Username, r.config.HttpAuth.Password)
	}

	return req, err
}
373512
func (s *AuthorizationsService) Create(ctx context.Context, auth *AuthorizationRequest) (*Authorization, *Response, error) {
	u := "authorizations"

	req, err := s.client.NewRequest("POST", u, auth)
	if err != nil {
		return nil, nil, err
	}

	a := new(Authorization)
	resp, err := s.client.Do(ctx, req, a)
	if err != nil {
		return nil, resp, err
	}
	return a, resp, nil
}
1304833
func (connection *PluginConnection) Make(request *http.Request, passedResponse *Response, proxyReader ProxyReader) error {
	// In case this function is called from a retry, passedResponse may already
	// be populated with a previous response. We reset in case there's an HTTP
	// error and we don't repopulate it in populateResponse.
	passedResponse.reset()

	response, err := connection.HTTPClient.Do(request)
	if err != nil {
		return connection.processRequestErrors(request, err)
	}

	body := response.Body
	if proxyReader != nil {
		proxyReader.Start(response.ContentLength)
		defer proxyReader.Finish()
		body = proxyReader.Wrap(response.Body)
	}

	return connection.populateResponse(response, passedResponse, body)
}
295571
func (api *APIClient) makeAPIRequest(ctx context.Context, verb, url string, body io.Reader, headers map[string]string, userIdentifier string) (*http.Response, error) {
	req, err := http.NewRequest(verb, url, body)
	if err != nil {
		return nil, fmt.Errorf("failed to create HTTP request: %s", err)
	}

	if _, ok := headers["Accept"]; !ok {
		req.Header.Add("Accept", fmt.Sprintf("application/vnd.gini.%s+json", api.Config.APIVersion))
	}

	req.Header.Add("User-Agent", fmt.Sprintf("gini-api-go/%s", VERSION))

	if reflect.TypeOf(api.Config.Authentication).Name() == "BasicAuth" {
		if userIdentifier == "" {
			return nil, fmt.Errorf("userIdentifier required (Authentication=BasicAuth)")
		}
		req.Header.Add("X-User-Identifier", userIdentifier)
	}

	// Append additional headers
	for h, v := range headers {
		req.Header.Add(h, v)
	}

	// Add context to request
	req = req.WithContext(ctx)

	resp, err := api.HTTPClient.Do(req)

	return resp, err
}
1135214
func (connection *UAAConnection) Make(request *http.Request, passedResponse *Response) error {
	// In case this function is called from a retry, passedResponse may already
	// be populated with a previous response. We reset in case there's an HTTP
	// error and we don't repopulate it in populateResponse.
	passedResponse.reset()

	response, err := connection.HTTPClient.Do(request)
	if err != nil {
		return connection.processRequestErrors(request, err)
	}

	return connection.populateResponse(response, passedResponse)
}
806392
func (s *Secret) Create() (*Secret, *http.Response, []error) {
	k := kumoru.New()

	k.Post(fmt.Sprintf("%v/v1/secrets/", k.EndPoint.Authorization))
	k.Send(genParameters(s.Value, s.Labels))
	k.SignRequest(true)

	resp, body, errs := k.End()

	if errs != nil {
		return s, resp, errs
	}

	err := json.Unmarshal([]byte(body), &s)

	if err != nil {
		errs = append(errs, err)
		return s, resp, errs
	}

	return s, resp, nil
}
187211
func BasicAuth(req *http.Request) (username, password string, err error) {
	auth := req.Header.Get("Authorization")
	if auth == "" {
		err = fmt.Errorf("Missing \"Authorization\" in header")
		return
	}
	matches := kBasicAuthPattern.FindStringSubmatch(auth)
	if len(matches) != 2 {
		err = fmt.Errorf("Bogus Authorization header")
		return
	}
	encoded := matches[1]
	enc := base64.StdEncoding
	decBuf := make([]byte, enc.DecodedLen(len(encoded)))
	n, err := enc.Decode(decBuf, []byte(encoded))
	if err != nil {
		return
	}
	pieces := strings.SplitN(string(decBuf[0:n]), ":", 2)
	if len(pieces) != 2 {
		err = fmt.Errorf("didn't get two pieces")
		return
	}
	return pieces[0], pieces[1], nil
}
766809
func BasicAuth(user, pass string) RequestOption {
	return func(req *http.Request) error {
		req.SetBasicAuth(user, pass)
		return nil
	}
}
388457
func (ba *BasicAuth) AddAuthHeaders(req *http.Request) {
	authString := []byte(ba.Username + ":" + ba.Password)
	header := "Basic " + base64.StdEncoding.EncodeToString(authString)
	req.Header.Set("Authorization", string(header))
}
1213419
func (t *UAAAuthentication) Make(request *cloudcontroller.Request, passedResponse *cloudcontroller.Response) error {
	if t.client == nil {
		return t.connection.Make(request, passedResponse)
	}

	if t.cache.AccessToken() != "" || t.cache.RefreshToken() != "" {
		// assert a valid access token for authenticated requests
		err := t.refreshToken()
		if nil != err {
			return err
		}
		request.Header.Set("Authorization", t.cache.AccessToken())
	}

	err := t.connection.Make(request, passedResponse)
	return err
}
644099
func (r *request) toHTTP() (*http.Request, error) {
	// Encode the query parameters
	r.url.RawQuery = r.params.Encode()

	// Check if we should encode the body
	if r.body == nil && r.obj != nil {
		b, err := encodeBody(r.obj)
		if err != nil {
			return nil, err
		}
		r.body = b
	}

	// Create the HTTP request
	req, err := http.NewRequest(r.method, r.url.RequestURI(), r.body)
	if err != nil {
		return nil, err
	}

	req.URL.Host = r.url.Host
	req.URL.Scheme = r.url.Scheme
	req.Host = r.url.Host
	req.Header = r.header

	// Setup auth
	if r.config.HttpAuth != nil {
		req.SetBasicAuth(r.config.HttpAuth.Username, r.config.HttpAuth.Password)
	}
	if r.ctx != nil {
		return req.WithContext(r.ctx), nil
	}

	return req, nil
}
970945
func (srv *server) request(jsonData []byte, target string) ([]byte, error) {
	result, err := srv.getResultMap(jsonData, target)
	if err != nil {
		return nil, err
	}
	cert := result["certificate"].(string)
	if cert != "" {
		return []byte(cert), nil
	}

	return nil, errors.Wrap(errors.APIClientError, errors.ClientHTTPError, stderr.New("response doesn't contain certificate."))
}
931878
func main() {
	ws := new(restful.WebService)
	ws.Route(ws.GET("/secret").Filter(basicAuthenticate).To(secret))
	restful.Add(ws)
	log.Fatal(http.ListenAndServe(":8080", nil))
}
1344265
func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "index.html")
	})

	//When asked to log in, generate a unique state and store the entered values in a cookie to retreive on callback
	http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		s := &sessionInformation{
			ClientID:        r.FormValue("client_id"),
			Secret:          r.FormValue("secret"),
			RequestedScopes: r.FormValue("requested_scopes"),
		}
		fmt.Printf("Logging in to %s with secret %s and asking for scopes %s\n", s.ClientID, s.Secret, s.RequestedScopes)

		randombytes := make([]byte, 12) //Multiple of 3 to make sure no padding is added
		rand.Read(randombytes)
		state := base64.URLEncoding.EncodeToString(randombytes)

		serializedSessionInformation, _ := json.Marshal(s)
		sessionCookie := &http.Cookie{
			Name:   state,
			Value:  base64.URLEncoding.EncodeToString(serializedSessionInformation),
			MaxAge: 5 * 60, // 5 minutes
		}
		http.SetCookie(w, sessionCookie)

		u, _ := url.Parse("https://dev.itsyou.online:8443/v1/oauth/authorize")
		q := u.Query()
		q.Add("client_id", s.ClientID)
		q.Add("redirect_uri", "http://localhost:8080/callback")
		q.Add("scope", s.RequestedScopes)
		q.Add("state", state)
		q.Add("response_type", "code")
		u.RawQuery = q.Encode()
		http.Redirect(w, r, u.String(), http.StatusFound)
	})

	http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		code := r.FormValue("code")
		fmt.Println("Code: ", code)
		state := r.FormValue("state")

		sessionCookie, err := r.Cookie(state)
		if err != nil || sessionCookie == nil {
			fmt.Println("Failed to retrieve session cookie: ", err)
			fmt.Println("Cookie: ", sessionCookie)
			return
		}

		fmt.Println("Cookie value: ", sessionCookie.Value)

		decodedCookie, err := base64.URLEncoding.DecodeString(sessionCookie.Value)
		if err != nil {
			fmt.Println("Could not decode session cookie value: ", err)
		}
		s := &sessionInformation{}

		err = json.Unmarshal(decodedCookie, s)
		if err != nil {
			fmt.Println("Failed to convert session cookie: ", err)
			return
		}

		fmt.Println(s)

		tr := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
		hc := &http.Client{Transport: tr}
		req, err := http.NewRequest("POST", "https://dev.itsyou.online:8443/v1/oauth/access_token", nil)
		if err != nil {
			return
		}
		q := req.URL.Query()
		q.Add("client_id", s.ClientID)
		q.Add("client_secret", s.Secret)
		q.Add("code", code)
		q.Add("redirect_uri", "http://localhost:8080/callback")
		q.Add("state", state)
		req.URL.RawQuery = q.Encode()

		resp, err := hc.Do(req)
		if err != nil {
			fmt.Println("Error while getting the access token: ", err)
			return
		}
		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)

		fmt.Println("Response body: ", string(body))
		return

	})

	log.Fatal(http.ListenAndServe(":8080", nil))

}
911756
func (sp *SAMLServiceProvider) BuildAuthRequest() (string, error) {
	doc, err := sp.BuildAuthRequestDocument()
	if err != nil {
		return "", err
	}
	return doc.WriteToString()
}