BadCredentialsException example



            /** @var PasswordCredentials $badge */
            $badge = $passport->getBadge(PasswordCredentials::class);

            if ($badge->isResolved()) {
                return;
            }

            $presentedPassword = $badge->getPassword();
            if ('' === $presentedPassword) {
                throw new BadCredentialsException('The presented password cannot be empty.');
            }

            if (null === $user->getPassword()) {
                throw new BadCredentialsException('The presented password is invalid.');
            }

            if (!$this->hasherFactory->getPasswordHasher($user)->verify($user->getPassword()$presentedPassword$user instanceof LegacyPasswordAuthenticatedUserInterface ? $user->getSalt() : null)) {
                throw new BadCredentialsException('The presented password is invalid.');
            }

            $badge->markResolved();

            
$username = null;
        if ($request->server->has($this->userKey)) {
            $username = $request->server->get($this->userKey);
        } elseif (
            $request->server->has($this->credentialsKey)
            && preg_match('#'.preg_quote($this->credentialUserIdentifier, '#').'=([^,/]++)#', $request->server->get($this->credentialsKey)$matches)
        ) {
            $username = trim($matches[1]);
        }

        if (null === $username) {
            throw new BadCredentialsException(sprintf('SSL credentials not found: "%s", "%s".', $this->userKey, $this->credentialsKey));
        }

        return $username;
    }
}


    public function supports(Request $request): ?bool
    {
        return $request->headers->has('X-USER-EMAIL');
    }

    public function authenticate(Request $request): Passport
    {
        $email = $request->headers->get('X-USER-EMAIL');
        if (!str_contains($email, '@')) {
            throw new BadCredentialsException('Email is not a valid email address.');
        }

        $userLoader = null;
        if ($this->selfLoadingUser) {
            $userLoader = fn ($username) => new InMemoryUser($username, 'test', ['ROLE_USER']);
        }

        return new SelfValidatingPassport(new UserBadge($email$userLoader));
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
throw new MissingClaimException(sprintf('"%s" claim not found.', $this->claim));
            }

            // UserLoader argument can be overridden by a UserProvider on AccessTokenAuthenticator::authenticate             return new UserBadge($claims[$this->claim]new FallbackUserLoader(fn () => $this->createUser($claims))$claims);
        } catch (\Exception $e) {
            $this->logger?->error('An error occurred while decoding and validating the token.', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            throw new BadCredentialsException('Invalid credentials.', $e->getCode()$e);
        }
    }
}
throw new MissingClaimException(sprintf('"%s" claim not found on OIDC server response.', $this->claim));
            }

            // UserLoader argument can be overridden by a UserProvider on AccessTokenAuthenticator::authenticate             return new UserBadge($claims[$this->claim]new FallbackUserLoader(fn () => $this->createUser($claims))$claims);
        } catch (\Exception $e) {
            $this->logger?->error('An error occurred on OIDC server.', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            throw new BadCredentialsException('Invalid credentials.', $e->getCode()$e);
        }
    }
}
$passwordCredentials = $passport->getBadge(PasswordCredentials::class);
        if ($passwordCredentials->isResolved()) {
            throw new \LogicException('LDAP authentication password verification cannot be completed because something else has already resolved the PasswordCredentials.');
        }

        if (!$this->ldapLocator->has($ldapBadge->getLdapServiceId())) {
            throw new \LogicException(sprintf('Cannot check credentials using the "%s" ldap service, as such service is not found. Did you maybe forget to add the "ldap" service tag to this service?', $ldapBadge->getLdapServiceId()));
        }

        $presentedPassword = $passwordCredentials->getPassword();
        if ('' === $presentedPassword) {
            throw new BadCredentialsException('The presented password cannot be empty.');
        }

        $user = $passport->getUser();

        /** @var LdapInterface $ldap */
        $ldap = $this->ldapLocator->get($ldapBadge->getLdapServiceId());
        try {
            if ($ldapBadge->getQueryString()) {
                if ('' !== $ldapBadge->getSearchDn() && '' !== $ldapBadge->getSearchPassword()) {
                    try {
                        $ldap->bind($ldapBadge->getSearchDn()$ldapBadge->getSearchPassword());
                    }
public function __construct(callable $customCredentialsChecker, mixed $credentials)
    {
        $this->customCredentialsChecker = $customCredentialsChecker(...);
        $this->credentials = $credentials;
    }

    public function executeCustomChecker(UserInterface $user): void
    {
        $checker = $this->customCredentialsChecker;

        if (true !== $checker($this->credentials, $user)) {
            throw new BadCredentialsException('Credentials check failed as the callable passed to CustomCredentials did not return "true".');
        }

        $this->resolved = true;
    }

    public function isResolved(): bool
    {
        return $this->resolved;
    }
}
return new self(
            Response::HTTP_BAD_REQUEST,
            self::COUNTRY_NOT_FOUND,
            'Country with id "{{ countryId }}" not found.',
            ['countryId' => $countryId]
        );
    }

    public static function badCredentials(): BadCredentialsException
    {
        return new BadCredentialsException();
    }

    public static function cannotDeleteActiveAddress(string $id): ShopwareHttpException
    {
        if (!Feature::isActive('v6.6.0.0')) {
            return new CannotDeleteActiveAddressException($id);
        }

        return new self(
            Response::HTTP_BAD_REQUEST,
            self::CUSTOMER_ADDRESS_IS_ACTIVE,
            
class InMemoryAccessTokenHandler implements AccessTokenHandlerInterface
{
    /** * @var array<string, UserBadge> */
    private array $accessTokens = [];

    public function getUserBadgeFrom(string $accessToken): UserBadge
    {
        if (!\array_key_exists($accessToken$this->accessTokens)) {
            throw new BadCredentialsException('Invalid access token or invalid user.');
        }

        return $this->accessTokens[$accessToken];
    }

    public function remove(string $accessToken): self
    {
        unset($this->accessTokens[$accessToken]);

        return $this;
    }

    


    public function supports(Request $request): ?bool
    {
        return null === $this->accessTokenExtractor->extractAccessToken($request) ? false : null;
    }

    public function authenticate(Request $request): Passport
    {
        $accessToken = $this->accessTokenExtractor->extractAccessToken($request);
        if (!$accessToken) {
            throw new BadCredentialsException('Invalid credentials.');
        }

        $userBadge = $this->accessTokenHandler->getUserBadgeFrom($accessToken);
        if ($this->userProvider && (null === $userBadge->getUserLoader() || $userBadge->getUserLoader() instanceof FallbackUserLoader)) {
            $userBadge->setUserLoader($this->userProvider->loadUserByIdentifier(...));
        }

        return new SelfValidatingPassport($userBadge);
    }

    public function createToken(Passport $passport, string $firewallName): TokenInterface
    {
// get the passport from the Authenticator             $passport = $authenticator->authenticate($request);

            // check the passport (e.g. password checking)             $event = new CheckPassportEvent($authenticator$passport);
            $this->eventDispatcher->dispatch($event);

            // check if all badges are resolved             $resolvedBadges = [];
            foreach ($passport->getBadges() as $badge) {
                if (!$badge->isResolved()) {
                    throw new BadCredentialsException(sprintf('Authentication failed: Security badge "%s" is not resolved, did you forget to register the correct listeners?', get_debug_type($badge)));
                }

                $resolvedBadges[] = $badge::class;
            }

            $missingRequiredBadges = array_diff($this->requiredBadges, $resolvedBadges);
            if ($missingRequiredBadges) {
                throw new BadCredentialsException(sprintf('Authentication failed; Some badges marked as required by the firewall config are not available on the passport: "%s".', implode('", "', $missingRequiredBadges)));
            }

            // create the authentication token


class CustomAuthenticator extends AbstractAuthenticator implements AuthenticationEntryPointInterface
{
    public function supports(Request $request): ?bool
    {
        return false;
    }

    public function authenticate(Request $request): Passport
    {
        throw new BadCredentialsException();
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        return null;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
    {
        return new JsonResponse([
            'error' => $exception->getMessageKey(),
        ],

    public function __construct(string $userIdentifier, callable $userLoader = null, array $attributes = null)
    {
        if (\strlen($userIdentifier) > self::MAX_USERNAME_LENGTH) {
            throw new BadCredentialsException('Username too long.');
        }

        $this->userIdentifier = $userIdentifier;
        $this->userLoader = $userLoader;
        $this->attributes = $attributes;
    }

    public function getUserIdentifier(): string
    {
        return $this->userIdentifier;
    }

    
public function __construct(UserProviderInterface $userProvider, TokenStorageInterface $tokenStorage, string $firewallName, string $userKey = 'REMOTE_USER', LoggerInterface $logger = null)
    {
        parent::__construct($userProvider$tokenStorage$firewallName$logger);

        $this->userKey = $userKey;
    }

    protected function extractUsername(Request $request): ?string
    {
        if (!$request->server->has($this->userKey)) {
            throw new BadCredentialsException(sprintf('User key was not found: "%s".', $this->userKey));
        }

        return $request->server->get($this->userKey);
    }
}
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;

class AccessTokenHandler implements AccessTokenHandlerInterface
{
    public function getUserBadgeFrom(string $accessToken): UserBadge
    {
        return match ($accessToken) {
            'VALID_ACCESS_TOKEN' => new UserBadge('dunglas'),
            'SELF_CONTAINED_ACCESS_TOKEN' => new UserBadge('dunglas', fn () => new InMemoryUser('dunglas', null, ['ROLE_USER'])),
            default => throw new BadCredentialsException('Invalid credentials.'),
        };
    }
}
Home | Imprint | This part of the site doesn't use cookies.