I want to get JWT Access token for Docusing, i tried use following code to get access token ,after that i pass access token to create envelope, i get an error
"Error calling CreateEnvelope: {
"errorCode": "AUTHORIZATION_INVALID_TOKEN",
"message": "The access token provided is expired, revoked or malformed."
}"
Dim PrivateKey As String = "MIIEowIBAAKCAQEAjtTe7UUP/CBI9s...BLABLABLA...JfwZ2hHqFPXA9ecbhc0".Replace(vbLf, "").Replace(vbCr, "")
Dim ar1 As JObject = New JObject()
ar1.Add("typ", "JWT")
ar1.Add("alg", "RS256")
Dim header As String = Base64UrlEncoder.Encode(ar1.ToString)
Dim ar2 As JObject = New JObject()
ar2.Add("iss", "INTEGRATION_ID")
ar2.Add("sub", "GUID_VERSION_OF_USER_ID")
ar2.Add("iat", DateDiff(DateInterval.Second, New Date(1970, 1, 1), Now().ToUniversalTime))
ar2.Add("exp", DateDiff(DateInterval.Second, New Date(1970, 1, 1), DateAdd(DateInterval.Hour, 1,Now().ToUniversalTime)))
ar2.Add("aud", "account-d.docusign.com")
ar2.Add("scope", "signature")
Dim body As String = Base64UrlEncoder.Encode(ar2.ToString)
Dim stringToSign As String = header & "." & body
Dim bytesToSign() As Byte = Encoding.UTF8.GetBytes(stringToSign)
Dim keyBytes() As Byte = Convert.FromBase64String(PrivateKey)
Dim privKeyObj = Asn1Object.FromByteArray(keyBytes)
Dim privStruct = RsaPrivateKeyStructure.GetInstance(privKeyObj)
Dim sig As ISigner = SignerUtilities.GetSigner("SHA256withRSA")
sig.Init(True, New RsaKeyParameters(True, privStruct.Modulus, privStruct.PrivateExponent))
sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length)
Dim signature() As Byte = sig.GenerateSignature()
Dim sign As String = Base64UrlEncoder.Encode(signature)
Return header & "." & body & "." & sign
I take above code from this link DocuSign JWT Access Token Request, in that user mention working code ,Pls advise me what i make mistakes,
Note : I am get access token and immediately pass that token to create envelope. "iss" is my integration key and "sub" is my userid and Private keyi generate from RSA key pair form on of the my app which created in Apps and Integration Keys
i am use docusing 3.0.0 dll which support .net framework 4.6.1
Regards,
Aravind
If you are using the DocuSign dll (version 3.0.0 is pretty old, I suggest you upgrade BTW) you don't need all this code.
Instead you can do this:
(note that I assume you have a configuration file with the information, you will want to update this code to include the ClientId/IK, UserId, AuthServer and RSA Key location).
Public Sub UpdateUserFromJWT()
Me._authToken = _apiClient.RequestJWTUserToken(Me._configuration("DocuSignJWT:ClientId"), Me._configuration("DocuSignJWT:ImpersonatedUserId"), Me._configuration("DocuSignJWT:AuthServer"), DSHelper.ReadFileContent(DSHelper.PrepareFullPrivateKeyFilePath(Me._configuration("DocuSignJWT:PrivateKeyFile"))), 1)
_account = GetAccountInfo(_authToken)
Me.User = New User With {
.Name = _account.AccountName,
.AccessToken = _authToken.access_token,
.ExpireIn = DateTime.Now.AddSeconds(_authToken.expires_in.Value),
.AccountId = _account.AccountId
}
Me.Session = New Session With {
.AccountId = _account.AccountId,
.AccountName = _account.AccountName,
.BasePath = _account.BaseUri
}
End Sub
Related
I'm trying to make an http request with the following attributes
Header - contains a key 'Referer' with a set value
Body format is x-www-form-urlencoded
Body contains multiple keyes 'type', 'encpwd', 'user', 'pwd' & 'admsid'
In the response from the request, I need to obtain values in the cookies. I'm able to do it via Postman get the cookies, however I need to write a function/method to achieve this and return the cookies values which will be required to authenticate in future API calls.
From the internet, I found a sample code as below
Dim client As RestSharp.RestClient = New RestSharp.RestClient(inEndpoint)
client.Timeout = 10000
client.CookieContainer = New System.Net.CookieContainer
Dim request As RestSharp.RestRequest = New RestRequest(RestSharp.Method.Post)
request.AddHeader("Referer", strReferer)
Dim response As IRestResponse = client.Execute(request)
responsecode=response.StatusCode
responsecontent=response.Content
Dim cookies =client.CookieContainer.GetCookieHeader(response.ResponseUri)
cookiecontainer=cookies.ToString
Console.WriteLine("cookieJar "+ cookies.ToString)
Console.WriteLine("response Uri "+response.ResponseUri.ToString)
But when I'm trying this code in Visual Studio (I have installed RestSharp package already), I'm getting lots of error as below:
client.Timeout = 10000 -- Timeout is not a member of RestClient
client.CookieContainer = New System.Net.CookieContainer -- Property 'CookieContainer' is 'Read-Only'
Dim request As RestSharp.RestRequest = New RestRequest(RestSharp.Method.Post) -- Type 'RestRequest' is not defined
request.AddHeader("Referer", strReferer) -- 'AddHeader' is not a member of 'RestRequest'
Dim response As IRestResponse = client.Execute(request) -- Type 'IRestResponse' is not defined
I'm quite new to https request, please help me where I'm making mistake. Also I don't know/find how to add the body parameters with x-www-form-urlencoded format, everywhere it's mentioned in JSON, but this API service only accepts this format for Body.
Thanks for the help in advance.
I've tried the below code
Dim client As RestClient = New RestClient(endPoint)
Dim request As RestRequest = New RestRequest(Method.Post)
request.AddHeader("Referer", strReferer)
request.AddParameter("application/x-www-form-urlencoded", "type=" + strType + "&encpwd= " + strEncPwd + "&user=" + strUser + "&pwd=" + strPwd + "&admsid=" + stradmsID, ParameterType.RequestBody)
Dim response = client.Execute(request)
It generates exception "cannot send a content-body with this verb-type."
Please help
The below code ran successfully.
Dim client = New RestClient(endPoint)
Dim request = New RestRequest()
request.Method = Method.Post
request.AddHeader("Referer", strReferer)
request.AddHeader("Content-Type", "application/x-www-form-urlencoded")
request.AddParameter("type", strType)
request.AddParameter("encpwd", strEncPwd)
request.AddParameter("user", strUser)
request.AddParameter("pwd", strPwd)
request.AddParameter("admsid", stradmsID)
Dim response = client.Execute(request)
Dim cookies = client.CookieContainer.GetCookieHeader(response.ResponseUri)
Console.WriteLine("cookieJar " + cookies.ToString)
Console.WriteLine(response.Content)
Hope it will help someone. Thanks
Our company is going to be using a service called Spiff to send commission numbers to them and they will generate reports on it. They have multiple integration options but we are down to 3: manually uploading excel (not great but free), exporting our data into a CSV file and providing a SFTP site for them to upload from (have to provide SFTP and integration costs), or using their API to send data to (also free but we have to push the data). I'm not familiar with scripting but I am decent at VB.net so I'm trying to convert their example code over. The API documentation is at https://app.getguru.com/card/iXpEBagT/How-to-send-data-to-Spiffs-API and it's a little beyond me so I asked them for a screen shot example which they gave me:
// Spiff provided key
const key = "YourSecret";
// Seconds since epoch
const time = Math.floor(Date.now() / 1000);
const preDigestString = '${time}.${request.data}';
// HMAC SHA256 digest (must be lowercase)
const digest = CryptoJS.HmacSHA256(preDigestString, key).toString(CryptoJS.digest).toLowerCase()
const signature = 't=${time},v1=${digest}'
pm.request.headers.add({ key: 'Signature', value: signature })
So this is what I have but I don't know what to do about the toString(CryptoJS.digest) in VB.net:
Dim myKey As String = "12345678" ' Fake test data
Dim myUnixTime As Double = (DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds
Dim myData As String = My.Computer.FileSystem.ReadAllText(FileNameTextBox.Text) ' Fake test data
Dim myPreDigestString = $"${myUnixTime}.${myData}"
Dim myDigest As String = GetHMACSHA256Hash(myPreDigestString, myKey)
Dim mySignature As String = $"t=${myUnixTime},v1=${myDigest}"
Dim myHeader As String = $"key: 'Signature', value: {mySignature}"
Dim result_post = SendRequest(New Uri(URITextBox.Text), UTF8.GetBytes(myData), "application/json", "PUT", myHeader)
My SendRequest just takes the passed URL (their webhook), the data, and adds the header. The result I get every time is a (400) Bad Request so I have to be doing something wrong and I'm guessing it's the conversion to Digest that their example has that I'm having trouble reproducing?
Edit. My GetHMACSHA256Hash function:
Private Shared Function GetHMACSHA256Hash(ByVal text As String, ByVal key As String) As String
Dim encoding As New ASCIIEncoding()
Dim textBytes As Byte() = encoding.GetBytes(text)
Dim keyBytes As Byte() = encoding.GetBytes(key)
Dim hashBytes As Byte()
Using hash As New HMACSHA256(keyBytes)
hashBytes = hash.ComputeHash(textBytes)
End Using
Return BitConverter.ToString(hashBytes).Replace("-", "").ToLower()
End Function
I'm at a loss as to what is wrong here. I'm trying to create a JWT with RS SHA256. At handler.WriteToken I get this error:
IDX10634: Unable to create the SignatureProvider.
Algorithm: 'System.String', SecurityKey: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey'
is not supported. The list of supported algorithms is available here: https://aka.ms/IdentityModel/supported-algorithms
The way I interpret it, it is telling me that I am specifying an unsupported algorithm, yet SecurityAlgorithms.RsaSha256 resolves to "RS256".
Any guidance would be appreciated. Below is my code.
Imports System.Security.Cryptography
Imports Microsoft.IdentityModel.Tokens
Imports System.IdentityModel.Tokens.Jwt
Public Function GetJWT()
Dim rsaPrivateKey As String = "MIIEvQI...small piece of key included here...J83wMcqFO4WXjrMXU="
Dim rsaPrivateKeyBytes() As Byte = System.Text.Encoding.Default.GetBytes(Base64UrlEncode(rsaPrivateKey))
Dim securityKey As Microsoft.IdentityModel.Tokens.SymmetricSecurityKey = New Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(rsaPrivateKeyBytes)
Dim credentials As SigningCredentials = New Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256)
Dim header As JwtHeader = New JwtHeader(credentials)
Dim payload As JwtPayload = New JwtPayload()
payload.Item("test") = "this is a test"
Dim secToken As JwtSecurityToken = New JwtSecurityToken(header, payload)
Dim handler As JwtSecurityTokenHandler = New JwtSecurityTokenHandler()
Dim tokenString As String = handler.WriteToken(secToken)
Return tokenString
End Function
Public Function Base64UrlEncode(input As String) As String
Dim inputBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(input)
Return Convert.ToBase64String(inputBytes).Replace("+", "-").Replace("/", "_").Replace("=", "")
End Function
According to the link you posted, RsaSha256 is not a supported symmetric algorithm. You need to try a symmetric algorithm, like SecurityAlgorithms.HmacSha256.
In my vb.net application I am interacting with a webservice written by another group. This interaction involved verifying an account number. The way the other group wrote their webservice is I am supposed to hit a specific url, retrieve a sessionid number and then use that number for subsequent requests. The problem I am having is that when I pass the sessionid it needs to be contained in { } brackets. for example: "http://server/acctverify/Verification.groovy;jsessionid=${123456789}"
The problem lies in when I pass the above URL it gets encoded to something like this:
http://server/acctverify/Verification.groovy;jsessionid=$%7B123456789%7D
with the {}'s replaced.
I don't understand why this is happening nor how to fix it.
Code I am running:
Dim client As WebClient = New WebClient
Dim Sessionuri As Uri = New Uri(VerifyInit)
Dim sessionID As String = client.DownloadString(Sessionuri)
Dim FinalUri As Uri = New Uri(VerifyPost & "{" & sessionID & "}?acctnumber=")
Dim FinalResults As String = client.DownloadString(FinalUri)
MessageBox.Show(FinalResults)
Thanks in advance for any help.
There is a deprecated constructor for the Uri class which will prevent URIs from being encoded when the dontEscape parameter of the constructor is True.
Like this:
Dim client As WebClient = New WebClient
Dim Sessionuri As Uri = New Uri(VerifyInit)
Dim sessionID As String = client.DownloadString(Sessionuri)
Dim FinalUri As Uri = New Uri(VerifyPost & "{" & sessionID & "}?acctnumber=", true)
Dim FinalResults As String = client.DownloadString(FinalUri)
MessageBox.Show(FinalResults)
This constructor is deprecated for good reason: the URI you're trying to create is not a legal URI. The { and } characters must be encoded. But if you're using a non-compliant server that only accepts unencoded characters, the constructor above should work.
I've been having a problem adding an AdGroup using the FacebookMediaObject in Visual Basic to create a new add using the Facebook ADS Api.
I understand not many people have access to it, but I hope someone here can shedd a light on it.
Dim objAuthorizer As Authorizer = New Authorizer
Dim objFB As FacebookClient = New FacebookClient(objAuthorizer.Session.AccessToken)
Dim objParametersTargeting As Object = New ExpandoObject()
Dim arrCountries() As String
ReDim arrCountries(0)
arrCountries(0) = "NL"
objParametersTargeting.countries = arrCountries
Dim objCreative As Object = New ExpandoObject()
objCreative.title = "Test Adgroup title"
objCreative.body = "Test Adgroup body"
objCreative.link_url = "www.test.com"
objCreative.image_file = "testcups.jpg"
Dim strFilename As String = "C:\Upload\testcups.jpg"
Dim objAdgroupParameters() As Object
ReDim objAdgroupParameters(0)
objAdgroupParameters(0) = New ExpandoObject()
objAdgroupParameters(0).campaign_id = "123456789"
objAdgroupParameters(0).name = "Test adgroup"
objAdgroupParameters(0).bid_type = 1
objAdgroupParameters(0).max_bid = 50
objAdgroupParameters(0).targeting = objParametersTargeting
objAdgroupParameters(0).creative = objCreative
Dim fbUplImage = New Facebook.FacebookMediaObject
fbUplImage.FileName = "testcups.jpg"
fbUplImage.ContentType = "image/png"
Dim objBytes As Byte() = System.IO.File.ReadAllBytes(strFilename)
fbUplImage.SetValue(objBytes)
Dim objParameters As Object = New ExpandoObject()
objParameters.method = "ads.createAdGroups"
objParameters.account_id = "123456789"
objParameters.adgroup_specs = objAdgroupParameters
objParameters.image = fbUplImage
Dim objResult As Object = objFB.Post(objParameters)
Of course the Account ID and the Campaign ID have to be valid ID's (which are valid ID's in my local source) and the file has to exist on your harddrive (which also is there on my local drive).
I keep getting the following results back:
{"updated_adgroups":[],"failed_adgroups":[{"spec_number":"0","errors":["Filesystem entity `/testcups.jpg' does not exist."]}]}
Anybody out there has any clue?
Thanks in advance,
Bas
Some extra info:
I found out (with a HTTP sniffer) that the Facebook C# SDK isn't making a Multipart Post requestout o
Have you tried switching "fbUplImage.ContentType = "image/png" to image/jpg?