I tried this with openid-connect, and it is working. I want same thing for SAML. FYI, I'm doing demo with Keycloak. So I already changed protocol from openid-connet to SAML inside Keycloak console/dashboard.
Code:
#Override
protected Boolean doInBackground(String... params) {
try {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
/*For openid-connect*/
//RequestBody body = RequestBody.create(mediaType, "client_id=lifetrenz-client-1&username=test&password=test#123&grant_type=password&client_secret=c89b1eed-136d-445f-bfb0-e7e2bdac89ee");
/*For SAML*/
RequestBody body = RequestBody.create(mediaType, "client_id=lifetrenz-client-1&username=test&password=test#123&grant_type=password");
/*URL is changing manually accoridng to protocol*/
Request request = new Request.Builder()
.url("http://10.0.2.2:8080/auth/realms/Lifetrenz/protocol/saml/token")
.method("POST", body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
Response response = client.newCall(request).execute();
data = "CODE: " + response.code() + "\n" + "MESSAGE: " + response.message() + "\n" + "BODY: " + response.body().string();
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
Please guide me. And please answer in Java instead of Kotlin.
You can't just change the protocol to SAML and then send OpenID Connect parameters.
Here's an example of a SAML request. The parameters are completely different.
And you can't use REST API. SAML uses browser redirects.
Not a Keycloak expert but your application needs a client-side SAML stack.
Related
I am trying to connect to pay by link by json.
We first tried with json and it worked like a charm.
I used the code postman provided to create this,
But we keep getting 400 bad request,
If we change the credentials we get unauthorized, se wo know it's not that
But if we go look in the request log of pay by link we see that the request send from java does not appear here at all, it does not show error, but nothing.
Does anybody know how we can fix it?
Thanks in advance!
Sincerely,
Laurens
try {
OkHttpClient client = new OkHttpClient();
client.setConnectionSpecs(Arrays.asList(
new ConnectionSpec[]{
new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.allEnabledCipherSuites()
.build()
}
));
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\r\n \"MappingTemplate\":\"test1\", \r\n\"OrderId\":\"NFA000053\",\r\n\"Description\":\"test#123.com\",\r\n\"Amount\":50,\r\n\"Gender\":\"Male\",\r\n\"Clientname\":\"Test\",\r\n\"Send\":\"nosend\"\r\n}");
Request request = new Request.Builder()
.url("https://testapi.paybylink.com/payment/create/abcdefghijkl.../")
.post(body)
.addHeader("Content-Type","application/json")
.addHeader("Authorization", credential)
.build();
Response response = client.newCall(request).execute();
System.out.println("request: " + request);
if(response.code()==400)
{
System.out.println("response: " + response);
}
} catch (Exception e) {
System.out.println("Exception occurred:- " + e.getMessage());
}
First I wanted to authenticate my java application using OkHttp and then after authentication the response returns a session ID(key) that I wanted to use in subsequent API calls. below is the code that I am using to achieve this.
String url = "my application url";
String username = "xxx";
String password = "zzz";
String userpass = username + ":" + password;
String basicAuth = "Basic :" + new String(Base64.getEncoder().encode(userpass.getBytes()));
OkHttpClient client = new OkHttpClient();
Response response ;
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", basicAuth)
.build();
response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
but its throwing an error saying
{"responseStatus":"FAILURE","responseMessage":"Request method 'GET' not supported","errorCodes":null,"errors":[{"type":"METHOD_NOT_SUPPORTED","message":"Request method 'GET' not supported"}],"errorType":"GENERAL"}
can someone please help me to solve this. or if any have any other idea to authenticate a java application using okhttp then please suggest...
You should use the helper classes to avoid most of the logic for username and password.
https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Authenticate.java
String credential = Credentials.basic("jesse", "password1");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
Assuming this API is POST and not GET also follow
https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/PostString.java
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(postBody, MEDIA_TYPE_MARKDOWN))
.build();
You had it all right already. Just a small fix needed:
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
i.e you just need to remove extra ':' as it's already taken care of in .addHeader("Authorization", basicAuth) part.
I didn't find any useful way to generate the Signature V4 in java for signing an AWS Chime HttpRequest. I want to use 3 apis of Aws Chime (Create meeting, create attendee and delete meeting) inside my java code.
Can anyone help me please !
API Details:
Url: https://service.chime.aws.amazon.com/meetings
Body: { "ClientRequestToken": "AXEXAMPLE", "MediaRegion":
"us-east-2" }
Headers: "content-type", "application/json" "host",
"service.chime.aws.amazon.com" "x-amz-date", "20200526T094404Z"
"authorization", ?(Generated Signature)
API Key: JHDCHGEXAEXAMPLE Secret Key : 4sjfkkjffs/sfkkh/sfkj/example
private Response createMeeting() {
OkHttpClient client = new OkHttpClient();
Response response = null;
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\n\t\"ClientRequestToken\": \"AXEXAMPLE\",\n \"MediaRegion\": \"us-east-2\"\n}");
Request request = new Request.Builder()
.url("https://service.chime.aws.amazon.com/meetings")
.post(body)
.addHeader("content-type", "application/json")
.addHeader("host", "service.chime.aws.amazon.com")
.addHeader("content-length", "68")
.addHeader("x-amz-date", getIsoDate())
.addHeader("authorization", "?????????") //To be replaced by generated signature
.addHeader("cache-control", "no-cache")
.build();
try {
response = client.newCall(request).execute();
System.out.println("ResponseMessage===========> " + response.message());
} catch (IOException e) {
System.out.println("Error===========> " + e.getMessage());
}
return response;
}
The error I am getting is: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
Hello I switched from RestTemplate to HttpClient from java 11. I want to switch from OAuth2RestTemplate to HttpClient from java 11 also.
I cannot find any materials about using HttpClient with OAuth2. Is it possible in easy way?
And is it good idea? Or should I use WebClient from spring?
I just did post using HttpClient to grab OAuthToken and then I added token to headers of next requests.
String tokenRequest =
"client_id="
+ lmGatewayCorrectClientId
+ "&client_secret="
+ lmGatewayCorrectClientSecret
+ "&grant_type="
+ lmGatewayCorrectGrantType;
HttpClient oAuth2Client = HttpClient.newBuilder().build();
HttpRequest oAuth2Request =
HttpRequest.newBuilder()
.header(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE)
.uri(URI.create(lmGatewayCorrectAccessTokenUri))
.POST(HttpRequest.BodyPublishers.ofString(tokenRequest))
.build();
HttpResponse<String> oAuth2Response = null;
try {
oAuth2Response = oAuth2Client.send(oAuth2Request, HttpResponse.BodyHandlers.ofString());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
I'm making a request to a website. However, I keep getting a returned JSON of {"error":"invalid_client"}. Additionally, when I navigate to the URL I'm making the request to through a web browser it shows HTTP ERROR 405.
From what I read on those errors that might mean that my request isn't structured correctly.
According to the API's documentation, this is an example of the request type I'm trying to do:
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "client_secret={your_client_secret}&client_id={your_client_id}&code={your_authorization_code}&grant_type=authorization_code&redirect_uri={your_redirect_uri}");
Request request = new Request.Builder()
.url("https://api.website.com/v2/oauth2/token")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
From what I can tell mine should be doing the same thing, just a little differently.
Here is a Pastebin of my doInBackground method (I'm using AsynchTask). Here is the more applicable part:
OkHttpClient client = new OkHttpClient();
// A section here gets strings from a JSON file storing values such as client_id
RequestBody bodyBuilder = new FormBody.Builder()
.add("client_secret", CLIENT_SECRET)
.add("client_id", CLIENT_ID)
.add("code", AUTHORIZATION_CODE)
.add("grant_type", GRANT_TYPE)
.add("redirect_uri", REDIRECT_URI)
.build();
System.out.println("Built body: " + bodyBuilder.toString());
String mediaTypeString = "application/x-www-form-urlencoded";
MediaType mediaType = MediaType.parse(mediaTypeString);
RequestBody body = RequestBody.create(mediaType, requestbodyToString(bodyBuilder)); // See Edit 1
Request request = new Request.Builder()
.url(TARGET_URL)
.post(body)
.addHeader("content-type", mediaTypeString)
.addHeader("cache-control", "no-cache")
.build();
try {
System.out.println("Starting request.");
Response response = client.newCall(request).execute();
String targetUrl = request.url().toString() + bodyToString(request);
System.out.println("request: " + targetUrl);
String responseBodyString = response.body().string();
System.out.println("response: " + responseBodyString);
return responseBodyString;
} catch (IOException ex) {
System.out.println(ex);
}
Like I said, I keep getting a returned JSON of {"error":"invalid_client"}, and when I navigate to the URL I'm making the request to through a web browser it shows HTTP ERROR 405.
I'd love to provide as much additional information as you need. Thanks!
Edit 1: The second parameter of this used to be "bodyBuilder.toString()", but I changed it because I realized it wasn't actually sending the body. The result is still the same - {"error":"invalid_client"}. The method now used comes from here.
I figured out what it was - I hadn't actually been writing the authentication_code to the file, only adding it to another JSONObject. Oops. :)