When i use authorization in headers for rest assured by bassing token variable giving "File Not Found" error. And if hardcode the token in headers then it's working successfully. Can anyone help me out what can be the issue. Below is my code,
public static void getIndentId() throws IOException {
if(indentId == null){
Payloads pal = new Payloads();
RestAssured.baseURI = CommonFunctions.getSitApiGatewayEndPoint();
String sessionKey = GbPortalLogin.getSessionKey();
String token = "Token "+sessionKey;
System.out.println(token);
Response res = given().
header("Content-Type","application/json").
header("Authorization",token).
body(pal.createIndentPayload()).
when().post(Resources.createNbIndent).
then().extract().response();
String s = res.asString();
System.out.println(s);
/*System.out.println(res.getBody().toString());
JsonPath js = CommonFunctions.rawToJson(res);
indentId = js.get("id").toString();*/
}
Related
I am using oauth2/token to authenticate my application and get the access_token. Bellow is the java code which is working fine.
private String getToken() throws Exception {
String access_token = "";
String url = "https://login.windows.net/MyApplication_ID_here/oauth2/token";
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
urlParameters.add(new BasicNameValuePair("client_id", "MyApplication_ID_here"));
urlParameters.add(new BasicNameValuePair("client_secret", "MyApplication_secret_here"));
urlParameters.add(new BasicNameValuePair("resource", "https://graph.microsoft.com"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Sending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
String responseAsString = EntityUtils.toString(response.getEntity());
System.out.println(responseAsString);
try {
access_token = responseAsString.split(",")[6].split("\"")[3]; // get the access_token from response
} catch (Exception e) {
e.printStackTrace();
return null;
}
return access_token;
}
Response :
{"token_type":"Bearer","expires_in":"3599","ext_expires_in":"0","expires_on":"1493011626","not_before":"1493007726","resource":"https://graph.microsoft.com","access_token":"eyJ0e..."}
then I am using access_token to load the memberOf value which is not working and gives me the Access Token missing or malformed error. Bellow is the java code
private void getMemberOf()
{
HttpClient httpclient = HttpClients.createDefault();
try
{
URIBuilder builder = new URIBuilder("https://graph.windows.net/MyApplication_ID_here/users/test#testABC.onmicrosoft.com/memberOf?api-version=1.6");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.addHeader("Authorization", "Bearer " + access_token);
request.addHeader("Content-Type", "application/json");
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
}
catch (Exception e)
{
e.getMessage();
}
}
Response :
Response Code : 401
{"odata.error":{"code":"Authentication_MissingOrMalformed","message":{"lang":"en","value":"Access Token missing or malformed."},"date":"2017-04-24T04:39:38","requestId":"c5aa2abe-9b37-4611-8db1-107e3ec08c14","values":null}}
Can someone please tell me which part of the above request is wrong? Am I not setting access_token correctly?
According to your code , your access token is for resource "https://graph.microsoft.com"(Microsoft Graph API) ,But the access token is used for "https://graph.windows.net"(AAD Graph API) :
URIBuilder builder = new URIBuilder("https://graph.windows.net/MyApplication_ID_here/users/test#testABC.onmicrosoft.com/memberOf?api-version=1.6");
If you want to call Azure AD graph api , you need to get access token for Azure AD Graph API .
I got this issue while performing the CRUD operation on Azure AD B2C service via AD Graph API for user management.
The idea is to get the access token for the resource "graph.windows.net" instead I was using my tenant App Id URI as it was suggested here.
*might help people who faced the same issue and landed up here
This is the code from the tutorial Getting Started and I'm only trying it, nothing else is running.
public class Launch {
private static final String url =
"http://api.linkedin.com/v1/people/~/connections:(id,first-name,last-name,email-address,picture-url)";
private static final String url2 =
"http://api.linkedin.com/v1/people/~/connections:(id,first-name,last-name)";
public Launch() {
OAuthService service = new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey("xxxx")
.apiSecret("xxxx")
.build();
Token requestToken = service.getRequestToken();
String authUrl = service.getAuthorizationUrl(requestToken);
Verifier v = new Verifier("verifier you got from the user");
Token accessToken = service.getAccessToken(requestToken, v); // the requestToken you had from step 2
OAuthRequest request = new OAuthRequest(Verb.GET, url2);
service.signRequest(accessToken, request); // the access token from step 4
Response response = request.send();
System.out.println(response.getBody());
}
In my controller I have:
#View
public Response.Content index(){
Launch launch = new Launch();
return index.ok();}
and when I try to launch it, it gives me this error:
org.scribe.exceptions.OAuthException: Response body is incorrect. Can't extract token and secret from this: 'oauth_problem=permission_unknown'
Found the solution: changed the code to add Scanner in = new Scanner(System.in); after the ServiceBuilder declaration to use it in Verifier verifier = new Verifier(in.nextLine());
And also, put manually the url found in the terminal which is the result of System.out.println(service.getAuthorizationUrl(requestToken));
It's a temporary url, but the only way this works till now.
I'm attempting to authenticate against a rails app running as an OAuth2 provider running Doorkeeper.
I'm attempting to modify an example from the Oltu sources. The code that I have currently is:
public class OAuthClientTest {
public static void main(String[] args) throws OAuthSystemException, IOException {
String authUri = "http://smoke-track.herokuapp.com/oauth/authorize";
String callback = "http://localhost:8080";
String clientId = "728ad798943fff1afd90e79765e9534ef52a5b166cfd25f055d1c8ff6f3ae7fd";
String secret = "3728e0449052b616e2465c04d3cbd792f2d37e70ca64075708bfe8b53c28d529";
String tokenUri = "http://smoke-track.herokuapp.com/oauth/token";
try {
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation(authUri)
.setClientId(clientId)
.setRedirectURI(callback)
.setResponseType("code")
.buildQueryMessage();
System.out.println("Visit: " + request.getLocationUri() + "\nand grant permission");
System.out.print("Now enter the OAuth code you have received in redirect uri ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
request = OAuthClientRequest
.tokenLocation(tokenUri)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(clientId)
.setClientSecret(secret)
.setRedirectURI(callback)
.setCode(code)
.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
//Facebook is not fully compatible with OAuth 2.0 draft 10, access token response is
//application/x-www-form-urlencoded, not json encoded so we use dedicated response class for that
//Own response class is an easy way to deal with oauth providers that introduce modifications to
//OAuth specification
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(request, GitHubTokenResponse.class);
System.out.println(
"Access Token: " + oAuthResponse.getAccessToken() + ", Expires in: " + oAuthResponse
.getExpiresIn());
} catch (OAuthProblemException e) {
System.out.println("OAuth error: " + e.getError());
System.out.println("OAuth error description: " + e.getDescription());
}
}
}
When I run this example with the original Facebook credentials, it takes me to a page that allows authentication. When I use my rails app, I get a url of the form:
http://smoke-track.herokuapp.com/oauth/authorize?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8080&client_id=728ad798943fff1afd90e79765e9534ef52a5b166cfd25f055d1c8ff6f3ae7fd
When I enter this in the browser I am forwarded to the redirect uri followed by:
?code=6d09201b18178ee7737fcdd330563143ef0b60855e9d06621dcec627a9c3f29a
When I enter the code at the prompt, I get the following errors:
OAuth error: invalid_request
OAuth error description: Missing parameters: access_token
I don't get that error when authenticating against Facebook. Any ideas as to what I am doing wrong?
you might try to use OAuthJSONAccessTokenResponse rather than GitHubTokenResponse
I'm getting "Unauthorized" error while trying to use filter in Intuit:
Exception Details: Intuit.Ipp.Exception.InvalidTokenException: Unauthorized
The code below is used to setup the Service Context:
string AppToken = ConfigurationManager.AppSettings["applicationToken"].ToString(CultureInfo.InvariantCulture);
String realmId = HttpContext.Current.Session["realm"].ToString();
String accessToken = HttpContext.Current.Session["accessToken"].ToString();
String accessTokenSecret = HttpContext.Current.Session["accessTokenSecret"].ToString();
String consumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(CultureInfo.InvariantCulture);
String consumerSecret = ConfigurationManager.AppSettings["consumerSecret"].ToString(CultureInfo.InvariantCulture);
IntuitServicesType intuitServiceType = (IntuitServicesType)HttpContext.Current.Session["intuitServiceType"];
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
context1 = new ServiceContext(oauthValidator, AppToken, realmId, IntuitServicesType.QBO);
Query for retrieving the last modified bills is as below:
List<Bill> CustomerBills = billQry.ExecuteQuery<Bill>(context1).ToList<Bill>();
Please let me know, which parameter value I'm passing incorrectly.
The following code .NET DevKit code sends a malformed request body and results in a OAuth signature error. This is a bug in the DevKit.
BillQuery billQry = new BillQuery();
billQry.LastUpdatedTime = DateTime.Now.AddDays(-20);
billQry.SpecifyOperatorOption(FilterProperty.LastUpdatedTime, FilterOperatorType.AFTER);
billQry.LastUpdatedTime = DateTime.Now;
billQry.SpecifyOperatorOption(FilterProperty.LastUpdatedTime, FilterOperatorType.BEFORE);
billQry.PageNumber = 1;
billQry.ResultsPerPage = 15;
billQry.SpecifySortOption(SortProperty.LastUpdatedTime, SortOrderOption.HighToLow);
List<Intuit.Ipp.Data.Qbo.Bill>CustomerBills =billQry.ExecuteQuery<Intuit.Ipp.Data.Qbo.Bill>(context).ToList();
The workaround is to modify the sample code below to make the request and deserialize the response into Bill objects.
Sample Code on Pastebin
Can't get the POST working? What's wrong?
Note: This works for a GET with autocomplete
GET works without signing the url
I'm following the Web services steps to Sign the URL with my "API Key"
Docs say"client id" still?
http://code.google.com/apis/maps/documentation/webservices/
2.Try sending the POST data with the signed URL (tried the unsigned signature aswell)
def signedUrl = "https://maps.googleapis.com/maps/api/place/add/json?key=xxxxxkeyxxxxxx&sensor=false&signature=xxxxxxxxxxsignaturexxxxxx"
String postData = "{'location': { 'lat': '-33.8669710','lng': '151.1958750'},'accuracy': '50','name': 'Google Shoes!'}"
URL urlPost = new URL(signedUrl);
URLConnection connection = urlPost.openConnection();
connection.addRequestProperty("Referer", "http://www.mysite.com");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("CONTENT-TYPE", "text/json");
connection.setRequestProperty("CONTENT-LENGTH", postData.length() + "");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(postData);
out.close();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject json = new JSONObject(builder.toString());
println json
Returns a 403
"java.io.IOException: Server returned HTTP response code: 403 for URL:"
Simular to the "Java Access"section under they give an example of a GET
http://code.google.com/apis/websearch/docs/#fonje
Ok solved.
No signing the URL required
postData string was wrong
should have been
String postData = "{\"location\": { \"lat\": -33.8669710,\"lng\": 151.1958750},\"accuracy\": 50,\"name\": \"Google Shoes!\", \"types\":[\"bar\"]}"