'SAS azure token 401 Unauthorized
I'm working with an API that's using azure and requires me to generate an SAS token. I haven't worked with azure before and the docs seem a bit vague and I have ended up a bit stuck.
I used the php snippet to generate the token and have passed it what I think is correct, but no matter what I do I get a 401 unauthorized response.
$sasKeyValue = json_decode($res->getBody()->getContents())->sas;
$sasKeyName = 'sas';
$uri = 'Sonar.azure-devices.net/devices/DEVICEID/messages/events?api-version=2018-06-30';
$sas = $this->generateSasToken($uri, $sasKeyName, $sasKeyValue);
try {
$res = $client->request('POST', 'https://Sonar.azure-devices.net/devices/DEVICEID/messages/events?api-version=2018-06-30', [
'headers' => [
'Content-Type' => 'application/json-patch+json',
'Authorization' => $sas
]
] );
} catch (ClientException $e) {
echo Psr7\Message::toString($e->getRequest());
echo Psr7\Message::toString($e->getResponse());
}
public function generateSasToken($uri, $sasKeyName, $sasKeyValue)
{
$targetUri = strtolower(rawurlencode(strtolower($uri)));
$expires = time();
$expiresInMins = 60;
$week = 60*60*24*7;
$expires = $expires + $week;
$toSign = $targetUri . "\n" . $expires;
$signature = rawurlencode(base64_encode(hash_hmac('sha256',
$toSign, $sasKeyValue, TRUE)));
$token = "SharedAccessSignature sr=" . $targetUri . "&sig=" . $signature . "&se=" . $expires . "&skn=" . $sasKeyName;
return $token;
}
POST /devices/DEVICEID/messages/events?api-version=2018-06-30 HTTP/1.1
User-Agent: GuzzleHttp/6.5.5 curl/7.47.0 PHP/7.4.11
Host: sonar.azure-devices.net
Content-Type: application/json-patch+json
Authorization: SharedAccessSignature sr=sonar.azure-devices.net%2fdevices%2fdeviceid%2fmessages%2fevents%3fapi-version%3d2018-06-30&sig=rz0L5BRmfSOMdi5HApG6PYbsYr7FyNxtdrTfkD%2ByXKs%3D&se=1643892485&skn=sas
HTTP/1.1 401 Unauthorized
Content-Length: 161
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
x-ms-request-id: 784a9013-f875-410f-a274-890cab4b964e
iothub-errorcode: IotHubUnauthorizedAccess
Date: Thu, 27 Jan 2022 12:48:04 GMT
Any chance someone could point out what they think I did wrong here? I'm assuming the key name or something like that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
