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!
12.
Adding & Checking the User's Password
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
}
}
72 Comments
Assuming i'm using Symfony 3.4, i need to migrate some old hashed password to a new one. As the brand new migrate_from is not an option to this version, where would be a good place to put this logic?
I do have only one Authenticator and i'm looking to put the logic inside checkCredentials().
What about something like this implementation?
`
`
Anything im missing?
Hey Pedro Hull
Nice question! Honestly your implementation looks good, the only correction from my point of view is checking order. I'd prefer first to check against new encoder and then old for some performance reasons. If you look closer checking against new encoder will save 1 encoder run, and for old encoder there is no reasons to save think about performance because you will run update queries.
Cheers!
Thanks sadikoff ! I definitely agree with you.
To finish, i will also have to update some other features to use the new encoder (signup flow, form to change customer password).
Yeah! That will be great! Cheers and have a nice time of day!
Hey Pedro Hull!
Excellent question :). Indeed, I see no problem with your implementation - checkCredentials() is a fine place for this and your logic looks perfect. Test this, then push it up to production - all +1 from me!
Cheers!
Hi guys.
I made similar LoginFormAuthenticator and it works really good.
But my client ask for a change: the authentification is now with email and a barcode.
Barcode is a similar property in my User entity: string of 6 char.
So I made some changes.
<b>In short:</b>
`
public function getCredentials(Request $request) {
}
`
But when I try to login, it seems that it's still the password who is checked.
I think I have to change some stuff in the checkCredentials function but I don't know what to do fo checking the combination email_adresse > barcode.
Some help ?
Hey Christina V.
If you won't check the password anymore, then yes, you have to change the
checkCredentialsmethod and do your "barcode" check in there. Probably something likeCheers!
Hey MolloKhan,
I tried something similar but... $user is the UserInterface. My getBarcode function is under my User entity so of course, error :(
Hey Christina V.
Yeah, you are technically correct but PHP allow you to call undefined methods on an object and since you already know that the user must be an instance of your entity user, then it should just work. Or you can do something like this just to be safer
Another approach you can take is to just store your barcode under your password field because you won't be using real passwords right? The barcode IS your password
I copied over the code from BaseFixture and UserFixture from the source code to my own project. at UserFixture.php it says:
use App\Entity\ApiToken. Undifined ApiToken. Is the path outdated?
Hey Farry7,
Did you forget to copy/paste namespace as well? Add "use App\Entity\ApiToken" in your BaseFixture and UserFixture files. Otherwise, could you share the exact error message? It would help to find the problem better.
Cheers!
Why does symfony not support pepper? Would that be inconvenient? If I would like to have two spices, one global, should I write my own encoder based on one of standard encoders or is there some other approach more recommended?
I have read some advice to not use the peppers because bcrypt was not meant for this (and because of other reasons), so I probably won't do it.
I think the best thing you can do is to always use the newest encryption algorithm and use the Symfony's mechanism to migrate all passwords
You can read more about it here https://symfony.com/doc/cur...
Cheers!
Hello everyone !
A simple "logical or best pratice" question about the password encoder : is it possible to use it inside the User entity, directly in the setPassword() function ?
Because you have to set up this encoder in every controllers, unit test or fixture test you need it... :(
Cheers !
Hey Michael
You can't use any service inside an entity, you may find a hack to do it but the recommendation is to treat your entities as a data model only. However, you can set up a Doctrine listener to automatically encode a user password on creation or update. You can learn about Doctrine listeners here: https://symfony.com/doc/cur...
Cheers!
Hi SF Team, thank you for your outstanding work!
Why is the password string different on my local machine vs my production server?
(After a new user registration)
Local machine password string in DB (PHP 7.4.1):
Production machine password string in DB (PHP 7.4.1):
At first I thought the reason is the environment, defined inside the .env file, but that's not the case.
The production server always creates passwords with this "type" of password string whereas the local machine always creates the other type of password string.
Why is that? (Both have PHP 7.4.1)
And is it important?
(The local machine password string ($argon2id$...) could be better, because SF can detect which type of algorithm was used for future "password encryption upgrades"? (whereas this is not possible with the "short password string" the production server produces?)
UDPATE://
After some research I found out that the local PHP 7.4.1 was build with Sodium support and the production PHP 7.4.1 build doesn't have Sodium support.
And the production server password "type" looks like a bcrypt string, correct?
But why chooses SF bcrypt instead of the stronger argon2id hashing algorithm on the production server (which should be implemented in every PHP 7.4 build?)?
The Symfony Docs tells me that it chooses argon2id over bcrypt if possible.
Is this possibly a bug inside Symfony?
My security.yaml of course contains this auto algorithm config:
Uodate2://
After digging deeper, I found out that the production php build is configured without libsodium/argon2 support. Thats why I think SF falls back to bcrypt
What a pity that PHP doesn't support the "latest" algorithms out of the box, only if you configure it manually to do so.
Yo Mike P. !
Happy new year! :) Nice digging through this - I think you identified everything perfectly: the "auto" mode will always use the "best" password encoder available and (yes) it looks like it was falling back to bcrypt on your production machine.
Yea, that's true :/. So the story is that, starting in PHP 7.2, the lib Sodium extension DOES come "bundled with PHP". What that means is that you do not need to install it manually, but when you compile php (or when someone compiles php) they do need to have the
--with-sodiumflag to enable it. It sounds like your server (Ubuntu?) didn't do that by default - often you need to install it manually - e.g.apt install php-libsodium.Anyways, good job sorting this out! If I remember correctly, if you DID install libsodium, Symfony will automatically start using it for new users and (I think?) automatically "migrate" old passwords to use argon when those "old users" log in (that's when Symfony temporarily has the plain-text passwords and so can re-hash it via Argon). I haven't tried that functionality out yet though, so I'm not 100% sure if you need do to some extra work to get that migration part or not.
Cheers!
Hello,
I'm updated User entity by adding password field, but when i run "make:migration" command, i got this warning "[WARNING] No database changes were detected." after that, i deleted file migration manually but still same warning!
solved!
./bin/console doctrine:cache:clear-result
./bin/console doctrine:cache:clear-query
Hey Abdessamad E.!'
Good solve! This should NOT be necessary, but there is temporarily a bug in DoctrineBundle that is requiring you to clear your cache after any Doctrine "metadata" changes. Actually, the bug has been fixed - https://github.com/doctrine... - we just need to wait for version 1.12.1 or 2.0.1 of that bundle to be released :).
Cheers!
Hello there,
Not sure what went wrong, but I always get "Invalid credentials" not sure where to debug it, can you please point me?
Thanks so much!
ooh, i found out that we have to logout first, by looking into user icon of Symfony debug bar I saw that i was still logged in as a user. Thanks anyway!
Hey Dung,
Glad yuo figured it out yourself, well done! Yeah, Symfony's web debug toolbar is the simplest and most powerful when you need to debug things in Symfony projects.
Cheers!
Hello,
how can I add a check, if the user is active?
In my user class I have the field active. A login should only be possible, if active = true.
Where I have to add this?
Hey Markus B.
That's a good question and there is an elegant way to manage it. Give it a check to this docs and if you still have more questions let us know!
https://symfony.com/doc/cur...
Cheers!
Hello! How to encode password in User->setPassword? setPassword store only plain password in database
Hey @Sana
If you are looking for an example you can watch this video from our security tutorial: https://symfonycasts.com/sc...
I hope it helps you. Cheers!
To encode my password in setPassword method, can i use doctrine listener from this tutorial?
https://symfonycasts.com/sc...
Or symfony 4 need to use another technic?
Hey Sasha,
Do you want to encode the password in setPassword() method? If so, it's a bad practice, because to encode passwords you need a special service, and injecting/passing the service into entities is not a good idea. Yes, you can use Doctrine event listener to listen, here's an example: https://symfonycasts.com/sc...
Cheers!
Hi! I have done the registration who send a confirmation token through email, but I still don't understand how redirect works..
Check this:
After the setup of the first password I get to login thanks to the redirect but when i press login I get redirected to https://localhost:8000/account/confirm/12345678
Why?
Hey Giacomo,
Redirects are pretty straightforward, but Symfony has a thing called TargetPathTrait that holds the previous URL from what you came to the Login page. It helps you to redirect users back to the same page where they were before came to the Login page for authentication. It's useful in almost all the cases, though in your case it returns you back to the confirm email page that's not a good idea. I think you can use that TargetPathTrait in your controller and call "saveTargetPath()" right before "return $this->redirectToRoute('app_login');" passing whatever URL you want users be redirected after successful login. Or just call "removeTargetPath()" and they will be redirected to the homepage IIRC. You can also debug things a bit with dump($this->getTargetPath()) at some points of your application.
Sorry for the late reply!
Cheers!
Lovely that's why then! Can I do something like if the user come from 'this path' redirect to a page istead of the one he was trying to access?
Also I need to modify the security and put:
if the user is not active, it can't log
Any ideas?
Hey Giacomo,
Yes, it should be possible with even listener where you can check what page user is on and tweak target path for him.
> if the user is not active, it can't log
If you're using Symfony Guard authenticator - as we do in this course - you can implement whatever logic you need, I'd do it in checkCredentials() method. You can throw a specific exception: CustomUserMessageAuthenticationException. We're talking about it in the end of the course: https://symfonycasts.com/sc... .
Btw, TargetPathTrait is also covered in this course, see: https://symfonycasts.com/sc...
So, I'd recommend you to complete this course to get more context about related things.
Cheers!
You said that Argon2i is recommended for PHP 7.2=<
Since Argon2id is implemented into PHP 7.3, is Argon2id now the recommended algorithm?
Hey Mike,
If you're on the newest PHP 7.3 - yes, use PASSWORD_ARGON2ID. See related RFC: https://wiki.php.net/rfc/ar... - it looks like Argon2 Password Hash Enhancements.
Cheers!
And now, in Symfony 4.3, you can use this cool "auto" algorithm instead of argon2i or anything else: it will automatically choose the best hashing algorithm available :)
Strange... Just after the post, I have a 302...
Hey Christina V.
That's the normal behavior after a successful login in. Symfony automatically redirects you to the target path
Cheers!
Hi SymfonyCasts Crew!
I was rolling along perfect with Symfony Security: Beautiful Authentication, Powerful Authorization until Chapter 12 - Checking the User’s Password.
When I set up the password field in the User entity and try the Login functions, I’m getting the PHP Fatal error in PhpStorm: Allowed memory size of 268435456 bytes exhausted (tried to allocators 262144 bytes …. Blah blah fun stuff! My browser locks up with HTTP 500 error…!
I know has nothing with the tutorial code but rather a problem with my AMP setup, but I’m wondering if you might have some tips on how to correct for this error. I’m on iMac with Mohave running PHP version 7.1.19. My php.ini has memory_limit set to 256mb and using PhpStorm with built in server.
Not sure if anyone has run across this type of memory error but any ideas for a fix would be welcome! Thanks in advance! Rob
Hey Robert V.!
Woh! That is super strange! And... ya know... probably shouldn't happen ;). So let's see what we can figure out:
A) First, do you see a stack trace when you run our of memory? I'd like to see *where* the error is happening. If you don't see a stack trace (you only see the error), installing XDebug might help.
B) When you say "My browser locks up" - what do you mean exactly? Does it really freeze or lock up? Or just a 500 error?
My first instinct is that there is possibly some accidental recursion (e.g. you're calling the same method that you're inside of) - but that's just a wild guess. I would try commenting out some code until you can get the memory error to go away - so that we can figure out where it's coming from!
Let me know what you find out!
Cheers!
Hi,
the faker isn't filling the database and also this error is being shown
An exception occurred while executing 'ALTER TABLE user ADD COLUMN password VARCHAR(255) NOT NULL':
SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL
while following exactly your steps
Hey @mike
The thing is that you already have some users loaded in your DB, so you can't add a new "not nullable" field to that table, you have to truncate it first (If it were a production table, then, you would have to do a three steps migration: add column, update existing records with a default value, alter column to not nullable)
Cheers!
Actually my table is empty anyhow.
Hmm, interesting. Which command are you running? Try re-creating your whole DB
Hello !
First things first, THANK YOU for all your work, it is just awesome !
Now the question ;-)
Is it me missing something or we actually do not logout, when reaching login, nor on failed login attempt ?
Especially if there is already a session for the failed email ?
I tried to invalidate session but it appears to be a abd idea as it makes fail the csrf check
So , what do you think is the best way to handle that ?
Thank you in advance for your advice !
I have an authenticator problem.
When I try different passwords in my login page, none of them passes the authenticator, even with "engage".
I tried to copy and paste the code for LoginFormAuthenticator from the folder "finish" but it still doesn't work.
Can you help me ?
Hey Victor L.
Did you run the fixtures? Could you double check that the user credentials you are submitting exist on the Database?
Cheers!
I finally figured out what the problem was !
I just forgot to override the getPassword method.
Now it works perfectly :)
Awesome! Let's keep learning :D
"Houston: no signs of life"
Start the conversation!