Created
April 11, 2018 19:30
-
-
Save trzye/27cff4f6a785618f32e10ab6737bbd02 to your computer and use it in GitHub Desktop.
Generates a SAS Token for Azure REST Api Calls (Particularly for Service Bus Services like Event Hub & Queues) in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.URLEncoder | |
import java.time.Instant | |
import java.util.* | |
import javax.crypto.Mac | |
import javax.crypto.spec.SecretKeySpec | |
const val ONE_HOUR = 3600L; | |
/** | |
* | |
* Code for generating of SAS token for authorization with Service Bus in Kotlin | |
* | |
* based on: https://gist.github.com/sedouard/79d9813bfae0ed1e56cf for C# | |
* | |
* @param resourceUri e.g. https://tripappservicebus.servicebus.windows.net/mediaservicequeue/messages | |
* @param key e.g. tZkUg3JERVurvDU8Ra+DUC7VTTAT6P3zi7xD8gALdXU= | |
*/ | |
fun generateSasToken(resourceUri: String, key: String, policy: String = "RootManageSharedAccessKey", expiryInSeconds: Long = ONE_HOUR): String | |
{ | |
val expiry = Instant.now().epochSecond + expiryInSeconds | |
val resourceUrl = URLEncoder.encode(resourceUri, Charsets.UTF_8.name()) | |
val stringToSign = resourceUrl + "\n$expiry" | |
val hmac = Mac.getInstance("HmacSHA256").apply { | |
init(SecretKeySpec(key.toByteArray(Charsets.UTF_8), algorithm)); | |
} | |
val signature = Base64.getEncoder().encodeToString(hmac.doFinal(stringToSign.toByteArray())); | |
val signatureUrl = URLEncoder.encode(signature, Charsets.UTF_8.name()) | |
return "SharedAccessSignature sr=$resourceUrl&sig=$signatureUrl&se=$expiry&skn=$policy" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment