in pkg/infrastructure/spRoleAssignmentManager/defaultSPRoleAssignmentManager.go [163:228]
func (r *SPRoleAssignmentManager) AssignRoleToSP(subscription string, SPOBjectID string, role domain.Role) error {
// scope := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s", subscription, resourceGroupName)
scope := fmt.Sprintf("/subscriptions/%s", subscription)
url := fmt.Sprintf("https://management.azure.com/%s/providers/Microsoft.Authorization/roleAssignments/%s?api-version=2022-04-01", scope, uuid.New().String())
data := map[string]interface{}{
"principalId": SPOBjectID,
"principalType": "ServicePrincipal",
"roleDefinitionId": role.RoleDefinitionResourceID,
}
properties := map[string]interface{}{
"properties": data,
}
// marshal data as json
jsonData, err := json.Marshal(properties)
if err != nil {
return err
}
//convert to json string
jsonString := string(jsonData)
log.Debugf("jsonString: %s", jsonString)
client := &http.Client{}
req, err := http.NewRequest("PUT", url, bytes.NewBufferString(jsonString))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "Go HTTP Client")
defaultApiBearerToken, err := r.azAPIClient.GetDefaultAPIBearerToken()
if err != nil {
return err
}
// add bearer token to header
req.Header.Add("Authorization", "Bearer "+defaultApiBearerToken)
// make request
resp, err := client.Do(req)
if err != nil {
return err
}
// read response body
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != 200 && resp.StatusCode != 201 {
return fmt.Errorf("Failed to assign role to SP. Status code: %s", string(body))
}
// print response body
log.Debugln(string(body))
return nil
}