Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

Handling Authentication Errors

Video not working?

It looks like your browser may not support the H264 codec. If you're using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.

Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let's us get back to making more videos :). But as always, please feel free to message us.

When we log in with an invalid email and password, it looks like the json_login system sends back some nice JSON with an error key set to "Invalid credentials". If we wanted to customize this, we could create a class that implements AuthenticationFailureHandlerInterface:

class AppAuthFailureHandler implements AuthenticationFailureHandlerInterface
{
    public function onAuthenticationFailure($request, $exception)
    {
        return new JsonResponse(
            ['something' => 'went wrong'],
            401
        );
    }
}

And then set its service ID onto the failure_handler option under json_login:

json_login:
    failure_handler: App\Security\AppAuthFailureHandler

Showing the Error on the Form

But, this is plenty good for us. So let's use it over in our /assets/vue/LoginForm.vue. We won't go too deeply into Vue, but I already have state called error, and if we set that, it will show up on the form:

... lines 1 - 48
<script setup>
... lines 50 - 54
const error = ref('');
... lines 56 - 65
const handleSubmit = async () => {
... line 67
error.value = '';
... lines 69 - 82
if (!response.ok) {
const data = await response.json();
console.log(data);
// TODO: set error
return;
}
... lines 90 - 93
}
</script>

After making the request, if the response is not okay, we're already decoding the JSON. Now let's say error.value = data.error:

... lines 1 - 48
<script setup>
... lines 50 - 65
const handleSubmit = async () => {
... lines 67 - 82
if (!response.ok) {
const data = await response.json();
error.value = data.error;
return;
}
... lines 89 - 92
}
</script>

To see if this works, make sure you have Webpack Encore running in the background so it recompiles our JavaScript. Refresh. And... you can click this little link to cheat and enter a valid email. But then type in a ridiculous password and... I love it! We see "Invalid credentials" on top with some red boxes!

json_login Requires Content-Type: application/json

So the AJAX call is working great. Though, there is one gotcha with the json_login security mechanism: it requires you to send a Content-Type header set to application/json. We are setting this on our Ajax call and you should to:

... lines 1 - 48
<script setup>
... lines 50 - 65
const handleSubmit = async () => {
... lines 67 - 69
const response = await fetch('/login', {
... line 71
headers: {
'Content-Type': 'application/json'
},
... lines 75 - 78
});
... lines 80 - 92
}
</script>

But... if someone forgets, we want to make sure that things don't go completely crazy.

Comment out that Content-Type header so we can see what happens:

... lines 1 - 48
<script setup>
... lines 50 - 65
const handleSubmit = async () => {
... lines 67 - 69
const response = await fetch('/login', {
... line 71
headers: {
//'Content-Type': 'application/json'
},
... lines 75 - 78
});
... lines 80 - 92
}
</script>

Then move over, refresh the page... type a ridiculous password and... it clears the form? Look down at the Network call. The endpoint returned a 200 status code with a user key set to null!

And... that makes sense! Because we're missing the header, the json_login mechanism did nothing. Instead, the request continued to our SecurityController... except that this time the user is not logged in. So, we return user: null... with a 200 status code.

That's a problem because it make it look like the Ajax call was successful. To fix this, if, for any reason the json_login mechanism was skipped... but the user is hitting our login endpoint, let's return a 401 status code that says:

Hey! You need to log in!

So, if not $user, then return $this->json()... and this could look like anything. Let's include an error key explaining what probably went wrong: this matches the error key that json_login returns when the credentials fail, so our JavaScript will like this. Heck. I'll even fix my typo!

... lines 1 - 9
class SecurityController extends AbstractController
{
... line 12
public function login(#[CurrentUser] $user = null): Response
{
if (!$user) {
return $this->json([
'error' => 'Invalid login request: check that the Content-Type header is "application/json".',
], 401);
}
... lines 20 - 23
}
}

Most importantly, for the second argument, pass a 401 for the status code.

Below, we can simplify... because now we know that there will be a user:

... lines 1 - 9
class SecurityController extends AbstractController
{
... line 12
public function login(#[CurrentUser] $user = null): Response
{
if (!$user) {
return $this->json([
'error' => 'Invalid login request: check that the Content-Type header is "application/json".',
], 401);
}
return $this->json([
'user' => $user->getId(),
]);
}
}

Beautiful! Spin over and submit another bad password. Oh, gorgeous! The 401 status code triggers our error handling code, which displays the error on top. So awesome.

Go back to LoginForm.vue and put the Content-Type header back:

... lines 1 - 48
<script setup>
... lines 50 - 65
const handleSubmit = async () => {
... lines 67 - 69
const response = await fetch('/login', {
... line 71
headers: {
'Content-Type': 'application/json'
},
... lines 75 - 78
});
... lines 80 - 92
}
</script>

Next: let's login successfully and... figure out what we want to do when that happens! We're also going to talk about the session and how that authenticates our API requests.

Leave a comment!

2
Login or Register to join the conversation
Ek24 Avatar

i think you put the coding-challenge before this chapter by mistake.

btw. Ryan ... my cats missing the cat-lang of the courses. they still stuck on Api-Platform 2.6.

Reply

Hey Ek24,

Agree, I reattached that challenge to the next chapter - it makes more sense to show it there, thanks for reporting!

my cats missing the cat-lang of the courses. they still stuck on Api-Platform 2.6.

Oh, sorry, we're still working on translating those remaining chapters into cat's language... but you know those cats, they are too lazy to fit things with deadlines ;)

Cheers!

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": ">=8.1",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "api-platform/core": "^3.0", // v3.1.2
        "doctrine/annotations": "^2.0", // 2.0.1
        "doctrine/doctrine-bundle": "^2.8", // 2.8.3
        "doctrine/doctrine-migrations-bundle": "^3.2", // 3.2.2
        "doctrine/orm": "^2.14", // 2.14.1
        "nelmio/cors-bundle": "^2.2", // 2.2.0
        "nesbot/carbon": "^2.64", // 2.66.0
        "phpdocumentor/reflection-docblock": "^5.3", // 5.3.0
        "phpstan/phpdoc-parser": "^1.15", // 1.16.1
        "symfony/asset": "6.2.*", // v6.2.5
        "symfony/console": "6.2.*", // v6.2.5
        "symfony/dotenv": "6.2.*", // v6.2.5
        "symfony/expression-language": "6.2.*", // v6.2.5
        "symfony/flex": "^2", // v2.2.4
        "symfony/framework-bundle": "6.2.*", // v6.2.5
        "symfony/property-access": "6.2.*", // v6.2.5
        "symfony/property-info": "6.2.*", // v6.2.5
        "symfony/runtime": "6.2.*", // v6.2.5
        "symfony/security-bundle": "6.2.*", // v6.2.6
        "symfony/serializer": "6.2.*", // v6.2.5
        "symfony/twig-bundle": "6.2.*", // v6.2.5
        "symfony/ux-react": "^2.6", // v2.7.1
        "symfony/ux-vue": "^2.7", // v2.7.1
        "symfony/validator": "6.2.*", // v6.2.5
        "symfony/webpack-encore-bundle": "^1.16", // v1.16.1
        "symfony/yaml": "6.2.*" // v6.2.5
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.4", // 3.4.2
        "mtdowling/jmespath.php": "^2.6", // 2.6.1
        "phpunit/phpunit": "^9.5", // 9.6.3
        "symfony/browser-kit": "6.2.*", // v6.2.5
        "symfony/css-selector": "6.2.*", // v6.2.5
        "symfony/debug-bundle": "6.2.*", // v6.2.5
        "symfony/maker-bundle": "^1.48", // v1.48.0
        "symfony/monolog-bundle": "^3.0", // v3.8.0
        "symfony/phpunit-bridge": "^6.2", // v6.2.5
        "symfony/stopwatch": "6.2.*", // v6.2.5
        "symfony/web-profiler-bundle": "6.2.*", // v6.2.5
        "zenstruck/browser": "^1.2", // v1.2.0
        "zenstruck/foundry": "^1.26" // v1.28.0
    }
}
userVoice