Chapters
33 Chapters
|
3:34:13
|
Login to bookmark this video
-
Course Code
Subscribe to download the code!Compatible PHP versions: ^7.1.3
Subscribe to download the code!Compatible PHP versions: ^7.1.3
-
This Video
Subscribe to download the video!
Subscribe to download the video!
-
Subtitles
Subscribe to download the subtitles!
Subscribe to download the subtitles!
-
Course Script
Subscribe to download the script!
Subscribe to download the script!
27.
API Token Authenticator
Scroll down to the script below, click on any sentence (including terminal blocks) to jump to that spot in the video!
Subscribe to jump to this part in the video!
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
What PHP libraries does this tutorial use?
// composer.json
{
"require": {
"php": "^7.1.3",
"ext-iconv": "*",
"composer/package-versions-deprecated": "^1.11", // 1.11.99
"doctrine/annotations": "^1.0", // 1.10.2
"doctrine/doctrine-bundle": "^1.6.10", // 1.10.2
"doctrine/doctrine-migrations-bundle": "^1.3|^2.0", // v2.0.0
"doctrine/orm": "^2.5.11", // v2.7.2
"knplabs/knp-markdown-bundle": "^1.7", // 1.7.0
"knplabs/knp-paginator-bundle": "^2.7", // v2.8.0
"knplabs/knp-time-bundle": "^1.8", // 1.8.0
"nexylan/slack-bundle": "^2.0,<2.2.0", // v2.0.0
"php-http/guzzle6-adapter": "^1.1", // v1.1.1
"phpdocumentor/reflection-docblock": "^3.0|^4.0", // 4.3.0
"sensio/framework-extra-bundle": "^5.1", // v5.2.0
"stof/doctrine-extensions-bundle": "^1.3", // v1.3.0
"symfony/asset": "^4.0", // v4.1.4
"symfony/cache": "^3.3|^4.0", // v4.1.4
"symfony/console": "^4.0", // v4.1.4
"symfony/flex": "^1.0", // v1.21.6
"symfony/framework-bundle": "^4.0", // v4.1.4
"symfony/lts": "^4@dev", // dev-master
"symfony/property-access": "^3.3|^4.0", // v4.1.4
"symfony/property-info": "^3.3|^4.0", // v4.1.4
"symfony/security-bundle": "^4.0", // v4.1.4
"symfony/serializer": "^3.3|^4.0", // v4.1.4
"symfony/twig-bundle": "^4.0", // v4.1.4
"symfony/web-server-bundle": "^4.0", // v4.1.4
"symfony/yaml": "^4.0", // v4.1.4
"twig/extensions": "^1.5" // v1.5.2
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.0", // 3.0.2
"easycorp/easy-log-handler": "^1.0.2", // v1.0.7
"fzaninotto/faker": "^1.7", // v1.8.0
"symfony/debug-bundle": "^3.3|^4.0", // v4.1.4
"symfony/dotenv": "^4.0", // v4.1.4
"symfony/maker-bundle": "^1.0", // v1.7.0
"symfony/monolog-bundle": "^3.0", // v3.3.0
"symfony/phpunit-bridge": "^3.3|^4.0", // v4.1.4
"symfony/stopwatch": "^3.3|^4.0", // v4.1.4
"symfony/var-dumper": "^3.3|^4.0", // v4.1.4
"symfony/web-profiler-bundle": "^3.3|^4.0" // v4.1.4
}
}
38 Comments
If using apache don't forget to add the following to your rewrite rules:
Hey Matt,
Thanks for sharing it, though Symfony suggest a bit different rules:
See https://github.com/symfony/recipes-contrib/blob/f43798bc00cadc9ca6b15984277412ed99722869/symfony/apache-pack/1.0/public/.htaccess#L33-L35 . Actually, you can require symfony/apache-pack to get a complete .htaccess file for Symfony applications.
But, isn't it useful for HTTP Basic Auth only?
Cheers!
Thanks, man! That saved my time debugging things.
for me too. although I should have been looking in this place earlier.
As mentioned below, when using Apache it is necessary to execute
composer require apache-packto get a proper .htaccess file to support the Authorization header, otherwise it won't be set in the headers object and the authorisation will fail, of course.Yep! And when you are ready to deploy to production, you can follow this guide to configure your web server and speed up your application
https://symfony.com/doc/cur...
Cheers!
Did I miss something? When symfony knows which "Security" class should be fired? Or both are fired and conditions are checking in both support methods?
The same question came to my mind :) Then I realised that both authenticators 'support' method will get called before the controller logic is executed.
So the APITokenAuthenticator will get called on every request (even for regular users, by example when they hit the front page) it seems.
Yep, that's correct. Unless the very first authenticator supports your request, then the next one won't be called.
Hey Dominik
You can define multiple authenticators and for each its support method will be called, if it returns true, then that's the authenticator that should return a response object.
Cheers!
ApiTokenRepsitory cannot find my entity:
<blockquote>Could not find the entity manager for class "App\Entity\ApiToken".
</blockquote>
Despite being defined:
Any hint?
Hey LluÃs F.
Sorry for my late reply. It's likely you have a typo on your entity annotations, or perhaps you're mixing formats (PHP annotations and attributes)
Cheers!
Project was using subfolders, specified in doctrine.yaml and services.yaml; I had to modify them.
Thanks
Hello from Poland :)
In symfony 5.3 I have depreciated error: Class 'AbstractGuardAuthenticator' is deprecated :/
What can I replace with this class?
Hey Lechu85,
Nice to see users from Poland here! :)
Let me give you some tips about. First of all, you can always find the class that was deprecated in the vendor/ dir and look why it was deprecated and how you can replace it. In this case, here's the deprecation message: https://github.com/symfony/... - it says that since Symfony 5.3, you should use the new authenticator system instead. To know more about the new authenticated system - you can watch a separate course on SymfonyCasts where we cover this topic in full: https://symfonycasts.com/sc... . Also, Ryan will have a workshop about it next week during the Symfony World online: https://live.symfony.com/20... - if you're going to attend it - you will know it there too :)
I hope this helps!
Cheers!
Thank you for your response :) I dont know how use solution from Your link: https://github.com/symfony/...
, but I found something like this: https://symfony.com/doc/cur...
will it be a good solution to build this class? :)
Hey Leszek C.!
Yup, that's exactly it :). You basically just need to "convert" the logic for the Guard authenticator that we build here into the new "authenticator" system. We don't talk specifically about API authenticators, but we talk about the new authenticator system in the Symfony 5 security tutorial: https://symfonycasts.com/sc...
Cheers!
Hi, thanks for the awesome course. I have a small issue with this ApiTokenAuthenticator. No matter how I send request to the /api/account via Postman, with or without token, Im always redirected to the login page. I'm using Symfony version 5 with the new Authenticatiors. Thanks
Never mind, I got it working :)))
Hey @Anh!
Awesome :). I'm glad you got it figured out so quickly! Keep going!
Cheers!
And the other thing is if I comment the entry_point from security.yaml, it still redirects the anonymous users back to login page, I'm wondering is the entry_point really necessary here? Thanks
I think
getCredentials()would be more readable if wereturn substr($authorizationHeader, strlen('Bearer '));Hey Paulius
Sounds not very efficient, why use
strlen()on known string? Maybe more readable will be to use some sort of constant?Cheers
Hi there !
Great tutorial as usual, thanks :)
Can you tell me what are the main pros and cons between the API token authentication method you are building in this tuto and JWT please ?
I am currently hesitating between both. It seems that JWT is more advanced, but I can't figure out why it is better than the token in the database system...
Moreover, managing the tokens in the database allows the user to deactivate them, for example if they lose their device...
Looking forward for your reply :)
HeySimon L. !
> Great tutorial as usual, thanks :)
Cheers! :)
> Can you tell me what are the main pros and cons between the API token authentication method you are building in this tuto and JWT please ?
Excellent question! And I think you already "sense" the answer. Mostly, JWT and "tokens stored in the database" are both just... tokens. So most things are the same: you can send both on a header to authenticate in an API, but give you information about who should be logged in and potentially the "scopes", they just store that information differently (JWT stores right inside itself vs token in the database stores that info in the database). So, most things are the same, so I'll focus on the PROs/CONs of what is different:
JWT
PROs: you don't need to store your tokens. But... for many apps... storing tokens is no big deal! However, if you have a big system and you use a JWT to authentication with each system, a JWT allows each system to NOT need to make an API request back to a central auth server to ask "is this token valid?". As long as each system has the JWT public key, it can verify the signature. This is not a use-case many people have,
CONs The big con is that invalidation is much trickier. In fact, if you want to invalidate a JWT, then you actually need to keep a database storage of your *invalidated* JWT's, so that you can check it each time. And that. completely defeats the purpose.
Here's a fun read that talks about this further: https://jolicode.com/blog/w...
Let me know what you think ;).
Cheers!
Hi weaverryan
Thank you very much, it is very clear and the link you provided is also very useful to me !
Hi, big thanks for all the awesome vids! I was trying to create a functional test for the authentication. You say; "The only thing better than using Postman is creating functional tests in your own app. But that's the topic for another tutorial.". What tutorial are you referring to?
Hey Lex,
We're talking about a completely new tutorial, like a separate one where would be covered this complex topic. Unfortunately, we don't have it yet. The only tutorials about testing we have are:
- https://symfonycasts.com/sc...
- https://symfonycasts.com/sc...
We do cover functional tests there, but not API token auth.
Cheers!
Will there be any tutorial about Two-Factor Authentication with sf4/sf5 soon?
Hey Nikolay S.!
Unfortunately, not soon - it may be something we talk about in the Symfony 5 security tutorial, but that is months away. Fortunately, I've had this conversation with someone before ;). And it includes some pointers on how to make this happen: https://symfonycasts.com/sc...
If you have any questions about that process, feel free to ask them here or there.
Cheers!
Hi,
In the supports function of the class ApiTokenAuthenticator, there is this line which I don't really understand:
0 === strpos($request->headers->get('Authorization'), 'Bearer ');Can you explain me please?
Hey Stephansav,
to understand this line you need to understand how the strpos() function works. Here's the link to PHP docs about it: https://www.php.net/manual/... . So, this function returns the position of the substring we're looking for inside the given string. So, basically, if the Authorization header string contains "Bearer" subsctring in it - the strpos() function will return its position. Ans so, if the Authorization header *starts* with "Bearer" - it will return 0, i.e. 0 is the position where "Bearer" string is found in the Authorization header string. And then we just compare its position with 0.
So, in short, if the "Bearer" string is a substring of the Authorization header and it's position starts with 0, i.e Authorization header literally start with "Bearer" string - then that check (0 === strpos($request->headers->get('Authorization'), 'Bearer ')) will return true.
I hope it's clearer to you now.
Cheers!
Can you tell me why I have an error in postman like "could not get any response"?
Hey Kamil,
Yes, I can :) It looks like you forgot to start the web server, or the host in your request URI is incorrect :) Please, double check it and make sure you can access that URI in the browser first.
Cheers!
It was first thing i have checked. I started web server and i have written correct url. I have response when i change barear token.
Hey Kamil,
Hm, do you mean invalid bearer token was caused "could not get any response"? Are you using SSL from Symfony Client? Actually, below the "Could not get any response" error there's a few ideas what could cause it:
I just double checked HTTPS URL by running the project with "symfony serve" command and it failed with the exact "Could not get any response" error. But after I turned on CA certs in config and specify path to it as "/Users/victor/.symfony/certs/rootCA.pem" - it works for me and I can send requests from Postman to the project HTTPS URL.
I hope this helps!
Cheers!
`$token = $this->apiTokenRepo->findOneBy([
`
Hi Ryan,
We struggle with two things :
Thanks for the great screencasts!
Hey Nethik
> 1. Since you have set the token property in ApiToken entity constructor, how is it not returning it instead of the value in the database?
Because of Doctrine, Doctrine create your objects based on the data from the DB, that's why you fetch them through a repository
> 2. Also, how does the ApiToken repository knows to pass the User entity to the ApiToken constructor?
Because of the same reason :) That's just how Doctrine works. IIRC, when you fetch an object from the DB, Doctrine never executes your constructor
Cheers!
"Houston: no signs of life"
Start the conversation!