Generate valid Authorization:Basic - java

I'm trying to generate correct string for Authorization:Basic [string] but i fail because i'm not really sure what info should i encode.
First request that client sends is sign_up request which doesn't include Authorization.Response for that request looks like this:
{
"user": {
"name": "Genome",
"id": 2417370297
},
"identifier": "OFpDN0VJU3UxM1B1dTZTWDNMS1hqYWNwbmFjM3Zib0lBaTJYbTdUUWVWRkhTUUdYVWJyK0FobnppY1pkZEFwTG1OQkpoQjBGOVY5RmVtN0RtQ1BsUEE9PTpZaTc1SFZBeDFsWGxZaUZNeDZxTTZRPT0="
}
After that,the next request client should send is sign_in which includes Authroization:Basic.This is how Authorization looks:
Authorization: Basic WWk3NUhWQXgxbFhsWWlGTXg2cU02UT09OjhaQzdFSVN1MTNQdXU2U1gzTEtYamFjcG5hYzN2Ym9JQWkyWG03VFFlVkZIU1FHWFVicitBaG56aWNaZGRBcExtTkJKaEIwRjlWOUZlbTdEbUNQbFBBPT0=
Problem is i don't know how to generate that string after "Basic" .If you need any info ask here

Basic authentication is name:password encoded in Base64.

Related

ContentType.URLENC with sending API REQUEST

I started API testing recently and facing different content-types each time, and i wan to know specific in what case we use ContentType.URLENC, I kinda sure we use it with x-www-form-urlencoded, but still confusing and we use it with usually POST request ?
Firstly, when you want to send infomation to server, you need to tell the server how you structure your message in BODY part. Below is some basic ContentType:
Using key-value with&: you can choose x-www-form-urlencoded.Since there are some special characters in your message, then these need to be encoded. That's why urlencoded.
Eg: name=abc&age=20
Json type: choose application/json .
Eg:
{
"name": "abc",
"age": 20
}
Want to send a file: choose form-data
Secondly, BODY part usually goes with POST and PUT request.

Not able to register webhook via postman in twitter app

https://api.twitter.com/1.1/account_activity/all/prod/webhooks.json?url=https://test.com not working
I have followed all steps to create a new application and getting consumer key, secret keys and also token details and try to create webhook via postman. I am getting follwing error
{
"errors": [
{
"code": 32,
"message": "Could not authenticate you."
}
]
}
I have tried delete and get methods for webhook and it is working fine.
They probably goofed in their example. You just need to move the url parameter from the query string to the form data. Use the x-www-form-urlencoded body.
Also - if you leave the nonce and timestamp blank, then Postman will auto-generate them for you.
enter image description here

How to get the attachment ID in JIRA

I want to delete the attachments in JIRA using REST service in JAVA.
restTemplate.delete("http://issusteackingsomething/jira/rest/api/2/attachment/{id})
I need to have the attachment ID from JIRA for the attachment to be deleted.
How do i get that attachment ID?
Use:
https://docs.atlassian.com/jira/REST/cloud/#api/2/issue-getIssue
This is simple URL-requst. Use URL:
http://"Your_domain_jira"/rest/api/2/issue/"Issue ID or Issue Key"
Parse responce json and you find all information about attachments, like that:
"attachment":[{"self":"what ever link", "id":"some sort of id that you need"} ]
You have to know issue key in order to understand to which issue attachment belongs. It can be done in DB or using rest api call:
http://issusteackingsomething/jira/rest/api/latest/issue/ISSUEKEY
In case of REST API call you will have to parse output:
"attachment": [
{
"self":
"id": "1074703",
"filename": "",
"author": {

RestTemplate and variable number of variable

I have to post json to api_url for login.
{
"username":"testre","password":"password"
}
When I use postman to check this api, it reply successful authentication like below.
{
"status": "success",
"code": 200,
"message": "username, password validated.",
"data": [
{
"password": "password",
"username": "testre"
}
],
"links": [
{
"rel": "self",
"link": "http://localhost:2222/pizza-shefu/api/v1.0/customers/login/"
},
{
"rel": "profile",
"link": "http://localhost:2222/pizza-shefu/api/v1.0/customers/testre"
}
]
}
For an unauthorized json like below.
{
"status": "unauthorized",
"code": 401,
"errorMessage": "HTTP_UNAUTHORIZED",
"description": "credentials provided are not authorized."
}
Previously I code to retrieve it using java. But now I want to refactor it using RestTemplate in spring. The problem is every example I read is written for fixed number of variables https://spring.io/guides/gs/consuming-rest/. Here I get different numbers of variable according to the login success status. I am new to spring so I'm confused in creating the class for login reply which we get from rest template. (Such as this in the example Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class); But I need to return a json object). I couldn't figure out how to write the RestTemplate part.
As suggested by #Andreas:
Add the superset of all fields for all possible responses
Identify the set of fields that are mandatory for every response and make them required
Make the rest of the fields as optional
Upon receveiving a response, check the status code and implement your logic accordingly.
If you are using Jackson for Deserialization, all fields are optional by default (see this question)

Play framework, Setting HTTP POST request headers

Question
When using the Google Plus Sign In Api with the Play Framework do you have to set headers in a different way? Is there something I am doing wrong here?
Background
I am using Play Framework(in Java) to use the Google Plus Sign in Api.
I am running into issues on the second leg of OAuth authentication, exchanging the Authorization Code for a Token.
Basic OAuth Flow
Pretty Picture
Redirect user to User login/Consent screen
This asks the user if they want to grant you application permission to the requested scopes
URL: https://accounts.google.com/o/oauth2/auth
Exchange Authorization Code for a Token
If the user gives your application permission then they will be redirected to a URL you specify, in that URL(As a GET param) will be an Authorization Code.
Your application can then use this Authoriztion Code to get a Token from the server
Your application does this by making a HTTP request to a endpoint on the Google Servers(Or whatever service you are using)
URL: https://accounts.google.com/o/oauth2/token
Use Token in API requests
The Issue
To Exchange the Authorization Code for a Token, with the Google Plus Sign In Api, you must make a POST request to https://accounts.google.com/o/oauth2/token with the following perimeters
{
"code": "Security Code Returned from Step 1",
"client_id": "Client Id that was given to you in GApi Console",
"client_secret": "Client Secret that was given to you in the GApi Console",
"redirect_uri": "Redirect Uri you specified in the GApi Console",
"grant_type": "authorization_code"
}
However when I make this request with all the correct parameters I get this error
{
"error" : "invalid_request",
"error_description" : "Required parameter is missing: grant_type"
}
From the Google Plus Sign in Api
To make HTTP requests in The Play Framework you use the WS Library. I make the request like this
public static F.Promise<Result> OAuthCallback(String state, String code){
/*
Note:
- The GoogleStrategy class is just a class that holds all my GApi credentials
- The parameters (String state, String code) are just GET params from Step 1, returned by the GApi
*/
//Make URL builder
WSRequestHolder requestHolder = WS.url(GoogleStrategy.getTokenUrl);
//Set headers
requestHolder.setHeader("code", code);
requestHolder.setHeader("client_id", GoogleStrategy.clientId);
requestHolder.setHeader("client_secret", GoogleStrategy.clientSecret);
requestHolder.setHeader("redirect_uri", GoogleStrategy.redirectUri);
requestHolder.setHeader("grant_type", GoogleStrategy.grantType);//GoogleStrategy.grantType = "authorization_code"
//Make HTTP request and tell program what to do once the HTTP request is finished
F.Promise<Result> getTokenPromise = requestHolder.post("").map(
new F.Function<WSResponse, Result>() {
public Result apply(WSResponse response){
return ok(response.asJson());//Returning result for debugging
}
}
);
return getTokenPromise;//Return promise, Play Framework will handle the Asynchronous stuff
}
As you can see, I set the header grant_type. Just to make sure setting headers was working I made a program that spits out the headers of a request in NodeJS(Source) and this was the result
{
"HEADERS": {
"host": "127.0.0.1:3000",
"code": "4/qazYoReIJZAYO9izlTjjJA.gihwUJ6zgoERgtL038sCVnsvSfAJkgI",
"grant_type": "authorization_code",
"client_secret": "XXXX-CENSORED FOR SECURITY PURPOSES-XXX",
"redirect_uri": "http://127.0.0.1:9000/api/users/auth/google/callback",
"client_id": "XXXX-CENSORED FOR SECURITY PURPOSES-XXX",
"content-type": "text/plain; charset=utf-8",
"connection": "keep-alive",
"accept": "*/*",
"user-agent": "NING/1.0",
"content-length": "14"
}
}
I think those are not to be sent as headers but as a body. In the link you provided there is an example:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
So pass them to your post call:
StringBuilder sb = new StringBuilder();
sb.append("code=").append(code)
.append("&client_id=").append(GoogleStrategy.clientId)
.append("&client_secret=").append( GoogleStrategy.clientSecret)
.append("&redirect_uri=").append(GoogleStrategy.redirectUri)
.append("&grant_type=").append(GoogleStrategy.grantType)
requestHolder.setContentType("application/x-www-form-urlencoded")
.post(sb.toString());

Categories