Spring security handle PreAuthenticatedCredentialsNotFoundException to yield 403 or 401 - exception

I am using [RequestHeaderAuthenticationFilter][1] and let it throw PreAuthenticatedCredentialsNotFoundException if header is not set. My problem is that this yields a 500 status.
How to handle PreAuthenticatedCredentialsNotFoundException that it returns the 401 or 403 error response?

Related

How to authenticate in the Wigle API for get requests

I'm trying to query the Wigle API from a jupyter notebook with the code below, but keep receiving the following error:
HTTPError: 401 Client Error: Unauthorized for url: https://api.wigle.net/api/v2/network/search?onlymine=false&freenet=false&paynet=false&ssidlike=Marriott
I suspect it has something to do with authentication, but in the documentation page on Wigle, I don't see/understand where I would include my api key. Any help would be greatly appreciated.
The below code is what I tried:
import requests
import json
ssidlike = "Marriott"
url = f"https://api.wigle.net/api/v2/network/search?onlymine=false&freenet=false&paynet=false&ssidlike={ssidlike}"
response = requests.get(url)
response.raise_for_status()
if response.status_code != 204:
return response.json()
I expected to receive a JSON return of the above query, but what resulted was the following error:
HTTPError: 401 Client Error: Unauthorized for url: https://api.wigle.net/api/v2/network/search?onlymine=false&freenet=false&paynet=false&ssidlike=Marriott

getResponseCode() method doesn't return expected response code

I have 2 questions about Google App Script Services getResponseCode() method.
1) "Unexpected Error"
When I run the getResponseCode() method, I got "Unexpected Error...".
https://developers.google.com/apps-script/reference/url-fetch/http-response#getResponseCode()
var response = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
responseCode = response.getResponseCode();
Unexpected error: https://www.example.com/
※I can't tell the url for business reasons.
HTTP response status codes don't include "Unexpected Error".
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
Please tell me what response codes actually return, when this error occurs?
2) getResponseCode() method didn't work as expected
When I run the code below, I got "200".
I expected "301" in response to the "http://google.com/" request.
function myFunction() {
var response = UrlFetchApp.fetch("http://google.com/");
 Logger.log(response.getResponseCode());
}
I think getResponseCode() method doesn't return actual http status codes.
Please tell me why I got "200" instead of "301".
get 301 response in browser
get 200 response instead of 301
This happens because the request is following the redirect. Take a look at the available parameters in the UrlFetchApp.fetch() method. You'll see followRedirects, which defaults to true.
Make this small change and you'll get the expected 301.
function myFunction() {
var response = UrlFetchApp.fetch("http://google.com/", { followRedirects: false });
 Logger.log(response.getResponseCode());
}

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)

FrisbyJS returning 415 instead of 200

I just started using FrisbyJS to test a rest service we are building out. I'm getting an error and that it says it's expecting a 415 instead of 200. My code looks like:
var frisby = require("frisby");
var apiUrl = // api url
frisby.create("GET resource by id " + "43")
.get(apiUrl + "/book/43")
.expectStatus(200)
.toss();
The exact error message is:
Expected 415 to equal 200.
When I put the exact url that jasmine spits out to me when I run my test into a browser, or try it as a GET request in Postman on Chrome, it works and I get a 200 back. For some reason I get a 415 though for my call. Is there something I am missing?
Edit
Tried to debug some more and if I just do
frisby.create("GET resource by id " + "43")
.get(apiUrl + "/book/43")
.inspectJSON()
.toss();
I get this error:
Error parsing JSON string: Unexpected end of input
Which makes me thing that our rest service is doing something funny. However when I view this url in a browser or Postman like I said, it works fine.
Try this in your solution:
frisby.globalSetup({
request: {
headers: {
'Content-Type': 'application/json'
}
}
});

DefaultHTTPClient in android sends basic auth header in every request after 401 is obtained

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?