Ejemplo n.º 1
0
// InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode
// that can be used with CheckForUserCompletion or WaitForUserCompletion.
func InitiateDeviceAuth(client *autorest.Client, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) {
	req, _ := autorest.Prepare(
		&http.Request{},
		autorest.AsPost(),
		autorest.AsFormURLEncoded(),
		autorest.WithBaseURL(oauthConfig.DeviceCodeEndpoint.String()),
		autorest.WithFormData(url.Values{
			"client_id": []string{clientID},
			"resource":  []string{resource},
		}),
	)

	resp, err := client.Send(req)
	if err != nil {
		return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err)
	}

	var code DeviceCode
	err = autorest.Respond(
		resp,
		autorest.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&code),
		autorest.ByClosing())
	if err != nil {
		return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err)
	}

	code.ClientID = clientID
	code.Resource = resource
	code.OAuthConfig = oauthConfig

	return &code, nil
}
Ejemplo n.º 2
0
func getResourceGroups(client *autorest.Client) (*string, error) {
	var p map[string]interface{}
	var req *http.Request
	p = map[string]interface{}{
		"subscription-id": subscriptionID,
	}
	q := map[string]interface{}{
		"api-version": apiVersion,
	}

	req, _ = autorest.Prepare(&http.Request{},
		autorest.AsGet(),
		autorest.WithBaseURL(resourceGroupURLTemplate),
		autorest.WithPathParameters(p),
		autorest.WithQueryParameters(q))

	resp, err := client.Send(req, http.StatusOK)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()
	contents, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	contentsString := string(contents)

	return &contentsString, nil
}
Ejemplo n.º 3
0
func setClientInspectors(
	client *autorest.Client,
	requestInspector autorest.PrepareDecorator,
	loggingModule string,
) {
	logger := loggo.GetLogger(loggingModule)
	client.ResponseInspector = tracing.RespondDecorator(logger)
	client.RequestInspector = tracing.PrepareDecorator(logger)
	if requestInspector != nil {
		tracer := client.RequestInspector
		client.RequestInspector = func(p autorest.Preparer) autorest.Preparer {
			p = tracer(p)
			p = requestInspector(p)
			return p
		}
	}
}
Ejemplo n.º 4
0
// CheckForUserCompletion takes a DeviceCode and checks with the Azure AD OAuth endpoint
// to see if the device flow has: been completed, timed out, or otherwise failed
func CheckForUserCompletion(client *autorest.Client, code *DeviceCode) (*Token, error) {
	req, _ := autorest.Prepare(
		&http.Request{},
		autorest.AsPost(),
		autorest.AsFormURLEncoded(),
		autorest.WithBaseURL(code.OAuthConfig.TokenEndpoint.String()),
		autorest.WithFormData(url.Values{
			"client_id":  []string{code.ClientID},
			"code":       []string{*code.DeviceCode},
			"grant_type": []string{OAuthGrantTypeDeviceCode},
			"resource":   []string{code.Resource},
		}),
	)

	resp, err := client.Send(req)
	if err != nil {
		return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err)
	}

	var token deviceToken
	err = autorest.Respond(
		resp,
		autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusBadRequest),
		autorest.ByUnmarshallingJSON(&token),
		autorest.ByClosing())
	if err != nil {
		return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err)
	}

	if token.Error == nil {
		return &token.Token, nil
	}

	switch *token.Error {
	case "authorization_pending":
		return nil, ErrDeviceAuthorizationPending
	case "slow_down":
		return nil, ErrDeviceSlowDown
	case "access_denied":
		return nil, ErrDeviceAccessDenied
	case "code_expired":
		return nil, ErrDeviceCodeExpired
	default:
		return nil, ErrDeviceGeneric
	}
}
Ejemplo n.º 5
0
// Use a Client Inspector to set the request identifier.
func ExampleWithClientID() {
	uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6"
	req, _ := autorest.Prepare(&http.Request{},
		autorest.AsGet(),
		autorest.WithBaseURL("https://microsoft.com/a/b/c/"))

	c := autorest.Client{Sender: mocks.NewSender()}
	c.RequestInspector = WithReturningClientID(uuid)

	autorest.SendWithSender(c, req)
	fmt.Printf("Inspector added the %s header with the value %s\n",
		HeaderClientID, req.Header.Get(HeaderClientID))
	fmt.Printf("Inspector added the %s header with the value %s\n",
		HeaderReturnClientID, req.Header.Get(HeaderReturnClientID))
	// Output:
	// Inspector added the x-ms-client-request-id header with the value 71FDB9F4-5E49-4C12-B266-DE7B4FD999A6
	// Inspector added the x-ms-return-client-request-id header with the value true
}
Ejemplo n.º 6
0
func setUserAgent(client *autorest.Client) {
	var version string
	if terraform.VersionPrerelease != "" {
		version = fmt.Sprintf("%s-%s", terraform.Version, terraform.VersionPrerelease)
	} else {
		version = terraform.Version
	}

	client.UserAgent = fmt.Sprintf("HashiCorp-Terraform-v%s", version)
}
Ejemplo n.º 7
0
Archivo: azure.go Proyecto: lvjp/packer
// NewAsyncPollingRequest allocates and returns a new http.Request to poll an Azure long-running
// operation. If it successfully creates the request, it will also close the body of the passed
// response, otherwise the body remains open.
func NewAsyncPollingRequest(resp *http.Response, c autorest.Client) (*http.Request, error) {
	location := GetAsyncOperation(resp)
	if location == "" {
		return nil, autorest.NewErrorWithResponse("azure", "NewAsyncPollingRequest", resp, "Azure-AsyncOperation header missing from response that requires polling")
	}

	req, err := autorest.Prepare(&http.Request{},
		autorest.AsGet(),
		autorest.WithBaseURL(location))
	if err != nil {
		return nil, autorest.NewErrorWithError(err, "azure", "NewAsyncPollingRequest", nil, "Failure creating poll request to %s", location)
	}

	autorest.Respond(resp,
		c.ByInspecting(),
		autorest.ByClosing())

	return req, nil
}
Ejemplo n.º 8
0
func setUserAgent(client *autorest.Client) {
	version := terraform.VersionString()
	client.UserAgent = fmt.Sprintf("HashiCorp-Terraform-v%s", version)
}