I am trying to connect to servicebus and getting data from it, it seems since I've got the token I must reuse it evertime I make a request what's wrong with this code?here is the error I've got at the last
line The remote server returned an error: (401) Unauthorized.
//sample usage string mydata1 = string.Format(Constants.myData, brfId);
public static readonly myData= "https://sdgsdg.servicebus.windows.net/sgsdg/gdgsg/{0}";
//sample usage - string agendaByBriefingDetailIdURI = string.Format(Constants.myData2 BriefingID, accessCode);
public static readonly string myData2= "https://sdgsg.servicebus.windows.net/sdg/dgsg/{0}/{1}";
string SCOPE = "http://lalalalala.servicebus.windows.net/";
string WRAP_PASSWORD = "lalalalalala"
string WRAP_USERNAME = "lalalala";
string ACS_NAMESPACE = "lalalalala";
WebClient client = new WebClient();
client.BaseAddress = string.Format("https://{0}.accesscontrol.windows.net", ACS_NAMESPACE);
NameValueCollection values = new NameValueCollection();
values.Add("wrap_name", WRAP_USERNAME);
values.Add("wrap_password", WRAP_PASSWORD);
values.Add("wrap_scope", SCOPE);
// WebClient takes care of the URL Encoding
byte[] responseBytes = client.UploadValues("WRAPv0.9", "POST", values);
// the raw response from ACS
string response = Encoding.UTF8.GetString(responseBytes);
string token = response.Split('&').Single(x => x.StartsWith("wrap_access_token=", StringComparison.OrdinalIgnoreCase)).Split('=')[1];
string decodedToken = HttpUtility.UrlDecode(token);
string.Format("WRAP access_token=\"{0}\"", HttpUtility.UrlDecode(token));
WebClient webClient = new WebClient();
webClient.Headers["Authorization"] = string.Format("WRAP access_token=\"{0}\"", HttpUtility.UrlDecode(token));
string returnString = webClient.DownloadString(string.Format(mystaticre, 10));
Related
I'm working with rest delete API. It is working fine but its returning No Content in every success response. I have given too much time but problem is still persist. Could you please correct me where I am wrong with code. I searched and implemented same but I don't know at what point I am making mistake.
public static string DeleteMessage(String queueName, string popreceipt, string messageid)
{
string requestMethod = "DELETE";
String urlPath = String.Format("{0}/messages/{1}?popreceipt={2}", queueName, Uri.EscapeDataString(messageid), Uri.EscapeDataString(popreceipt));
String storageServiceVersion = "2017-11-09";
String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format(
"x-ms-date:{0}\nx-ms-version:{1}",
dateInRfc1123Format,
storageServiceVersion);
//String canonicalizedResource = String.Format("/{0}/{1}", StorageAccountName, urlPath);
String canonicalizedResource = string.Format("/{0}/{1}/messages/{2}\npopreceipt:{3}", StorageAccountName, queueName, messageid, popreceipt);
String stringToSign = String.Format(
"{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}",
requestMethod,
canonicalizedHeaders,
canonicalizedResource);
String authorizationHeader = CreateAuthorizationHeader(stringToSign);
Uri uri = new Uri("https://" + StorageAccountName + ".queue.azure.com/" + urlPath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = requestMethod;
request.Headers.Add("x-ms-date", dateInRfc1123Format);
request.Headers.Add("x-ms-version", storageServiceVersion);
request.Headers.Add("Authorization", authorizationHeader);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
return response.StatusCode.ToString();
}
}
public static String CreateAuthorizationHeader(String canonicalizedString)
{
String signature = String.Empty;
using (HMACSHA256 hmacSha256 = new HMACSHA256(Convert.FromBase64String(StorageAccountKey)))
{
Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(canonicalizedString);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
String authorizationHeader = String.Format(
CultureInfo.InvariantCulture,
"{0} {1}:{2}",
"SharedKey",
StorageAccountName,
signature
);
return authorizationHeader;
}
This is expected behavior. Delete Message operation is supposed to return no content. From the documentation here:
Status code
A successful operation returns status code 204 (No
Content).
As an addition to Gaurav's answer: deleting a message is not the same as getting or dequeuing a message. What would you expect calling DELETE to return?
According to MDN (DELETE - responses):
If a DELETE method is successfully applied, there are several response status codes possible:
A 202 (Accepted) status code if the action will likely succeed but has not yet been enacted.
A 204 (No Content) status code if the action has been enacted and no further information is to be supplied.
A 200 (OK) status code if the action has been enacted and the response message includes a representation describing the status.
I am using this great method, found in this article https://codingstill.com/2016/01/verify-jwt-token-signed-with-rs256-using-the-public-key/#comment-3232, to validate my Azure idToken, which is signed with RS256.
I noticed that Azure AD changes the public key in a period of time. By reading this article, https://nicksnettravels.builttoroam.com/post-2017-01-24-verifying-azure-active-directory-jwt-tokens-aspx. Therefore, I used HttpClient (c#) to obtain the public key from the URL below, every time when I need to validate the token.
https://login.microsoftonline.com/{TenantId}/discovery/v2.0/keys?appid={AppId}
I did get the result of the public key, which is a string array in x5c key. Below is my code:
public static string GetPublicKeyAsync(string kid)
{
using (var client = new HttpClient())
{
HttpResponseMessage response = client.GetAsync("https://login.microsoftonline.com/{TenantId}/discovery/v2.0/keys?appid={AppId}").Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
// by calling .Result you are synchronously reading the result
string responseBody = responseContent.ReadAsStringAsync().Result;
JObject json = JObject.Parse(responseBody);
string c = json["keys"].ToString();
List<ADPublic> allPublicKeys = JsonConvert.DeserializeObject<List<ADPublic>>(json["keys"].ToString());
foreach (ADPublic key in allPublicKeys)
{
if (key.kid == kid)
{
string certificateString = key.x5c[0];
var certificate = new X509Certificate2(Convert.FromBase64String(certificateString));
string pkey = Convert.ToBase64String(certificate.PublicKey.EncodedKeyValue.RawData);
var x509SecurityKey = new X509SecurityKey(certificate)
{
KeyId = key.kid
};
return pkey;
}
}
}
return null;
}
}
When I pass my public key over to the validation method. I always get an error at the line (PublicKeyFactory.CreateKey(keyBytes) method ):
Please refer to the verify method I mentioned in the beginning of this question for the code below:
// call my get public key function...
string key = GetPublicKeyAsync(headerData["kid"].ToString());
var keyBytes = Convert.FromBase64String(key); // your key here
**AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);**
Unknown object in GetInstance: Org.BouncyCastle.Asn1.DerInteger Parameter name: obj
I think I am almost there, but missing the last part, could you please help? Thank you very much!
I got the same error when using certificate.PublicKey.EncodedKeyValue.RawData to get the public key. I referred to this issue and finally succeeded.
The code shows getting AsymmetricKeyParameter from x5c string. Decode(...) function is referred to in the article.
string token = "<the token that you want to verify>";
string certificateString = "<the first x5c of the first key from https://login.microsoftonline.com/{TenantId}/discovery/v2.0/keys?appid={AppId}>";
byte[] buffer = Convert.FromBase64String(certificateString);
X509CertificateParser parser = new X509CertificateParser();
var _certificate = parser.ReadCertificate(buffer);
AsymmetricKeyParameter publicKey = _certificate.GetPublicKey();
string result = Decode(token, publicKey);
Console.WriteLine("result: " + result);
I wish to send sms through my java application using some third party API. While running the below code snippet with my api credentials (variable 'type' contains the url and the 'params' hold the parameters of the message like sender, receiver,message etc...), it shows Authentication failure while getting the response back. But using the same credentials in browser, it works properly and sends message. Please help me in figuring out the reason for the authentication failure.
uri = new URI( type, params , null );
URL url = uri.toURL();
HttpURLConnection conn;
conn= (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responseCode = conn.getResponseCode();
System.out.println(" The Response Code after Sending the SMS : "+responseCode);
InputStream isr = ((responseCode>= 200)&&(responseCode< 300)) ? conn.getInputStream() : conn.getErrorStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(isr));
String line;
StringBuilder result = new StringBuilder("");
while((line = rd.readLine()) != null)
{
result.append(line);
}
String response = result.toString();
System.out.println("The Response after Sending the SMS : "+response);
I am using Spring Integration in my project. I am trying to execute a rest service which takes multipart/formdata input parameters. I am using int-http:outbound-gateway to execute rest service. The following is the code:
<int:channel id="PQcreateAttachment-Rest-Channel" />
<int:chain input-channel="PQcreateAttachment-Rest-Channel" output-channel="PQcreateAttachment-StoredProcedure-Router" >
<int:header-filter header-names="accept-encoding"/>
<int:service-activator ref="httpOutboundGatewayHandler" method="buildMultipartHttpOutboundGatewayRequest" />
<int-http:outbound-gateway url-expression="headers.restResourceUrl"
http-method-expression="headers.httpMethod"
extract-request-payload="true"
>
</int-http:outbound-gateway>
<int:service-activator ref="msgHandler" method="buildMessageFromExtSysResponse" />
</int:chain>
But I am getting the following error when I execute the above code.
Caused by: org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.integration.message.GenericMessage] and content type [application/x-java-serialized-object]
at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:665)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:481)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:460)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:409)
at org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler.handleRequestMessage(HttpRequestExecutingMessageHandler.java:372)
... 121 more
Here is the java code that prepares my multipart request:
public Message<?> buildMultipartHttpOutboundGatewayRequest(Message<?> inMessage) throws Exception{
logger.debug(" ************** buildMultipartHttpOutboundGatewayRequest Start *************************");
String inMsgPayload = (String)inMessage.getPayload();
SOAXml soaXml = parseSOAXml(inMsgPayload);
String restURL = null;
String contentType = null;
String acceptHdr = null;
String userId = null;
String password = null;
String businessAreaName = null;
String typeName = null;
String attachmentLocation = null;
String httpMethod = null;
Message<?> outMessage = null;
MessageHeaders inMsgHdrs = null;
MessageBuilder<?> msgBuild = null;
String authorization = null;
//TODO: File location needs to be changed to standard one
String fileLocation = "C:\\source.xml";
//if we reach here means, it is AWD system
restURL = getAwdSOAService(soaXml);
Document document = XmlParserUtil.convertString2Document(inMsgPayload);
userId = XmlParserUtil.getNodeValue(document,"//userId");
password = XmlParserUtil.getNodeValue(document,"//PQcreateAttachment/password");
businessAreaName = XmlParserUtil.getNodeValue(document,"//businessAreaName");
typeName = XmlParserUtil.getNodeValue(document,"//typeName");
httpMethod = XmlParserUtil.getNodeValue(document,"//METHOD");
attachmentLocation = XmlParserUtil.getNodeValue(document,"//attachmentLocation");
//Construct source xml
//Creating document
Document sourceDocument = DocumentHelper.createDocument();
Element sourceInstance = sourceDocument.addElement("createSourceInstance");
sourceInstance.addAttribute("xmlns", "http://www.dsttechnologies.com/awd/rest/v1");
Element orderItem=sourceInstance.addElement("businessAreaName");
orderItem.setText("SAMPLEBA");
Element orderItemDesc=sourceInstance.addElement("typeName");
orderItemDesc.setText("SAMPLEST");
// create source xml file
XmlParserUtil.createXMLFileUsingDOM4J(sourceDocument, fileLocation);
authorization = getBasicAuthorization(userId,password);
Resource source = new ClassPathResource(fileLocation);
Resource attachment = new ClassPathResource(attachmentLocation);
Map<String, Object> multipartMap = new HashMap<String, Object>();
multipartMap.put("source", source);
multipartMap.put("attachment", attachment);
logger.info("Created multipart request: " + multipartMap);
inMessage = buildMessageForMultipart(multipartMap);
// contentType = csProps.getHttpAwdContentTypeValue();
acceptHdr = csProps.getHttpAwdAcceptTypeValue() ;
// authorization = getBasicAuthorization(soaXml.getUserid(),decriptPassword(soaXml.getPassword()));
inMsgHdrs = inMessage.getHeaders();
msgBuild = MessageBuilder.withPayload(inMessage).copyHeaders(inMsgHdrs);
msgBuild.removeHeader("Content-Encoding");
msgBuild.removeHeader("accept-encoding");
msgBuild.setHeader(csProps.getHttpUrlHdr(), restURL);
msgBuild.setHeader(csProps.getHttpMethodHdr(), httpMethod);
msgBuild.setHeader(csProps.getHttpAuthorizatonHdr(),authorization );
// msgBuild.setHeader(csProps.getHttpContentTypeHdr(), contentType);
// msgBuild.setHeader(csProps.getHttpAcceptTypeHdr(),acceptHdr);
outMessage = msgBuild.build();
logger.debug(" ************** buildHttpOutboundGatewayRequest End*************************");
logger.debug(outMessage);
logger.debug(" ************************************************************************");
return outMessage;
}
Any ideas on what's wrong here?
Your problem is because you wrap one message to another.
What your buildMessageForMultipart(multipartMap); does?
I'm sure the simple map as payload and those header would be enough.
Not sure what is the point to wrap one message to another.
I called a REST API with the following JSON string returned:
"{\"profile\":[{\"name\":\"city\",\"rowCount\":1,\"location\": ............
I tried to remove escape character with the following code before I deserialize it:
jsonString = jsonString.Replace(#"\", " ");
But then when I deserialize it, it throws an input string was not in a correct format:
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
The following is the complete code:
public static SearchRootObject obj()
{
String url = Glare.searchUrl;
string jsonString = "";
// Create the web request
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
// Get response
var response = request.GetResponse();
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
jsonString = jsonString + readStream.ReadToEnd();
jsonString = jsonString.Replace(#"\", " ");
// A C# object representation of deserialized JSON string
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
return obj;
}
After switching to use JavaScriptSerializer() to deserialize JSON string , I realized that I have an int type property in my object for a decimal value in the JSON string. I changed int to double, and this solved my problem. Both JsonConvert.DeserializeObject<> and JavaScriptSerializer() handle escape character. There's no need to remove escape character.
I replaced the following codes:
jsonString = jsonString.Replace(#"\", " ");
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
return obj;
With:
return new JavaScriptSerializer().Deserialize<SearchObj.RootObject>(jsonString);