'How to set JWT to Bearer authorization
I have to call an api endpoint that requires Bearer authentication. For the authentication token, I called another endpoint that will return a jwt in the request body. I'm new to api and have an issue how to get this jwt available in request body and map to Bearer
Following is my authentication call request for jwt token,
public String getAuthToken() {
OkHttpClient authClient = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\r\n\"grant_type\": \"password\",\r\n\"username\": \"vmnadmin|rvbsu\",\r\n\"connection\": \"local_account\",\r\n\"password\": \"Pqltuv\",\r\n\"domain\": \"\",\r\n\"auth_domain\": \"\",\r\n\"refresh_token_revoke_unused_in\": 60\r\n \r\n}");
Request request = new Request.Builder()
.url("https://smqp.vpsis.app/api/smv/auth/tokens/")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = null;
try {
response = authClient.newCall(request).execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Following is my Patch method which will change the assureId
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\r\n \r\n\"meta\": {\r\n \"assureId\": \"rmsuv|srv.emsdv\"\r\n }\r\n\r\n \r\n}");
Request request = new Request.Builder()
.url("https://smqp.vpsis.app/api/smv/file/secure2/newsecure.rvmct")
.method("PATCH", body)
.addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiIwM2ExMjU5NC0zYzFiLTQwOGItYjY5NC01NGE0MzM1ZTEwZTIiLCJzdWIiOiJla21hZG1pbnN8YWRhc2lkYSIsImlzcyI6Imt5bG8iLCJhY2MiOiJreWxvIiwicHJlZmVycmVkX3VzZXJuYW1lIjo")
.addHeader("Content-Type", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
System.out.println(response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
After getting JWT from 1st method, I need to apply that JWT to Bearer. I have an issue with how to get this jwt available in request body and map to Bearer. Please let me know if there any efficient way to invoke this request.
Solution 1:[1]
Usually response.getBody is a representation of the response itself. You need get a string representation of it and to deserialize it to an appropriate model with Jackson or gson. The next step is to extract a token from the model and pass it as an Authorization header.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
