Skip to content

Commit

Permalink
Merge pull request #2 from ecphp/1-handle-ajax-requests
Browse files Browse the repository at this point in the history
#1: Detect when the request is AJAX and respond using a JSON response.
  • Loading branch information
drupol committed Feb 10, 2020
2 parents 4fd6825 + 0ce4464 commit 5aeb24f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
15 changes: 15 additions & 0 deletions spec/EcPhp/CasBundle/Security/CasGuardAuthenticatorSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
use Nyholm\Psr7\ServerRequest;
use PhpSpec\ObjectBehavior;
use Psr\Log\NullLogger;
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\HttpClient\Psr18Client;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
Expand Down Expand Up @@ -122,6 +124,19 @@ public function it_can_check_the_credentials(UserInterface $user)
->during('checkCredentials', [$response, $user]);
}

public function it_can_detect_when_the_request_is_an_ajax_request_and_respond_accordingly()
{
$request = new ServerRequest(
'GET',
'http://app/?ticket=ticket',
['X-Requested-With' => 'XMLHttpRequest']
);

$this
->start((new HttpFoundationFactory())->createRequest($request))
->shouldBeAnInstanceOf(JsonResponse::class);
}

public function it_can_get_the_user_from_the_response()
{
$body = <<< 'EOF'
Expand Down
9 changes: 9 additions & 0 deletions src/Security/CasGuardAuthenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@
use InvalidArgumentException;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
Expand Down Expand Up @@ -169,6 +171,13 @@ public function onLogoutSuccess(Request $request)
*/
public function start(Request $request, ?AuthenticationException $authException = null)
{
if (true === $request->isXmlHttpRequest()) {
return new JsonResponse(
['message' => 'Authentication required'],
Response::HTTP_UNAUTHORIZED
);
}

return new RedirectResponse(
$this
->cas
Expand Down

0 comments on commit 5aeb24f

Please sign in to comment.