Docusign: Obtain the access token - docusignapi

Ref: https://developers.docusign.com/platform/auth/authcode/authcode-get-token/
I am having an issue on Step 2: Obtain Access Token
I am trying to get an access token. However I am getting the following error:
{
"error": "invalid_grant",
"error_description": "unsupported_grant_type"
}
whether its using c# code or using PostMan I am getting the error above.
In PostMan
URL: https://account-d.docusign.com/oauth/token
Method: Post
Headers
Authorization: BASIC BASE64_COMBINATION_OF_INTEGRATION_AND_SECRET_KEYS
Content_Type: application/json;charset=utf-8
Body: I tried form-data, x.www.form-urlencoded, raw... all are the same
grant_type: authorization_code
code: My_AUTHORIZATION_CODE
I also tried getting the access token in the call back page when I get the Authorization Code.
protected void Page_Load(object sender, EventArgs e)
{
var url = ConfigurationManager.AppSettings["DocuSign.TokenEndPoint"];
var data = $"grant_type=authorization_code=&{Request.QueryString["Code"]}";
WebRequest req = WebRequest.Create(url);
req.Method = "POST";
req.ContentLength = data.Length;
req.ContentType = "application/json; charset=UTF-8";
UTF8Encoding enc = new UTF8Encoding();
var code64 = Convert.ToBase64String(enc.GetBytes($"{ConfigurationManager.AppSettings["DocuSign.ClientId"]}:{ConfigurationManager.AppSettings["DocuSign.ClientSecret"]}"));
req.Headers.Add("Authorization", "Basic " + code64);
using (Stream ds = req.GetRequestStream())
{
ds.Write(enc.GetBytes(data), 0, data.Length);
}
WebResponse wr = req.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Response.Write(content);
}

Your content_type should be application/x-www-form-urlencoded

the following line was wrong:
var data = $"grant_type=authorization_code=&{Request.QueryString["Code"]}";
Changed to
var data = $"grant_type=authorization_code&code={Request.QueryString["Code"]}";
I was missing code=

Related

Azure AD Adal4j Token recieved after refresh token is not signed JWT

I am developing an authentication service for my web based java application using Azure AD OpenID connect framework. I am referring to adal4j-1.2.0.jar
The authentication is happening as per the behavior. I am getting the JWT claims and able to validate it.
But when 60 mins of session timeout occurs and I am trying to get new token claims using refresh token, the new tokens are not Signed JWT. They are Plain JWT.
I am using below call to acquire token using my initial refresh token which I am caching.
acquireTokenByRrefreshToken(refreshtoken, credential,null,null)
For validation of token, I am using the code as below
IDtokenValidator validator = new IDTokenValidator(issuer,clientID, JWSAlgo,URL)
validator.validate(idToken, exoectedNoounce); //this line throws badjwtexception signed ID token expected
Can anyone help me to understand how can I redeem the refresh token to get new Signed tokens. Or after redeeming the token, the new tokens are always Plain JWT.
I believe ,you are using implicit grant flow to get token.You are getting token from authorization end point.In this flow ,you will not get refresh token.Either you need to get new token after session expire or create a hidden frame which can get token before session expire.
You could refer to the official doc to acquire access token and refresh token by code grant flow.
Actually,methods in adal4j are implemented via HTTP REST API so that you could refer to the code below to request AuthorizationCode.
public static void getAuthorizationCode() throws IOException {
String encoding = "UTF-8";
String params = "client_id=" + clientId
+ "&response_type=" + reponseType
+ "&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F"
+ "&response_mode=query"
+ "&resource=https%3A%2F%2Fgraph.windows.net"
+ "&state=12345";
String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/authorize";
byte[] data = params.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
BufferedReader br = null;
if (conn.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
Then you could get access token using the AuthorizationCode you got and get refresh code using the code below.
public static void getToken(String refreshToken) throws IOException {
String encoding = "UTF-8";
String params = "client_id=" + clientId + "&refresh_token=" + refreshToken
+ "&grant_type=refresh_token&resource=https%3A%2F%2Fgraph.windows.net";
String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
byte[] data = params.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
BufferedReader br = null;
if (conn.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
Hope it helps you.

Microsoft Face Detect API code example Bad Request

I have been trying to solve this bad request error. I am able to make the request call and Azure reports total calls correctly and also reports total errors.
I can not get this code example to work; however if I send this via their online console all is fine:
static async void MakeRequest()
{
string key1 = "YourKey"; // azure the one should work
string data = "https://pbs.twimg.com/profile_images/476054279438868480/vvv5YG0Q.jpeg";
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request parameters
queryString["returnFaceId"] = "true";
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key1);
Console.Beep();
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + queryString;
//string statusURL = HttpContext.Current.Request.Url.Host;
//console.WriteLine("Your Status URL address is :" + statusURL);
HttpResponseMessage response;
// Request body
// byte[] byteData = Encoding.UTF8.GetBytes("{url: https://pbs.twimg.com/profile_images/476054279438868480/vvv5YG0Q.jpeg}");
byte[] byteData = Encoding.UTF8.
GetBytes("{"+ "url"+":"+"https://pbs.twimg.com/profile_images/476054279438868480/vvv5YG0Q.jpeg" + "}");
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType =
new MediaTypeHeaderValue("application/json");
response = await client.PostAsync(uri, content);
}
HttpRequestMessage request =
new HttpRequestMessage(HttpMethod.Post, uri);
request.Content = new StringContent("{body}",
Encoding.UTF8,
"application/json");
//CONTENT-TYPE header
await client.SendAsync(request)
.ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
Console.WriteLine("-----------------------------------");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("End of Post return from MS");
Console.WriteLine("Hit ENTER to exit...");
Console.ReadKey();
});
}// end of Make request
Your JSON is malformed. Your fields and non-scalar fields must be quoted. You also have some unnecessary code. Here's code that works:
static async void MakeRequest()
{
string key1 = "YourKey"; // azure the one should work
string imageUri = "https://pbs.twimg.com/profile_images/476054279438868480/vvv5YG0Q.jpeg";
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request parameters
queryString["returnFaceId"] = "true";
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key1);
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + queryString;
string body = "{\"url\":\"" + imageUri + "\"}";
using (var content = new StringContent(body, Encoding.UTF8, "application/json"))
{
await client.PostAsync(uri, content)
.ContinueWith(async responseTask =>
{
var responseBody = await responseTask.Result.Content.ReadAsStringAsync();
Console.WriteLine("Response: {0}", responseBody);
Console.WriteLine("-----------------------------------");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("End of Post return from MS");
Console.WriteLine("Hit ENTER to exit...");
Console.ReadKey();
});
}
}// end of Make request
If you're using Visual Studio, I would recommend the NuGet package as this will handle much of the mundane details for you, including C# types for responses.

Can't delete Azure Storage Table using Azure REST API

I am getting an error "Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature."
I followed the authorization tutorial provided by Microsoft, Delete Table, Authentication for the Azure Storage Services.
Am I missing anything?
It seems that you’d like to delete table via rest api.
DELETE https://myaccount.table.core.windows.net/Tables('mytable')
the following sample works fine on my side, please refer to the code to generate the signature.
string StorageAccount = "account name here";
string StorageKey = "account key here";
string tablename = "table name";
string requestMethod = "DELETE";
string mxdate = "";
string storageServiceVersion = "2015-12-11";
protected void Button1_Click(object sender, EventArgs e)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(string.Format(CultureInfo.InvariantCulture,
"https://{0}.table.core.windows.net/Tables('{1}')",
StorageAccount, tablename));
req.Method = requestMethod;
//specify request header
string AuthorizationHeader = generateAuthorizationHeader();
req.Headers.Add("Authorization", AuthorizationHeader);
req.Headers.Add("x-ms-date", mxdate);
req.Headers.Add("x-ms-version", storageServiceVersion);
req.ContentType = "application/json";
req.Accept = "application/json;odata=minimalmetadata";
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
}
}
public string generateAuthorizationHeader()
{
mxdate = DateTime.UtcNow.ToString("R");
string canonicalizedResource = $"/{StorageAccount}/Tables('{tablename}')";
string contentType = "application/json";
string stringToSign = $"{requestMethod}\n\n{contentType}\n{mxdate}\n{canonicalizedResource}";
HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(StorageKey));
string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
String authorization = String.Format("{0} {1}:{2}",
"SharedKey",
StorageAccount,
signature
);
return authorization;
}

Get Access token from Spotify api

I'm trying to get a access token from this endpoint using asp.net: https://accounts.spotify.com/api/token
The token i get back has Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}".
When creating my app over att Spotify Developer i stated my Redirect Uri as http://localhost:59486/ which is my Project Url.
What am i doing wrong?
I have borrowed this method from https://hendrikbulens.wordpress.com/2015/01/07/c-and-the-spotify-web-api-part-i/
private async Task<string> GetAccessToken()
{
SpotifyToken token = new SpotifyToken();
string postString = string.Format("grant_type=client_credentials");
byte[] byteArray = Encoding.UTF8.GetBytes(postString);
string url = "https://accounts.spotify.com/api/token";
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.Headers.Add("Authorization", "Basic YjlkZj****************************************jQ2YjM3MjE5MDE=");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
string responseFromServer = reader.ReadToEnd();
token = JsonConvert.DeserializeObject<SpotifyToken>(responseFromServer);
}
}
}
}
return token.access_token;
}
EDIT:
This is my Http request:
spotify.com/api/token HTTP/1.1
Authorization: Basic Yjlk....................5MDE=
Content-Type: application/x-www-form-urlencoded
Host: accounts.spotify.com
Content-Length: 29
Expect: 100-continue
Connection: Keep-Alive
grant_type=client_credentials

World Pay Payment gateway Integration In ASP.Net MVC using C#

string xml = "<?xml version='1.0'? encoding='UTF-8'?><!DOCTYPE paymentService PUBLIC '-//WorldPay//DTD WorldPay PaymentService v1//EN''http://dtd.worldpay.com/paymentService_v1.dtd'><paymentService version='1.4' merchantCode='MYMERCHANTCODE'><submit><order orderCode='RecurringOrderCode'><description>Monthly subscription.</description><amount value='1399' currencyCode='EUR' exponent='2' /><orderContent>Your Original Order Content</orderContent> <paymentDetails><VISA-SSL> <cardNumber>4444333322221111</cardNumber><expiryDate> <date month='09' year='2019'/> </expiryDate> <cardHolderName>J. Shopper</cardHolderName><cvc>123</cvc> <cardAddress> <address> <street>47A Queensbridge Rd</street><postalCode>CB94BQ</postalCode><city>GB</city><countryCode>GB</countryCode><telephoneNumber>+44</telephoneNumber> </address> </cardAddress> </VISA-SSL> <session shopperIPAddress='100.100.100.100' id='0215ui8ib1' /> </paymentDetails></order></submit></paymentService>";
string url = "https://secure-test.worldpay.com/jsp/merchant/xml/paymentService.jsp";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//string s = "id="+Server.UrlEncode(xml);
byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(xml);
req.Method = "POST";
req.ContentType = "text/xml;charset=utf-8";
req.ContentLength = requestBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
string backstr = sr.ReadToEnd();
sr.Close();
res.Close();
return View();
I am using this code to integrate the Worldpay payment gateway API i am getting this error on getting response from line HttpWebResponse res = (HttpWebResponse)req.GetResponse();
the error is -401 Authorization Required
You need to add your credentials to the request, probably HTTP basic auth. Can do it like this:
req.Headers[HttpRequestHeader.Authorization] = "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(<username> + ":" + <password>));

Resources