OkHttp Api call to Okta Api end point hits {"successful":true,"redirect":false} instead of actual dataset - okhttp

I am attempting to call okta to get the user info API endpoint with the Okhttp library. The application received {"successful": true,"redirect": false} when the call from java spring boot, instead of the actual dataset from the API endpoint using Postman. What am i missing in this case:
Request requestValue = new Request.Builder()
.url("https://dev-xxxxxxx.okta.com/api/v1/users/xxxxxx")
.addHeader("Accept-Encoding", "gzip, deflate, br")
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "SSWS " + apiKey.getCfgValue()).build();
try (Response response = httpClient.newCall(requestValue).execute()) {
if (response.code() == 200) {
return response;
}
}
Appreciate much that anyone could help.

Response response = httpClient.newCall(requestValue).execute()
**response.body()**
That's what you want.

Related

Axios JWT doesn't send

I have a project divided in two layers. The back-end is developed in spring boot, secured by Sprint security and JWT, and the front-end is developed in Vue.js, using Axios library for communication between layers.
I receive the "Bearer token" authentication properly, and all the authentication process is done correctly. The issue appears when I try to send a request with a token header to access content but the token doesn't send, and the Spring boot returns null without the content.
Here is the code
getOffers: function () {
if (localStorage.getItem("userSession")) {
this.aux = JSON.parse(localStorage.getItem("userSession"));
this.token = this.aux.token;
this.tokenHeader = "Bearer "+this.token;
alert(this.tokenHeader)
};
console.log(`Bearer ${this.token}`)
axios.
get('http://localhost:8080/api/v1/offer', {'Authorization' : `Bearer ${this.token}`})
.then(response => {
console.log(response);
this.offers = response.data
}).catch(e => console.log(e))
}
P.S: When I make a request in Postman, it works fine and returns the desired object. Here is a postman example:
postman
Correct way to pass header is :
axios.get(uri, { headers: { "header1": "value1", "header2": "value2" } })
In your case try this:
axios.get('http://localhost:8080/api/v1/offer', { headers:{Authorization : `Bearer ${this.token}`} })
Also, check in console if this gives correct Bearer token:
console.log(`Bearer ${this.token}`)
Register the Bearer Token as a common header with Axios so that all outgoing HTTP requests automatically have it attached.
window.axios = require('axios')
let bearer = window.localStorage['auth_token']
if (bearer) {`enter code here`
window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + bearer
}
And no need to send bearer token on every request.

Outh2 Access Token Exception

I am implementing Outh2 for authentication in spring boot application.I am getting the authorization code successfully but when i am making post request to token url by rest template it is giving me exception 400 bad Request.By this exception i am not able to identify the issue.Below is my code.
ResponseEntity<String> response = null;
System.out.println("Authorization Ccode------" + code);
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> request = new HttpEntity<String>(headers);
String access_token_url = "https://www.googleapis.com/oauth2/v3/token";
access_token_url += "?code=" + code;
access_token_url += "&client_id =487786082511-ta7fnptb8dnd4lbq9lphbtbpll9eo1it.apps.googleusercontent.com";
access_token_url += "&client_secret =fS4KHLUUMOm-lYu8QtDOFcDV";
access_token_url += "&grant_type=authorization_code";
access_token_url += "&redirect_uri=http://localhost:8080/salesgoal/googleOuth2Success";
try {
response = restTemplate.exchange(access_token_url, HttpMethod.POST, request, String.class);
}
catch(Exception e){
e.printStackTrace();
Please let me know what i am doing wrong.
Thanks
Following google's oauth2 documentation
Exchange code for access token and ID token
The response includes a code parameter, a one-time authorization code that your server can exchange for an access token and ID token. Your server makes this exchange by sending an HTTPS POST request. The POST request is sent to the token endpoint, which you should retrieve from the Discovery document using the token_endpoint metadata value. The following discussion assumes the endpoint is https://oauth2.googleapis.com/token. The request must include the following parameters in the POST body:
Follwing their documentation there could be validations on the url parameters (which yield the 400 Bad Request error code)
Please check the following:
The redirect_uri is URL_encoded (by using UrlEncoder)
Url parameters don't contain spaces ( checkclient_id and client_secret )
Later Edit:
Also try following oauth2 specification by using 'Content-Type', 'application/x-www-form-urlencoded' headers on the /token request

Calling rest server from mobile app

Following on from https://lists.hyperledger.org/g/composer/message/91
I have adapted the methodology described by Caroline Church in my IOS app.
Again I can authenticate with google but still get a 401 authorization error when POSTing.
I have added the withCredentials parameter to the http header in my POST request.
does the rest server pass back the token in cookie ? I don't receive anything back from the rest server.
where does the withCredentials get the credentials from ?
COMPOSER_PROVIDERS as follows
COMPOSER_PROVIDERS='{
"google": {
"provider": "google",
"module": "passport-google-oauth2",
"clientID": "93505970627.apps.googleusercontent.com",
"clientSecret": "",
"authPath": "/auth/google",
"callbackURL": "/auth/google/callback",
"scope": "https://www.googleapis.com/auth/plus.login",
"successRedirect": "myAuth://",
"failureRedirect": "/"
}
}'
the successRedirect points back to my App. After successfully authenticating I return to the App.
Got this working now. The App first authenticates with google then exchanges the authorization code with the rest server.
The Rest server COMPOSER_PROVIDERS needs to be changed to relate back to the app.
clientID is the apps ID in google,
callbackURL and successRedirect are reversed_clientID://
The App calls http://localhost:3000/auth/google/callback with the authorization code as a parameter.
this call will fail, but an access_token cookie is written back containing the access token required for the rest server.
The user id of the logged in user is not passed back, when exchanging the code for a token with google we get back a JWT with the details of the logged in user. We need this back from the rest server as well as the token. Is there any way to get this ?
changing the COMPOSER_PROVIDERS means that the explorer interface to the Rest server no longer works.
func getRestToken(code: String) {
let tokenURL = "http://localhost:3000/auth/google/callback?code=" + code
let url = URL(string:tokenURL);
var request = URLRequest(url: url!);
request.httpMethod = "GET";
request.setValue("localhost:3000", forHTTPHeaderField: "Host");
request.setValue("text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8", forHTTPHeaderField: "Accept");
request.setValue("1", forHTTPHeaderField: "Upgrade-Insecure-Requests");
request.httpShouldHandleCookies = true;
request.httpShouldUsePipelining = true;
let session = URLSession.init(configuration: .default);
session.configuration.httpCookieAcceptPolicy = .always;
session.configuration.httpShouldSetCookies=true;
session.configuration.httpCookieStorage = HTTPCookieStorage.shared;
let task = session.dataTask(with: request) { (data, response, error) in
var authCookie: HTTPCookie? = nil;
let sharedCookieStorage = HTTPCookieStorage.shared.cookies;
// test for access_token
for cookie in sharedCookieStorage! {
if cookie.name == "access_token"
{
print(“Received access token”)
}
}
guard error == nil else {
print("HTTP request failed \(error?.localizedDescription ?? "ERROR")")
return
}
guard let response = response as? HTTPURLResponse else {
print("Non-HTTP response")
return
}
guard let data = data else {
print("HTTP response data is empty")
return
}
if response.statusCode != 200 {
// server replied with an error
let responseText: String? = String(data: data, encoding: String.Encoding.utf8)
if response.statusCode == 401 {
// "401 Unauthorized" generally indicates there is an issue with the authorization
print("Error 401");
} else {
print("HTTP: \(response.statusCode), Response: \(responseText ?? "RESPONSE_TEXT")")
}
return
}
}
task.resume()
}
have you authorised the redirect URI in your Google OAUTH2 configuration ?
This determines where the API server redirects the user, after the user completes the authorization flow. The value must exactly match one of the redirect_uri values listed for your project in the API Console. Note that the http or https scheme, case, and trailing slash ('/') must all match.
This is an example of an Angular 5 successfully using it Angular 5, httpclient ignores set cookie in post in particular the answer at the bottom
Scope controls the set of resources and operations that an access token permits. During the access-token request, your application sends one or more values in the scope parameter.
see https://developers.google.com/identity/protocols/OAuth2
The withCredentials option is set, in order to create a cookie, to pass the authentication token, to the REST server.
Finally this resource may help you https://hackernoon.com/adding-oauth2-to-mobile-android-and-ios-clients-using-the-appauth-sdk-f8562f90ecff

MVC to WebAPI- httpclient

I have MVC App and webapi and both are in different projects and mvc app authenticates via webapi using token authentication. I can authenticate via webapi and get the bearer token in MVC.But when i pass the bearer token to webapi and access resources which are protected by authorize keyword , it throws unauthorized 401 response. Iam using httpclient within MVC to communicate to webapi
1) Using fiddler i can login to webapi and access the webapi resouces using bearer token and authorization working properly.
2) using console app , i can login to webapi and access the webapi resources using bearer token and httpclient works properly
3) using a different MVC project and access the webapi using httpclient gives the same unauthorized error.
using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(handler))
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", BearerToken);
string json = JsonConvert.SerializeObject(requestvalue);
System.Net.Http.HttpResponseMessage response = await client.PostAsync(url, new StringContent(json, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
HttpContent content = response.Content;
if (content != null)
{
value = content.ReadAsAsync<T>().Result;
}
}
}
Can anyone help on this issue?
I'd recommend you to capture the HTTP request sent through the HTTP Client via Fiddler and compare it to the request that was successful.
Even though, you're setting the Authorization header on the http client, I'm not sure if it is sent in the right format required by the Web API unless I inspect the raw HTTP request
Also you can try setting the authorization header, like below.
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenNo);

Enable authenticator manually

Currently my client authenticates request only on case of 401 response:
this.client.authenticator(new okhttp3.Authenticator() {
public Request authenticate(Route route, Response response) throws IOException {
String credentials = authenticator.getCredentials();
if (credentials.equals(response.request().header("Authorization"))) {
throw new TraversonException(401, "Unauthorized", response.request().url().toString());
} else {
defaultHeader("Authorization", credentials);
Request.Builder newRequest = response.request().newBuilder()
.headers(Headers.of(defaultHeaders));
return newRequest.build();
}
});
But I'd like to change this behavior and be able to call it either manually or auto per first call? Is it possible somehow?
If the authentication is predictably required and not related to a proxy, then the solution is to implement an Interceptor instead of Authenticator.
OkHttpClient.Builder clientBuilder = ...;
clientBuilder.networkInterceptors().add(0, myInterceptor);
client = clientBuilder.build();
Example Interceptor https://github.com/yschimke/oksocial/blob/48e0ca53b85e608443eab614829cb0361c79aa47/src/main/java/com/baulsupp/oksocial/uber/UberAuthInterceptor.java
n.b. There is discussion around possible support for this usecase in https://github.com/square/okhttp/pull/2458. One issue with current Authenticator API is that it assumes a Response from the failed (401) request.

Resources