RestAssured delete method returns status code 405 - rest-assured

RestAssured Delete method returns status code as 405 but when I try from Postman it returns 202 ( which is as expected )
In Postman :
Method : DELETE
PATH : .../rest/end1/end2?name=xyz
Code :
String name = "xyz";
String baseURI = System.getProperty("environmentPathUrl");
String path = "/rest/end1";
public void deleteName(String baseURI, String path, String name) {
String Resp = RestAssured.given().baseUri(baseURI).basePath(path).queryParam("name", name).when()
.delete("/end2").then().assertThat().statusCode(202).and().extract().response().asString();
System.out.println("Response is\t" + Resp);
}

You're making a mistake in the Rest Assured code, Add a .log().all() after given() to see the request traffic and you will be able to see your mistake
I've made few changes to the code and this should work for you hopefully
public static void deleteName() {
String name = "xyz";
String baseURI = System.getProperty("environmentPathUrl");
String path = "/rest/end1";
String Resp = RestAssured.given().log().all().baseUri(baseURI).basePath(path).queryParam("name", name).when()
.delete("/end2").then().assertThat().statusCode(202).and().extract().response().asString();
System.out.println("Response is\t" + Resp);
}
public static void main(String[] args) {
deleteName();
}

Related

How to pass request param using feign client?

I am currentlt using Feign Client to call an end point to get outlook mails. But the request parameter are not passing correctly in the api.
#FeignClient(name = "email", url = "${BASE.URI}")
public interface EmailClient {
#GetMapping("/mailfolders/Inbox/messages")
EmailRequestNew getMessages(#RequestHeader HashMap<String, Object> headers,
#RequestParam String filter);
Through service I am calling this Email client to get Mails and passing the filter as
below where from and to are datetime
String param = "$filter=receivedDateTime ge " + from + " and receivedDateTime lt " + to +
"&$expand=singleValueExtendedProperties($filter=id+eq+'String+0x0070')";
but the actual api which are calling is not accurate
assume BASE.URI is something like (10.0.0.120:8080)
https://BASE.URI/mailfolders/Inbox/messages?param=%24filter%3DreceivedDateTime%20ge%202022-11-18T05%3A32%3A56Z%20and%20receivedDateTime%20lt%202022-11-18T09%3A32%3A56Z%26%24expand%3DsingleValueExtendedProperties%28%24filter%3Did%20eq%20%27String%200x0070%27%29
but I want my complete api to be like below when I hardcoded the Request param in the GetMapping
(#GetMapping("/mailfolders/Inbox/messages$filter=receivedDateTime ge 2022-11-18T05:32:56Z and receivedDateTime lt 2022-11-18T09:32:56Z&$expand=singleValueExtendedProperties($filter=id+eq+'String+0x0070')"))
https://dev-api.bhspecialty.com/xchange/v1/mailfolders/Inbox/messages?%24filter=receivedDateTime%20ge%202022-11-18T04:16:58Z%20and%20receivedDateTime%20lt%202022-11-18T08:16:58Z&%24expand=singleValueExtendedProperties($filter=id+eq+'String+0x0070')
How can I achive this.
I tried URL Encoding/Decoding but it is not working.
Example:
URLDecoder.decode(param,"UTF-8")
UriUtils.encodePath(param, "UTF-8");
But nothing is working.
So I was able to do this by creating a RequestInterceptor and then decoding the URI and also change my EmailClient to take PathVariable instead of RequestParam.
#GetMapping(value = "/mailfolders/Inbox/messages?$expand={expand}&$filter={filter}", consumes = MediaType.APPLICATION_JSON_VALUE)
EmailRequestNew getMessages(#RequestHeader HashMap<String, Object> headers,
#PathVariable String filter, #PathVariable String expand);
#Component
public class FeignClientRequestInterceptor implements RequestInterceptor {
private static Logger logger = LogManager.getLogger(FeignClientRequestInterceptor.class);
#Override
public void apply(RequestTemplate template) {
try {
template.uri(URLDecoder.decode(template.request().url(), "UTF-8"));
logger.info("FeignClientRequestInterceptor: " + URLDecoder.decode(template.request().url(), "UTF-8") );
} catch (UnsupportedEncodingException e) {
logger.log(Level.INFO,"Error in FeignClientRequestInterceptor: " + template.request().url() );
throw new RuntimeException(e);
}
}
}
This is the final uri which is created:
https://BASE.URI/mailfolders/Inbox/messages?%24expand=singleValueExtendedProperties($filter=id%20eq%20'String%200x0070')&%24filter=receivedDateTime%20ge%202022-11-21T08:17:59Z%20and%20receivedDateTime%20lt%202022-11-21T12:17:59Z

Yahoo Fantasy Sports API

Is anyone still using the Yahoo Fantasy Sports API? I had an app that worked last year, have not changed my code at all, and now it is returning a 500 internal error when I try to run it.
I used to test things through the YQL Console, but that is no longer available.
https://developer.yahoo.com/yql/
Anyone know how to make authenticated requests on that site above?
My feeling is that Yahoo has just discontinued support for their FantasySports API, I will have to look for other solutions I think.
Wondering if anyone else out there used this API previously and is or is not still having success with it.
I figured out how to use C# core and Yahoo's API. Huge thanks to this guy
Get your api key etc from yahoo.
Make a controller action that redirects to the request URL something like this:
public IActionResult Test()
{
yo.yKey = {your Yahoo API key};
yo.ySecret = {your Yahoo API secret};
yo.returnUrl = {your return URL as set in the API setup, example "https://website.com/home/apisuccess"};
var redirectUrl = "https://api.login.yahoo.com/oauth2/request_auth?client_id=" + yo.yKey + "&redirect_uri=" + yo.returnUrl + "&response_type=code&language=en-us";
return Redirect(redirectUrl);
}
This will send you to a site that authenticates with Yahoo. Upon successful authentication it is going to send you to your redirect site with a string parameter called code, in the example it would be home/apisuccess, so that controller action should look like this:
public async Task<IActionResult> ApiSuccess(string code)
{
List<string> msgs = new List<string>(); //This list just for testing
/*Exchange authorization code for Access Token by sending Post Request*/
Uri address = new Uri("https://api.login.yahoo.com/oauth2/get_token");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] headerByte = System.Text.Encoding.UTF8.GetBytes(_yKey + ":" + _ySecret);
string headerString = System.Convert.ToBase64String(headerByte);
request.Headers["Authorization"] = "Basic " + headerString;
/*Create the data we want to send*/
StringBuilder data = new StringBuilder();
data.Append("client_id=" + _yKey);
data.Append("&client_secret=" + _ySecret);
data.Append("&redirect_uri=" + _returnUrl);
data.Append("&code=" + code);
data.Append("&grant_type=authorization_code");
//Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = await request.GetRequestStreamAsync())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
var vM = new yOauthResponse();
string responseFromServer = "";
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
msgs.Add("Into response");
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
responseFromServer = reader.ReadToEnd();
msgs.Add(responseFromServer.ToString());
vM = JsonConvert.DeserializeObject<yOauthResponse>(responseFromServer.ToString());
}
}
catch (Exception ex)
{
msgs.Add("Error Occured");
}
ViewData["Message"] = msgs;
return View(vM);
}
Note that I used a json deserializer of this model, but you can do whatever you want with the response to get the data you need out of it. This is my json model:
public class yOauthResponse
{
[JsonProperty(PropertyName = "access_token")]
public string accessToken { get; set; }
[JsonProperty(PropertyName = "xoauth_yahoo_guid")]
public string xoauthYahooGuid { get; set; }
[JsonProperty(PropertyName = "refresh_token")]
public string refreshToken { get; set; }
[JsonProperty(PropertyName = "token_type")]
public string tokenType { get; set; }
[JsonProperty(PropertyName = "expires_in")]
public string expiresIn { get; set; }
}
Once you have that data, the main thing you need is the access_token, and use it as follows in a controller action:
//simple code above removed
var client = new HttpClient()
{
BaseAddress = new Uri({your request string to make API calls})
};
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
HttpResponseMessage response = await client.GetAsync(requestUri);
if (response.IsSuccessStatusCode)
{
//do what you will with the response....
}
//rest of simple code
Hopefully this helps someone somewhere. Happy coding!

Google Apps Marketplace UpgradeableApp API Getting "code":500,"message":"Backend Error"

We are in process of migration of Google Apps Marketplace listing using the UpgradeableApp API resource but when calling
PUT https://www.googleapis.com/appsmarket/v2/upgradableApp/listingID/cwsID/domain
with signed request getting error:
81 {"error":{"errors":[{"domain":"global","reason":"backendError","message":"Backend Error"}],"code":500,"message":"Backend Error"}} 0
What i am doing wrong....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OAuth.Net.Common;
using OAuth.Net.Components;
using System.IO;
using System.Net;
using System.Security.Cryptography;
namespace Google_UpgradeableApi_Console
{
class Program
{
private static readonly ISigningProvider SigningProvider = new HmacSha1SigningProvider();
static void Main(string[] args)
{
// Setup the variables necessary to create the OAuth 1.0 signature and make the request
string httpMethod = "PUT";
string listingID = "xxxx+23453809800066606066";
string cwsID = "bbmagicjcjeblpadhhnnjahfbbbbhjk";
string domain = "xyz.com";
Uri url = new Uri(String.Format("{0}/{1}/{2}/{3}", "https://www.googleapis.com/appsmarket/v2/upgradableApp", listingID, cwsID, domain));
string consumerKey = "xyz.apps.googleusercontent.com";
string secret = "gt2sj34656U687f8qj677+GK";
string body = "";
MemoryStream requestBody = null;
string signatureMethod = SigningProvider.SignatureMethod;
HttpWebResponse response = null;
// Set the Nonce and Timestamp parameters
string nonce = getNonce();
string timestamp = getTimestamp();
// Set the request body if making a POST or PUT request
if (httpMethod == "POST" || httpMethod == "PUT")
{
requestBody = new MemoryStream(Encoding.UTF8.GetBytes(body));
}
// Create the OAuth parameter name/value pair dictionary
Dictionary<string, string> oauthParams = new Dictionary<string, string>
{
{ "oauth_consumer_key", consumerKey },
{ "oauth_signature_method", signatureMethod },
{ "oauth_timestamp", timestamp },
{ "oauth_nonce", nonce },
};
// Get the OAuth 1.0 Signature
string signature = generateSignature(httpMethod, url, oauthParams, requestBody, secret);
Console.WriteLine("OAuth 1.0 Signature = " + signature + "\r\n\r\n");
// Add the oauth_signature parameter to the set of OAuth Parameters
IEnumerable<KeyValuePair<string, string>> allParams = oauthParams.Union(new[]
{
new KeyValuePair<string, string>("oauth_signature", signature)
});
// Defines a query that produces a set of: keyname="URL-encoded(value)"
IEnumerable<string> encodedParams = from param in allParams
select param.Key + "=\"" + Uri.EscapeDataString(param.Value) + "\"";
// Join all encoded parameters with a comma delimiter and convert to a string
string stringParams = String.Join(",", encodedParams);
// Build the X-Authorization request header
string xauth = String.Format("X-Authorization: OAuth realm=\"{0}\",{1}", url, stringParams);
Console.WriteLine("X-Authorization request header: \r\n" + xauth + "\r\n\r\n");
try
{
// Setup the Request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = httpMethod;
request.Headers.Add(xauth);
// Set the request body if making a POST or PUT request
if (httpMethod == "POST" || httpMethod == "PUT")
{
byte[] dataArray = Encoding.UTF8.GetBytes(body);
request.ContentLength = dataArray.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(dataArray, 0, dataArray.Length);
requestStream.Close();
}
// Send Request & Get Response
response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// Get the response stream and write to console
string json = reader.ReadToEnd();
Console.WriteLine("Successful Response: \r\n" + json);
}
}
catch (WebException e)
{
// This exception will be raised if the server didn't return 200 - OK
// Retrieve more information about the error
if (e.Response != null)
{
using (HttpWebResponse err = (HttpWebResponse)e.Response)
{
Console.WriteLine("The server returned '{0}' with the status code '{1} ({2:d})'.",
err.StatusDescription, err.StatusCode, err.StatusCode);
}
}
}
finally
{
if (response != null) { response.Close(); }
}
Console.ReadLine();
}
#region Helper Functions
/// <summary>
/// Generates a random nonce.
/// </summary>
/// <returns>A unique identifier for the request.</returns>
private static string getNonce()
{
string rtn = Path.GetRandomFileName() + Path.GetRandomFileName() + Path.GetRandomFileName();
rtn = rtn.Replace(".", "");
if (rtn.Length > 32)
return rtn.Substring(0, 32);
else
return rtn;
}
/// <summary>
/// Generates an integer representing the number of seconds since the unix epoch using the
/// UTC date/time of the request.
/// </summary>
/// <returns>A timestamp for the request.</returns>
private static string getTimestamp()
{
return ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString();
}
/// <summary>
/// Generates an OAuth 1.0 signature.
/// </summary>
/// <param name="httpMethod">The HTTP method of the request.</param>
/// <param name="url">The URI of the request.</param>
/// <param name="oauthParams">The associative set of signable oauth parameters.</param>
/// <param name="requestBody">A stream containing the serialized message body.</param>
/// <param name="secret">Alphanumeric string used to validate the identity of the education partner (Private Key).</param>
/// <returns>A string containing the BASE64-encoded signature digest.</returns>
private static string generateSignature(
string httpMethod,
Uri url,
IDictionary<string, string> oauthParams,
Stream requestBody,
string secret
)
{
// Ensure the HTTP Method is upper-cased
httpMethod = httpMethod.ToUpper();
// Construct the URL-encoded OAuth parameter portion of the signature base string
string encodedParams = normalizeParams(httpMethod, url, oauthParams, requestBody);
// URL-encode the relative URL
string encodedUri = Uri.EscapeDataString(url.AbsolutePath);
// Build the signature base string to be signed with the Consumer Secret
string baseString = String.Format("{0}&{1}&{2}", httpMethod, encodedUri, encodedParams);
//return generateCmac(secret, baseString);
return generateHMAC(secret, baseString);
}
/// <summary>
/// Normalizes all oauth signable parameters and url query parameters according to OAuth 1.0.
/// </summary>
/// <param name="httpMethod">The upper-cased HTTP method.</param>
/// <param name="url">The request URL.</param>
/// <param name="oauthParams">The associative set of signable oauth parameters.</param>
/// <param name="requestBody">A stream containing the serialized message body.</param>
/// <returns>A string containing normalized and encoded OAuth parameters.</returns>
private static string normalizeParams(
string httpMethod,
Uri url,
IEnumerable<KeyValuePair<string, string>> oauthParams,
Stream requestBody
)
{
IEnumerable<KeyValuePair<string, string>> kvpParams = oauthParams;
// Place any Query String parameters into a key value pair using equals ("=") to mark
// the key/value relationship and join each paramter with an ampersand ("&")
if (!String.IsNullOrWhiteSpace(url.Query))
{
IEnumerable<KeyValuePair<string, string>> queryParams =
from p in url.Query.Substring(1).Split('&').AsEnumerable()
let key = Uri.EscapeDataString(p.Substring(0, p.IndexOf("=")))
let value = Uri.EscapeDataString(p.Substring(p.IndexOf("=") + 1))
select new KeyValuePair<string, string>(key, value);
kvpParams = kvpParams.Union(queryParams);
}
// Include the body parameter if dealing with a POST or PUT request
if (httpMethod == "POST" || httpMethod == "PUT")
{
MemoryStream ms = new MemoryStream();
requestBody.CopyTo(ms);
byte[] bodyBytes = ms.ToArray();
string body = Convert.ToBase64String(bodyBytes, Base64FormattingOptions.None);
body = Uri.EscapeDataString(body);
kvpParams = kvpParams.Union(new[]
{
new KeyValuePair<string, string>("body", Uri.EscapeDataString(body))
});
}
// Sort the parameters in lexicographical order, 1st by Key then by Value; separate with ("=")
IEnumerable<string> sortedParams =
from p in kvpParams
orderby p.Key ascending, p.Value ascending
select p.Key + "=" + p.Value;
// Add the ampersand delimiter and then URL-encode the equals ("%3D") and ampersand ("%26")
string stringParams = String.Join("&", sortedParams);
string encodedParams = Uri.EscapeDataString(stringParams);
return encodedParams;
}
private static string generateHMAC(string _key, string _msg)
{
string message;
string key;
key = _key;
message = _msg;
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(key);
HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);
byte[] messageBytes = encoding.GetBytes(message);
byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
return ByteToString(hashmessage);
}
public static string ByteToString(byte[] buff)
{
string sbinary = "";
for (int i = 0; i < buff.Length; i++)
{
sbinary += buff[i].ToString("X2"); // hex format
}
return (sbinary);
}
#endregion // Helper Functions
}
}
There are many reasons behind this, but first please check the URL must be signed with OAuth1 (not OAuth2) and must have valid values for the other parameters. The error reporting may make throw the same error for a lot of reason, but make sure your setup is correct and make sure your app is published on new chrome apps marketplace. Make sure you've submitted the Google Apps Marketplace Listing Review Request form here:
https://docs.google.com/forms/d/14QOb8PbSLKDgwIp8Zv-luoAAVurPXUqtzL0Hgikp3rk/viewform
After all is finished and google approved (you will get an email) your app then make call to UpgradeableApp API with oAuth 1.0 sign request, Here is an example you can see how to do it.
http://www.codeproject.com/Tips/359144/Legged-OAuth-Authentication-in-NET-Csharp
Hope that helps

401 (Unauthorized) when accessing JIRA API with query string

I'm following the tutorial found here to create a JWT token to access the REST API of JIRA. I do not have any problem accessing endpoints without passing query strings like /rest/api/2/project and /rest/api/2/issue/ISSUE-KEY but I get 401 Unauthorized when trying to pass query strings, say /rest/api/2/user/assignable/search?project=PROJECT-KEY
I'm guessing I'm missing out something, specificially the generation of canonical URL,
Here is the code that generates the get request and JWT token:
#Override
public CloseableHttpResponse get(String url) throws HttpException,
IOException, NoSuchAlgorithmException, ParseException,
JOSEException {
CloseableHttpClient client = HttpClientBuilder.create()
.setUserAgent("Kevin 6.9").build();
String token = createToken(url, JIRAClient.Method.GET);
HttpGet method = new HttpGet(jwt.getBaseUrl() + url);
method.setHeader("Authorization", "JWT " + token);
return client.execute(method);
}
/**
* Create JWT token
*
* #return
* #throws UnsupportedEncodingException
* #throws NoSuchAlgorithmException
*/
private String createToken(String apiPath, JIRAClient.Method method)
throws UnsupportedEncodingException, NoSuchAlgorithmException {
long issuedAt = System.currentTimeMillis() / 1000L;
long expiresAt = issuedAt + 1000L;
String httpMethod = method.toString();
System.out.println(httpMethod);
String contextPath = "/jira";
JwtJsonBuilder jwtBuilder = new JsonSmartJwtJsonBuilder()
.issuedAt(issuedAt).expirationTime(expiresAt)
.issuer(jwt.getKey());
HashMap<String, String[]> parameters = new HashMap<String, String[]>();
CanonicalHttpUriRequest canonical = new CanonicalHttpUriRequest(
httpMethod, apiPath, contextPath, parameters);
System.out.println("Canonical : " + canonical.getRelativePath());
JwtClaimsBuilder.appendHttpRequestClaims(jwtBuilder, canonical);
JwtWriterFactory jwtWriterFactory = new NimbusJwtWriterFactory();
String jwtbuilt = jwtBuilder.build();
String jwtToken = jwtWriterFactory.macSigningWriter(
SigningAlgorithm.HS256, jwt.getSharedSecret()).jsonToJwt(
jwtbuilt);
return jwtToken;
}
Note that I am passing an empty HashMap<String, String[]> to the CanonicalHttpUriRequest... is this correct?
Apparently the Map<String, String[]> is required to generate the appropriate canonical URI.
Note that I am passing an empty HashMap<String, String[]> to the
CanonicalHttpUriRequest... is this correct?
I modified my method signature so I can pass it as a parameter. Note: createQueryString is a method inside my class that manually creates the query String from the parameter map.
#Override
public CloseableHttpResponse get(String url,
#SuppressWarnings("rawtypes") Map parameters) throws Exception {
CloseableHttpClient client = HttpClientBuilder.create()
.setUserAgent("Kevin 5.0").build();
String token = createToken(url, JIRAClient.Method.GET, parameters);
HttpGet method = new HttpGet(jwt.getBaseUrl() + url
+ createQueryString(parameters));
method.setHeader("Authorization", "JWT " + token);
return client.execute(method);
}
And it works.
#Test
public void testJQL() throws Exception {
HashMap param = new HashMap();
param.put("jql", new String[] {"project=COR"});
param.put("startAt", new String[] {"0"});
HttpResponse response = client.get("/rest/api/2/search", param);
Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
}

Invalid signature when connecting to VitaDock API with Scribe library

I am using grails plugin: oauth 2.1.0 to connect to oauth APIs.
Vitadock requires HMACSHA256 to encode base signature string, so I created a HMACSha256SignatureService.groovy to do it and customize TargetScaleApi.groovy
HMACSha256SignatureService.groovy
import javax.crypto.*
import javax.crypto.spec.*
import org.apache.commons.codec.binary.*
import org.scribe.exceptions.*
import org.scribe.services.SignatureService
import org.scribe.utils.*
public class HMACSha256SignatureService implements SignatureService {
private static final String EMPTY_STRING = "";
private static final String CARRIAGE_RETURN = "\r\n";
private static final String UTF8 = "UTF-8";
private static final String HMAC_SHA256 = "HMACSHA256";
private static final String METHOD = "HMAC-SHA256";
/**
* {#inheritDoc}
*/
public String getSignature(String baseString, String apiSecret, String tokenSecret) {
try {
println baseString
Preconditions.checkEmptyString(baseString, "Base string cant be null or empty string");
Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty string");
return doSign(baseString, OAuthEncoder.encode(apiSecret) + '&' + OAuthEncoder.encode(tokenSecret));
}
catch (Exception e) {
throw new OAuthSignatureException(baseString, e);
}
}
private String doSign(String toSign, String keyString) throws Exception {
SecretKeySpec key = new SecretKeySpec((keyString).getBytes(UTF8), HMAC_SHA256);
Mac mac = Mac.getInstance(HMAC_SHA256);
mac.init(key);
byte[] bytes = mac.doFinal(toSign.getBytes(UTF8));
String a = new String(Base64.encodeBase64(bytes)).replace(CARRIAGE_RETURN, EMPTY_STRING)
println a
return a;
}
public String getSignatureMethod() {
return METHOD;
}
}
TargetScaleApi.groovy
import org.scribe.builder.api.DefaultApi10a
import org.scribe.model.Token
import org.scribe.services.SignatureService
class TargetScaleApi extends DefaultApi10a {
private static final String AUTHORIZE_URL = "https://vitacloud.medisanaspace.com/auth?oauth_token=%s"
#Override
public String getAccessTokenEndpoint() {
return "https://vitacloud.medisanaspace.com/auth/accesses/verify"
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return String.format(AUTHORIZE_URL, requestToken.getToken());
}
#Override
public String getRequestTokenEndpoint() {
return "https://vitacloud.medisanaspace.com/auth/unauthorizedaccesses"
}
#Override
public SignatureService getSignatureService() {
return new HMACSha256SignatureService();
}
}
But I received a error message: invalid signature.
<b>message</b>Invalid signature (jBbmlITCOBuIN3KfVB8glzv1sftrx1v7MvNyAJkiGTU%3D, expected: Ia21vjqskdBXrRE%2BngpHqaP4GJV3hfUGOt0ksGVcgk0%3D) [Base Parameter String: oauth_consumer_key=V5BiK7kzVcefBVfJ1htu13vfreWZNDPnkzx4DG67UBG6lNe0dZ1DUClKk5XM1Y1L&oauth_nonce=897870535&oauth_signature_method=HMAC-SHA256&oauth_timestamp=1372069427&oauth_version=1.0, Base Signature String: POST&https%3A%2F%2Fvitacloud.medisanaspace.com%2Fauth%2Funauthorizedaccesses&oauth_consumer_key%3DV5BiK7kzVcefBVfJ1htu13vfreWZNDPnkzx4DG67UBG6lNe0dZ1DUClKk5XM1Y1L%26oauth_nonce%3D897870535%26oauth_signature_method%3DHMAC-SHA256%26oauth_timestamp%3D1372069427%26oauth_version%3D1.0] [authorization = OAuth oauth_callback="http%3A%2F%2Flocal.mydatainnet.axonactive.vn%3A8080%2Faa-mdin-web-client-2.0.1%2Foauth%2Fcallback%3Fprovider%3Dtargetscale", oauth_signature="jBbmlITCOBuIN3KfVB8glzv1sftrx1v7MvNyAJkiGTU%3D", oauth_version="1.0", oauth_nonce="897870535", oauth_signature_method="HMAC-SHA256", oauth_consumer_key="V5BiK7kzVcefBVfJ1htu13vfreWZNDPnkzx4DG67UBG6lNe0dZ1DUClKk5XM1Y1L", oauth_timestamp="1372069427", content-type = application/x-www-form-urlencoded, cache-control = no-cache, pragma = no-cache, user-agent = Java/1.6.0_25, host = vitacloud.medisanaspace.com, accept = text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2, connection = keep-alive, content-length = 0, ]
Thanks for any help
Hang Dinh
I believe that VitaDock implements Oauth 1.0 (https://github.com/Medisana/vitadock-api/wiki/Definitions). If you are using a plugin geared towards oauth 2.1.0 maybe that could be the source of the error.

Resources