DefaultHTTPClient in android sends basic auth header in every request after 401 is obtained - apache-httpclient-4.x

I am using DefaultHTTPClient in my android Application to connect to the server.
The login URL is protected by basic authentication scheme which involves multiple redirects.
The problem I am facing is that after the 401 is obtained for the first time, the HttpClient is adding the same basic authorization header in the subsequent request due to which there are some side effects in the production environment,.
here is the desired flow:
302 -> 302 > 401>302>302>200 (200 is reported due to the cookies being set by the intermediate responses)
But now I am getting :
302 > 302 >401 > 302 >302 >401
All the requests marked in bold have a Basic authorization header included.
Please let me know how can I resolve this/workaround?
Edit -1
On debugging : I found that the authscheme after receiving the first 401 does not get changed due to which the code in RequestTargetAuthentication:
if (authState.getAuthScope() != null || !authScheme.isConnectionBased()) {
try {
request.addHeader(authScheme.authenticate(creds, request));
} catch (AuthenticationException ex) {
if (this.log.isErrorEnabled()) {
this.log.error("Authentication error: " + ex.getMessage());
}
}
}
adds the basic auth header in the request. Is this the desired behavior?

Related

How to solve CORS policy error in hybrid app which uses angular 6 ,ionic 4 as front end and scala as back end?

I am trying to use GET method for login purpose, Using following code:
login(data){
return this.http.get("http://Server_IP:88/mLogin/" +
data.controls['mobile'].value + "/" +
data.controls['password'].value,{}).pipe(tap(
res=>{console.log('User: '+res)},
err=>console.log(err) ));
}
Above code works fine on chrome browser and getting a response too. but it does not work when build APK i.e. it does not work on the device. and when we inspect application it gets a response in the console but gives the following error:
Access to XMLHttpRequest at 'http://Server_IP:88/mLog' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is my scala (server code):
`nextFilter(requestHeader)
.map { result =>
if (requestHeader.method.equals("OPTIONS")) {
Results.Ok.withHeaders(
Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN -> "*",
Http.HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS -> "X-Requested-
With,
Accept, Content-Type",
Http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS ->
"OPTIONS,HEAD,GET,POST,PUT,PATCH,DELETE")
} else {
result.withHeaders(
Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN -> "*",
Http.HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS -> "X-Requested-
With, Accept, Content-Type",
Http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS ->
"HEAD,GET,POST,PUT,PATCH,DELETE",
Http.HeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS -> "X-Custom-
Header-To-Expose")
}
}`

Why is my HTTP response both 502 on my side but 401 on the server?

I am making an HTTP POST of a JSON from an Android app to my server (server code was not set by myself).
Most of the times this works correctly and I get a response of 200. However sometimes I get a 502 error code on the phone, but it logs as a 401 error code on the server.
The JSON is generated using unknown data from another source, however I have reviewed the JSON and it appears to be correct. The issue has only been seen when the JSON is particularly big.
Below is the code to set credentials and attach JSON to the HTTP post:
//set httpClient
httpClient = new DefaultHttpClient(httpParameters);
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password"));
//create http post
HttpPost httpPost = new HttpPost(ServerURL);
//TODO SET THE JSON
try {
JSONObject thisObject = new JSONObject(query);
StringEntity se = new StringEntity(thisObject.toString());
httpPost.setEntity(se);
}
catch (JSONException ex)
{
longInfo("JSONException - JSON error" + ex.getMessage(), 0);
}
Why are the error codes different? Is it because the credentials are not verified by the server when it gets a 401 error?
Is there a common cause for this pairing of error codes which is known?
(NOTE the username and password are definitely correct as they are successful when sending small JSON file)

Call to realtime.loadAppDataDocument fails when realtime.load works?

After calling realtime.loadAppDataDocument I receive the error:
XMLHttpRequest cannot load https://drive.google.com/load?
access_token=ya29.AHES6ZRoDqY0PmpHlbUjniB8wIl… Kzw
&id=1xAp1SMlamIfjnUGO9pDwfNF5IphdtnZsCw36KalJss27wy00LJ-rCN9MpcHMx408Xg.
Origin http://localhost:4567 is not allowed by Access-Control-Allow-Origin.
However if I call realtime.load with a fileid it works. See code extract below
if (fileId === null) {
// this call fails
gapi.drive.realtime.loadAppDataDocument(onFileLoaded, initializeStorageModel, handleErrors);
} else {
// this call succeeds
gapi.drive.realtime.load(fileId, onFileLoaded, initializeStorageModel, handleErrors);
}
Variables being used before this point (passed to google for the access token):
LOAD_APIS = 'auth:client,drive-realtime,drive-share';
SCOPE = [
'https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.file'
];
LOAD_CLIENT_APIS = ['drive', 'v2'];
Does anyone know how to get the method realtime.loadAppDataDocument to work?
Update: I think the request may be actually receiving a 401 response (but because the CORS header isn't sent with the 401 response the Access-Control-Allow-Origin error is called)
Google pushed some changes to the Realtime API which has fixed the problem.

google Drive API exchange authorization code throws 500 at times

Using this code to exchange the initial code of the requests coming from Drive UI with a token i can use to make API requests.
public GoogleCredential exchangeCode(String authorizationCode) throws CodeExchangeException {
try {
GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(), CLIENT_ID, CLIENT_SECRET, authorizationCode, REDIRECT_URI).execute();
return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET).setTransport(new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build().setFromTokenResponse(response);
}
catch (Exception e) {
log.error("An error occurred: " + e);
throw new CodeExchangeException(null);
}
}
In most cases it works, however in some cases (perhaps 5%), i get
An error occurred: com.google.api.client.auth.oauth2.TokenResponseException: 500 Error processing OAuth 2 request
<HTML>
<HEAD>
<TITLE>Error processing OAuth 2 request</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Error processing OAuth 2 request</H1>
<H2>Error 500</H2>
</BODY>
</HTML>
What could be the problem?
I get '500 Internal Server Errors' to approx. 0.5% of my API calls. I have a retry mechanism which always seems to succeed on the second attempt.
function doSomething(req) {
.
.
.
.
restRequest.execute(function(resp) {
var myResp = new Object();
try {
if (resp.error) {
if (resp.error.code == "401") {
do401(function() {
doSomething(req);
}, req, myResp);
return;
}
if (resp.error.code == "403") {
cl("403 no auth " + resp.error.message);
return;
}
if (resp.error.code == "500") {
cl("server error 500, retrying " + resp.error.message);
exponentialBackoff();
doSomething(req);
return;
}
}
} catch (ex) {
cl("[fg62] exception " + ex);
}
This was caused by a timeout between 2 of our internal servers during the authorization process (auth code exchange of the OAuth 2.0 server side flow). We were facing the same issue with the OAuth 2.0 Playground. This should have now been resolved by the auth team at Google.
Let us know if you get this issue again.
A retry mechanism is usually good to workaround transient 503 errors that you get from the Drive API. But in that case (500 errors from the Auth servers) it wasn't helping because the same call would time out every time for the same users in the same server configuration (i.e. users and server in distant geo regions).

JSON GET Method request

I have developed a iphone application that need to send User name and Password through HTTP authentication request header. can any one guide me or sent the source code for that functionalities.
You'll need to implement the NSURLConnection:didReceiveAuthenticationChallenge: method.
- (void)request:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
NSURLCredential *newCredential = [NSURLCredential
credentialWithUser:#"username"
password:#"password"
persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:newCredential
forAuthenticationChallenge:challenge];
}
else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
Edit: Or you could simply send the credentials in the URL in the format http://username:password#www.example.com/