FOSRestBundle: Returning JSON/XML meta data for "Bad Credentials" Exception - authentication

I'm using FOSRestBundle for my REST API and so far it has been a great tool. I use HTTP Basic Auth and in most of the cases it works just fine. However, I have problems with the bundle's exception behaviour when bad credentials are submitted. When handling exceptions (via the integrated authentication handlers or the exception mapping configuration), the bundle always gives me a response with the correct HTTP status and JSON/XML content similar to this:
{
"code": 401,
"message": "You are not authenticated"
}
This is fine, it also works when no authentication information is submitted at all. However, when submitting bad credentials (e.g. unknown username or incorrect password) I get the HTTP code 401 Bad credentials (which is fine) with an empty message body. Instead, I would have expected something similar to the JSON above.
Is it a bug or a configuration issue on my side? I would also love to know how these kinds of authentication errors are exactly handled by the bundle, since overriding the BadCredentialsException's status code in the codes section of the bundle's exception configuration section seems to be ignored.
Thanks!

Alright, after digging into the bundle's code some more, I figured it out. The problem results from the way bad credentials are handled by Symfony's HTTP Basic Authentication impementation. The 401 Bad Credentials response is a custom response created by BasicAuthenticationEntryPoint, which is called by the BasicAuthenticationListener's handle function, immediately after an AuthenticationException has been thrown in the same function. So there is no way of catching this exception with a listener:
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (false === $username = $request->headers->get('PHP_AUTH_USER', false)) {
return;
}
if (null !== $token = $this->securityContext->getToken()) {
if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && $token->getUsername() === $username) {
return;
}
}
if (null !== $this->logger) {
$this->logger->info(sprintf('Basic Authentication Authorization header found for user "%s"', $username));
}
try {
$token = $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey));
$this->securityContext->setToken($token);
} catch (AuthenticationException $failed) {
$this->securityContext->setToken(null);
if (null !== $this->logger) {
$this->logger->info(sprintf('Authentication request failed for user "%s": %s', $username, $failed->getMessage()));
}
if ($this->ignoreFailure) {
return;
}
$event->setResponse($this->authenticationEntryPoint->start($request, $failed));
}
}
The entry point's start function creates the custom response, with no exceptions involved:
public function start(Request $request, AuthenticationException $authException = null)
{
$response = new Response();
$response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', $this->realmName));
$response->setStatusCode(401, $authException ? $authException->getMessage() : null);
return $response;
}
The fist if-clause in the handle function above also explains why it works in the case of "no user credentials at all", since in that case, the listener just stops trying to authenticate the user, and therefore an exception will be thrown by Symfony's firewall listeners (not quite sure where exactly), so FOSRestBundle's AccessDeniedListener is able to catch the AuthenticationException and do its thing.

You can extend AccessDeniedListener and tell FOSRestBundle to use your own listener with the parameter %fos_rest.access_denied_listener.class%. (service definition)
parameters:
fos_rest.access_denied_listener.class: Your\Namespace\For\AccessDeniedListener
Then add an additional check for BadCredentialsException and emmit an HttpException with the desired code/message similar to the check for AuthenticationException at Line 70.

Related

How to log and respond with error messages from failed JWT authorisation in Ktor?

When I am authorising a request, if any of the standard claims in the JWT are invalid, or if it fails for some other reason (such as the signature being incorrect), I would like to be able to see what exactly was incorrect, especially when testing. Currently, I am not able to see any message in the Unauthorized 401 response, nor in my logs.
My authentication setup (in my Application.module() function), using the auth0-jwt library.
val jwtVerifier = JWT.require(Algorithm.RSA256(getPublicKeyFromString(publicKey), null))
.withAudience("audience")
.acceptLeeway(1)
.acceptExpiresAt(5)
.build()
install(Authentication) {
jwt {
verifier(jwtVerifier)
validate { credential: JWTCredential ->
JWTPrincipal(credential.payload)
}
}
}
#OptIn(KtorExperimentalLocationsAPI::class)
install(Locations) // see http://ktor.io/features/locations.html
install(Routing) {
authenticate {
ServiceEndpoints()
}
}
I have set up an endpoint handler as follows:
fun Route.ServiceEndpoints() {
get<Paths.getData> { params ->
checkCustomClaim(context.authentication.principal(), <some other parameters here>)
//handling code here
}
}
I'll point out that checkCustomClaim() will raise an AuthorisationException (just a simple exception that I created) if the custom claim fails. I do it this way because each endpoint will be checking different information in my custom claims.
I have attempted to get logs and more information in the response with a custom status page. I am able to get the log message and response data for my AuthorisationExceptions, but not for failures in the standard claims.
install(StatusPages) {
exception<JWTVerificationException> { cause ->
log.warn("Unauthorized: ${cause.message}")
this.call.respond(
status = HttpStatusCode.Unauthorized,
message = cause.message ?: "Unauthorized"
)
}
exception<AuthorisationException> { cause ->
log.warn("Unauthorized: ${cause.message}")
this.call.respond(
status = HttpStatusCode.Unauthorized,
message = cause.message ?: "Unauthorized"
)
}
}
You can use information from a JWT diagnostics log that is written on the TRACE level.

google oauth and refresh token confusion/questions

I had expected the refresh of an expired access token to happen during the authentication process instead of during an api access.
I think I understand why this happens - authorization is done once but an access token can expire at any time, therefore a refresh attempt needs to be attempted whenever the token is determined to be expired.
I'd like to confirm this is the right interpretation of what's going on.
My first clue was the part of the docs that said
If you use a Google API Client Library, the client object refreshes
the access token as needed as long as you configure that object for
offline access.
I am using the following:
google-oauth-client 1.24.1
google-oauth-client-java6 1.24.1
google-oauth-client-jetty 1.24.1
When I run with a completely invalid access token ("i am no good") and a valid refresh token and execute a
DCM API call to a com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient subclass, I observe the following behavior:
control passes to com.google.api.client.auth.oauth2.Credential at method:
public final boolean refreshToken() throws IOException {
lock.lock();
try {
try {
TokenResponse tokenResponse = executeRefreshToken();
if (tokenResponse != null) {
setFromTokenResponse(tokenResponse);
for (CredentialRefreshListener refreshListener : refreshListeners)
{
refreshListener.onTokenResponse(this, tokenResponse);
}
return true;
}
} catch (TokenResponseException e) {
boolean statusCode4xx = 400 <= e.getStatusCode() && e.getStatusCode() < 500;
// check if it is a normal error response
if (e.getDetails() != null && statusCode4xx) {
// We were unable to get a new access token (e.g. it may have been revoked), we must now
// indicate that our current token is invalid.
setAccessToken(null);
setExpiresInSeconds(null);
}
for (CredentialRefreshListener refreshListener : refreshListeners) {
refreshListener.onTokenErrorResponse(this, e.getDetails());
}
if (statusCode4xx) {
throw e;
}
}
return false;
} finally {
lock.unlock();
}
}
This goes out and gets a new access token as long as the refresh token is valid (i've tried using an invalid refresh token and watched it fail).
Upon successful retrieval of a new access token, control passes to
refreshListener.onTokenErrorResponse(this, e.getDetails());
The token is inserted into the proper objects and access continues.
If I run with a bad refresh token the above method fails with:
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad
Request
{
"error" : "invalid_grant",
"error_description" : "Bad Request"
}
Can anyone confirm I've got the right general idea?

How to configure custom error pages for exceptions in view files?

We're using UseStatusCodePagesWithReExecute in combination with a simple custom middleware that sets Response.StatusCode to 500, to successfully to send users to our custom error page on exceptions that occur in mvc controllers.
However, for exceptions that occur in razor/cshtml views, UseStatusCodePagesWithReExecute doesn't send the user to our error page (though our custom middleware does detect these exceptions in Invoke()).
We tried using an Exception Filter as well, but it only traps exceptions from controller actions, not from views.
Is there a way to send users to our error page if the exception originates in a view?
StatusCodePagesMiddleware added by UseStatusCodePagesWithReExecute extension call has the following check after executing of underlying middlewares:
// Do nothing if a response body has already been provided.
if (context.Response.HasStarted
|| context.Response.StatusCode < 400
|| context.Response.StatusCode >= 600
|| context.Response.ContentLength.HasValue
|| !string.IsNullOrEmpty(context.Response.ContentType))
{
return;
}
When rendering of the View starts, MVC middleware fills Response.ContentType with text/html value. That's why above check returns true and request with status code page is not re-executed.
The fix is fair simple. In your middleware that handles exceptions, call Clear() method on Response:
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception)
{
context.Response.Clear();
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
}
Sample Project on GitHub

Exception thrown when WebAuthenticationBroker receives an OAuth2 callback

The WebAuthenticationBroker doesn't seem to be able to handle navigation to my ms-app://. Just throws this ugly error as you will see below.
Steps
Call AuthenticateAsync(), including callback uri obtained at runtime: WebAuthenticationBroker.GetCurrentApplicationCallbackUri()
Go through authorize process, hit Allow.
Instead of returning, the broker shows the page Can't connect to service. We can't connect to the service you need right now. Unable to do anything, so I hit the Back button visible.
Debugger breaks on catch: "The specified protocol is unknown. (Exception from HRESULT: 0x800C000D)"
The callback for WebAuthenticationBroker.AuthenticateAsync() is received (according to Fiddler4 & the Event Viewer) but it throws the aforementioned exception as if it doesn't know how to interpret the ms-app:// protocol.
All examples imply my code should work but I think there's something less obvious causing an issue.
Code
private static string authorizeString =
"https://api.imgur.com/oauth2/authorize?client_id=---------&response_type=token";
private Uri startUri = new Uri(authorizeString);
public async void RequestToken() {
try {
var war = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.UseTitle
, startUri);
// Imgur knows my redirect URI, so I am not passing it through here
if (war.ResponseStatus == WebAuthenticationStatus.Success) {
var token = war.ResponseData;
}
} catch (Exception e) { throw e; }
}
Event Viewer log excerpts (chronological order)
For information on how I obtained this, read the following MSDN: Web authentication problems (Windows). Unfortunately this is the only search result when querying authhost.exe navigation error.
Information: AuthHost redirected to URL: <ms-app://s-1-15-2-504558873-2277781482-774653033-676865894-877042302-1411577334-1137525427/#access_token=------&expires_in=3600&token_type=bearer&refresh_token=------&account_username=------> from URL: <https://api.imgur.com/oauth2/authorize?client_id=------&response_type=token> with HttpStatusCode: 302.
Error: AuthHost encountered a navigation error at URL: <https://api.imgur.com/oauth2/authorize?client_id=------&response_type=token> with StatusCode: 0x800C000D.
Information: AuthHost encountered Meta Tag: mswebdialog-title with content: <Can't connect to the service>.
Thanks for reading, Stack. Don't fail me now!
Afaik, you need to pass the end URL to AuthenticateAsync even if you assume that the remote service knows it.
The way WebAuthenticationBroker works is like the following: you specify an "endpoint" URL and when it encounters a link that starts with this URL, it will consider the authentication process complete and doesn't even try navigating to this URL anymore.
So if you specify "foo://bar" as callback URI, navigating to "foo://bar" will finish the authentication, as will "foo://barbaz", but not "foo://baz".
Resolved! #ma_il helped me understand how the broker actually evaluates the redirect callback and it led me back to square one where I realized I assumed WebAuthenticationOptions.UseTitle was the proper usage. Not so. Up against Imgur's API using a token, it requires WebAuthenticationOptions.None and it worked immediately.
As an example to future answer-seekers, here's my code.
private const string clientId = "---------";
private static Uri endUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
private static string authorizeString = "https://api.imgur.com/oauth2/authorize?"
+ "client_id="
+ clientId
+ "&response_type=token"
+ "&state=somestateyouwant"
+ "&redirect_uri="
+ endUri;
private Uri startUri = new Uri(authorizeString);
public async void RequestToken() {
try {
WebAuthenticationResult webAuthenticationResult =
await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None
, startUri
, endUri);
if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) {
string token = webAuthenticationResult.ResponseData;
// now you have the token
}
} catch { throw; }
}

using request builder to authenticate user: Not working in spring security

I need to authenticate a user in a page based on the remember me cookie,
inspired by this site: Tutorial for checking spring authentication,
I came up with a solution for checking the authentication.
Changes made in my application
applicationContext-security.xml:
<intercept-url pattern='/**AuthenticationChecker.html' access="ROLE_ADMIN"/>
...
<form-login login-page="/Login.html" authentication-failure-url="/Login.html" always-use-default-target="true" default-target-url="/Main.html"/>
Gwt code:
try
{
RequestBuilder rb = new RequestBuilder(
RequestBuilder.POST, "AuthenticationChecker.html");
rb.sendRequest(null, new RequestCallback()
{
public void onError(Request request, Throwable exception)
{
RootPanel.get().add(new HTML("[error]" + exception.getMessage()));
}
public void onResponseReceived(Request request, Response response)
{
RootPanel.get()
.add(new HTML("[success (" + response.getStatusCode() + "," + response.getStatusText() + ")]"));
}
}
);
}
catch (Exception e)
{
RootPanel.get().add(new HTML("Error sending request " + e.getMessage()));
}
AuthenticationChecker.html is a simple blank html page,
from what I understand, as AuthenticationChecker.html requires role as admin, I should have got a 401 Unauthorized if remember me cookie was not present and a 200 OK if the user was authenticated and his cookie was present.
However, the output always shows: [success (200,OK)]
To cross check, i simply typed authenticaionChecker.html (without logging in) and it returned back to Login.html indicating that spring is indeed authenticating the user.
Am I doing something wrong here ?
If you look at the tutorial, you'll see that a 401 is only returned when you're using Basic Authentication. With form-based authentication, you have to check the response text for an error message. For example:
public void onResponseReceived(Request request, Response response) {
if (response.getStatusCode() != Response.SC_OK) {
onError(request, new RequestException(response.getStatusText() + ":\n" + response.getText()));
return;
}
if (response.getText().contains("Access Denied")) {
Window.alert("You have entered an incorrect username or password. Please try again.");
} else {
// authentication worked, show a fancy dashboard screen
}
}