Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, what is the right way to post attachments to Confluence REST API?

I am migrating from Confluence's SOAP API to using their REST API. I see there is support for adding attachments to a page (by doing a POST) but I am running into issues getting it to work (I am getting a 403: Forbidden Error message). I have other "get" items working fine through the rest api but doing an attachment post seems to keep failing.

Here is my current code (given a specific filename):

 byte[] rawData = File.ReadAllBytes(filename);
 var pageId = "11134";
 var url = new Uri("http://example.com:9088/rest/api/content/" + pageId + "/child/attachment");
 var requestContent = new MultipartFormDataContent();
 var imageContent = new ByteArrayContent(rawData);
 imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse(attachement.contentType);
 requestContent.Add(imageContent, "file", attachement.fileName);
 requestContent.Headers.Add("X-Atlassian-Token", "nocheck");

Can you see if I am doing anything wrong above?

like image 978
leora Avatar asked Sep 25 '15 11:09

leora


1 Answers

403 status indicates that request is not authorized. In order to authorize a request you need to specify Authorization header. Confluence REST API supports Basic authorization scheme. For basic authentication you need to specify the following header with each request: Authorization: Basic username:password where username:password part should be Base64-encoded. You can use the following code in order to do this:

string userName;
string password;
string authorizationString = userName + ":" + password;
string encodedValue = Convert.ToBase64String(Encoding.ASCII.GetBytes(authorizationString));
string authorizationHeaderValue = "Basic " + encodedValue;

requestContent.Headers.Add("Authorization", authorizationHeaderValue);

According to this link you also should specify the following url parameter with each request: os_authType=basic.

HTTP basic authentication: (Authorization HTTP header) containing 'Basic username:password'. Please note however, username:password must be base64 encoded. The URL must also contain the 'os_authType=basic' query parameter.

Note: make sure to connect via https if using basic authentication;

like image 187
Vova Avatar answered Nov 03 '22 01:11

Vova