Currently I'm running SQL Server 2017 on a local workstation. I would like to make a call (GET) from a SQL stored procedure to a SharePoint 2016 REST API on our network.
When using the REST API url in a browser or when using PostMan (NTLM authentication) I'm successful in getting results.
When trying to call the same API from SQL I keep on running into a 401 Unauthorized
error. The authentication header contains the same account details as the one used in PostMan.
The SQL query below returns:
Status: 401 (Unauthorized)
Response text: 401 UNAUTHORIZED
How can I fix the SQL query below to resolve this issue?
DECLARE @contentType NVARCHAR(64);
DECLARE @responseText NVARCHAR(2000);
DECLARE @responseXML NVARCHAR(2000);
DECLARE @ret INT;
DECLARE @status NVARCHAR(32);
DECLARE @statusText NVARCHAR(32);
DECLARE @token INT;
DECLARE @url NVARCHAR(256);
DECLARE @authHeader VARCHAR(8000);
SET @authHeader = 'BASIC ' +(SELECT CAST('<account>:<password>' as varbinary(max)) FOR XML PATH(''), BINARY BASE64)
--SET @contentType = 'application/x-www-form-urlencoded';
SET @contentType = 'application/atom+xml';
SET @url = 'http://<FQDN>/sites/<site>/_api/web/lists/getbytitle(''Documents'')/items';
-- Open the connection.
EXEC @ret = sp_OACreate 'MSXML2.ServerXMLHTTP', @token OUT;
IF @ret <> 0 RAISERROR('Unable to open HTTP(S) connection.', 10, 1);
-- Send the request.
EXEC @ret = sp_OAMethod @token, 'open', NULL, 'POST', @url, 'false';
IF @ret <> 0 EXEC sp_OAGetErrorInfo @token
EXEC @ret = sp_OAMethod @token, 'setRequestHeader', NULL, 'Authentication', @authHeader;
IF @ret <> 0 EXEC sp_OAGetErrorInfo @token
EXEC @ret = sp_OAMethod @token, 'setRequestHeader', NULL, 'Content-type', @contentType;
IF @ret <> 0 EXEC sp_OAGetErrorInfo @token
EXEC @ret = sp_OAMethod @token, 'send'--, NULL, @postData;
IF @ret <> 0 EXEC sp_OAGetErrorInfo @token
-- Handle the response.
EXEC @ret = sp_OAGetProperty @token, 'status', @status OUT;
EXEC @ret = sp_OAGetProperty @token, 'statusText', @statusText OUT;
EXEC @ret = sp_OAGetProperty @token, 'responseText', @responseText OUT;
-- Show the response.
PRINT 'Status: ' + @status + ' (' + @statusText + ')';
PRINT 'Response text: ' + @responseText;
-- Close the connection.
EXEC @ret = sp_OADestroy @token;
IF @ret <> 0 RAISERROR('Unable to close HTTP connection.', 10, 1);