Symfony4:如何在UserController中读取bcrypt加密配置的cost值?
cost Value from Security Encoder Configuration in Symfony 4 Hey Craig, no worries—this is a common sticking point when working with Symfony's security system, especially since the encoder's internal properties are private. Let's walk through two reliable ways to grab that cost value in your UserController:
Method 1: Use the EncoderFactoryInterface Service
Symfony's EncoderFactoryInterface lets you fetch the exact encoder configured for your User entity. Since you're using bcrypt, the returned encoder is a BcryptPasswordEncoder which has a public getCost() method you can leverage.
First, inject the service into your controller action:
use App\Entity\User; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface; use Symfony\Component\Security\Core\Encoder\BcryptPasswordEncoder; class UserController extends AbstractController { public function yourAction(EncoderFactoryInterface $encoderFactory) { // Fetch the encoder linked to your User entity $encoder = $encoderFactory->getEncoder(User::class); // Confirm it's the Bcrypt encoder, then get the cost value if ($encoder instanceof BcryptPasswordEncoder) { $costValue = $encoder->getCost(); // Now you can use $costValue for whatever you need! } } }
This method is ideal because it pulls the value directly from the encoder your app is actually using—no risk of mismatched values if you update your security.yaml later.
Method 2: Define a Reusable Parameter
If you need to use the cost value in multiple places (not just the controller), define it as a parameter first. This keeps your configuration DRY (Don't Repeat Yourself) and easy to update.
- Add the parameter to
config/services.yaml:
parameters: app.user.password_cost: 15
- Update your
security.yamlto reference this parameter instead of hardcoding the value:
security: encoders: App\Entity\User: algorithm: bcrypt cost: '%app.user.password_cost%'
- Now you can inject this parameter directly into your controller action:
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class UserController extends AbstractController { public function yourAction(int $appUserPasswordCost) { // $appUserPasswordCost will match the 15 you defined in parameters } }
Alternatively, use the ParameterBagInterface to fetch it dynamically:
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; class UserController extends AbstractController { public function yourAction(ParameterBagInterface $parameterBag) { $costValue = $parameterBag->get('app.user.password_cost'); } }
Either approach works great—pick the one that fits your use case best!
内容的提问来源于stack exchange,提问作者Craig Rayner

