I'm trying to make a How to create a custom Authentication Provider, after a full reading and looking into the Symfony code, I thought that just with creating a Factory, Authentication Provider and using the symfony default class will be enough but actually I'm missing something and I'm getting this error
ContextErrorException: Catchable Fatal Error: Argument 1 passed to Acme\DemoBundle\Provider\MyProvider::__construct() must implement interface Symfony\Component\Security\Core\User\UserProviderInterface, string given, called in D:\wamp\www\sf2ldap\app\cache\dev\appDevDebugProjectContainer.php on line 1383 and defined in D:\wamp\www\sf2ldap\src\Acme\DemoBundle\Provider\MyProvider.php line 20
The Factory
namespace Acme\DemoBundle\Factory;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AbstractFactory;
class MyFactory extends AbstractFactory
{
public function getPosition()
{
return 'form';
}
public function getKey()
{
return 'kstr';
}
protected function createAuthProvider(ContainerBuilder $container, $id, $config, $userProviderId)
{
$providerId = 'security.authentication.provider.kstr.' . $id;
$container
->setDefinition($providerId, new DefinitionDecorator('kstr.security.authentication.provider'))
->replaceArgument(0, new Reference($userProviderId));
return $providerId;
}
protected function getListenerId()
{
return 'security.authentication.listener.form';
}
}
My Provider
namespace Acme\DemoBundle\Provider;
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class MyProvider implements AuthenticationProviderInterface
{
private $_userProvider;
public function __construct(UserProviderInterface $userProvider)
{
$this->_userProvider = $userProvider;
}
public function authenticate(TokenInterface $token)
{
try
{
$user = $this->_userProvider->loadUserByUsername($token->getUsername());
//custom auth steps
$token = new UsernamePasswordToken(
$token->getUsername(), null, $token->getProviderKey(), $user->getRoles()
);
return $token;
}
} catch (\Exception $exc)
{
throw new AuthenticationException('Invalid username or password. ', 0, $e);
}
throw new AuthenticationException('Invalid username or password asdfasd');
}
public function supports(TokenInterface $token)
{
return $token instanceof UsernamePasswordToken;
}
}
services.yml
services:
kstr.security.authentication.provider:
class: Acme\DemoBundle\Provider\MyProvider
arguments: [""]
security.yml
security:
encoders:
Acme\DemoBundle\Entity\SecureUser: plaintext
providers:
multiples:
chain:
providers: [entity_provider, ldap]
entity_provider:
entity: { class: AcmeDemoBundle:SecureUser, property: username }
ldap:
id: kstr.security.authentication.provider
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/demo/secured/login$
security: false
secured_area:
pattern: ^/demo/secured/
kstr:
check_path: _security_check
login_path: _demo_login
provider: ldap
logout:
path: _demo_logout
target: _demo
need some help to figure this out, what I'm missing here? do I need to create a custom listener even if the default "security.authentication.listener.form" fulfil my needs?
You're passing a string arguments: [""] as first argument to the constructor of the service.
That's why the typehint in __construct(UserProviderInterface $userProvider) fails.
Inject a UserProviderInterface properly and the exception will disappear.
Related
The question is simple. I am implmenting AccessDeniedListener and I get an ExceptionEvent object. From this I can get request. I want to apply certain logic ONLY if I am inside one of my firewalls defined in security.yaml.
How can I get the Firewall name from ExceptionEvent or Request instances?
EDIT:
I have found this code "works"
$firewall_context_name = $event->getRequest()->attributes->get('_firewall_context');
However Im not very happy about it. There should be a FirewallContext or FirewallConfig objects retrieveable somehow, no?
Thanks
class AccessDeniedListener implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
// the priority must be greater than the Security HTTP
// ExceptionListener, to make sure it's called before
// the default exception listener
KernelEvents::EXCEPTION => ['onKernelException', 2],
];
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
if (!$exception instanceof AccessDeniedException) {
return;
}
$request = $event->getRequest();
// HOW TO GET FIREWALL NAME HERE???
security.yaml
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
api:
pattern: ^/api/
security: false
main:
custom_authenticators:
- App\Security\LoginFormAuthenticator
logout:
path: app_logout
lazy: true
provider: app_user_provider
As stated in the docs you linked:
This object can be accessed through the getFirewallConfig(Request $request) method of the
Symfony\Bundle\SecurityBundle\Security\FirewallMap class
This class cannot be injected directly, so you'll have to configure your dependency in services.yaml using the service alias security.firewall.map (or create a service alias if you plan to use it somewhere else).
services:
# ...
App\Listener\AccessDeniedListener:
arguments:
$firewallMap: '#security.firewall.map'
Now modify your listener to receive this parameter:
class AccessDeniedListener implements EventSubscriberInterface
{
private $firewallMap;
public function __construct(FirewallMapInterface $firewallMap)
{
$this->firewallMap = $firewallMap;
}
// Ommited getSubscribedEvents
public function onKernelException(ExceptionEvent $event): void
{
$request = $event->getRequest();
$firewallConfig = $this->firewallMap->getFirewallConfig($request);
if (null === $firewallConfig) {
return;
}
$firewallName = $firewallConfig->getName();
}
}
With the new Symfony 5.1 security system, I'm not able to fire the InteractiveLoginEvent.
I followed the configuration in the official documentation (here and here) and the system was working perfectly in the former security system.
Below is my security.yaml :
security:
enable_authenticator_manager: true
encoders:
App\Entity\User:
algorithm: auto
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
form_login:
login_path: login
check_path: login
entry_point: form_login
guard:
authenticators:
- App\Security\LoginFormAuthenticator
logout:
path: logout
And the UserLocalSuscriber :
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
class UserLocaleSubscriber implements EventSubscriberInterface
{
private $session;
public function __construct(SessionInterface $session)
{
$this->session = $session;
}
public function onInteractiveLogin(InteractiveLoginEvent $event)
{
$user = $event->getAuthenticationToken()->getUser();
if ($user->getLocale() !== null) {
$this->session->set('_locale', $user->getLocale());
}
}
public static function getSubscribedEvents()
{
return [
SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin',
];
}
}
How to configure it correctly? Without it, the user locale is not set properly once the user has been logged in.
For the Symfony's new security system, the SecurityEvents::INTERACTIVE_LOGIN has been replaced with Symfony\Component\Security\Http\Event\LoginSuccessEvent.
Change your subscriber to listen for this one:
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class UserLocaleSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
LoginSuccessEvent::class => 'onLoginSuccess',
];
}
public function onLoginSuccess(LoginSuccessEvent $event): void
{
//...
}
}
These new events are mentioned briefly in the blog with the announcement for the new authenticator system.
The rest of the documentation has not been updated yet, the new auth system will probably become the default on a future Symfony realese, but right now it still is an experimental feature.
Try using this method onSecurityInteractivelogin()
First a short explanation of my task. I'm using Symfony 2.8 and have an application with REST API and SonataAdminBundle. Visitors of the website can post certain data over the REST API that is persisted to the database. A certain group of employees should manage those data through the admin area.
The access to the admin area should be protected with username and password. There is entity Employee with a property username, but no password. The authentication should be done against the LDAP server, but the access to admin area should be restricted only to those employees that are present in the entity Employee i.e. the referring database table.
For the LDAP authentication I am using the new LDAP component in Symfony 2.8.
Beyond that there should be an admin account as in_memory user.
This is what I have now:
app/config/services.yml
services:
app.ldap:
class: Symfony\Component\Ldap\LdapClient
arguments: ["ldaps://ldap.uni-rostock.de"]
app.db_user_provider:
class: AppBundle\Security\DbUserProvider
arguments: ["#doctrine.orm.entity_manager"]
app/config/security.yml
security:
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
providers:
chain_provider:
chain:
providers: [db_user, app_users]
in_memory:
memory:
users:
admin: { password: adminpass, roles: 'ROLE_ADMIN' }
app_users:
ldap:
service: app.ldap
base_dn: ou=people,o=uni-rostock,c=de
search_dn: uid=testuser,ou=people,o=uni-rostock,c=de
search_password: testpass
filter: (uid={username})
default_roles: ROLE_USER
db_user:
id: app.db_user_provider
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
admin:
anonymous: true
pattern: ^/
form_login_ldap:
provider: chain_provider
service: app.ldap
dn_string: "uid={username},ou=people,o=uni-rostock,c=de"
check_path: /login_check
login_path: /login
form_login:
provider: in_memory
check_path: /login_check
login_path: /login
logout:
path: /logout
target: /
access_control:
- { path: ^/admin, roles: ROLE_USER }
encoders:
Symfony\Component\Security\Core\User\User: plaintext
AppBundle\Entity\Employee: bcrypt
src/AppBundle/Entity/Employee.php
namespace AppBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Doctrine\ORM\Mapping as ORM;
class Employee implements UserInterface, EquatableInterface
{
// other properties
private $username;
// getters and setters for the other properties
public function getUsername()
{
return $this->username;
}
public function getRoles()
{
return array('ROLE_USER');
}
public function getPassword()
{
return null;
}
public function getSalt()
{
return null;
}
public function eraseCredentials()
{
}
public function isEqualTo(UserInterface $user)
{
if (!$user instanceof Employee) {
return false;
}
if ($this->username !== $user->getUsername()) {
return false;
}
return true;
}
}
src/AppBundle/Security/DbUserProvider.php
<?php
namespace AppBundle\Security;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\EntityManager;
use AppBundle\Entity\Employee;
class DbUserProvider implements UserProviderInterface
{
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function loadUserByUsername($username)
{
$repository = $this->em->getRepository('AppBundle:Employee');
$user = $repository->findOneByUsername($username);
if ($user) {
return new Employee();
}
throw new UsernameNotFoundException(
sprintf('Username "%s" does not exist.', $username)
);
}
public function refreshUser(UserInterface $user)
{
if (!$user instanceof Employee) {
throw new UnsupportedUserException(
sprintf('Instances of "%s" are not supported.', get_class($user))
);
}
return $this->loadUserByUsername($user->getUsername());
}
public function supportsClass($class)
{
return $class === 'AppBundle\Entity\Employee';
}
}
The authentication against LDAP works like a charm. When an employee from the database is trying to login, he/she is redirected to the homepage('/') and the login is failed. All other users, who are not in the database, can login without a problem.
That is exactly the opposite of what I want!
If I chain the providers like this:
chain_provider:
chain:
providers: [app_users, db_user]
then the method loadUserByUsername is not even called and all users can login, those who are in the database and those who are not.
The in_memory user admin can login without a problem in any case.
I appreciate any help. If someone thinks that my entire approach is bad and knows a better way, please don't spare with critics.
I know there is FOSUserBundle and SonataUserBundle, but I would prefer a custom user provider as I don't want to bloat the entity Employee, since I really don't need all those properties like password, salt, isLocked, etc. Also I don't think configuring SonataUserBundle in my particular case would be much simpler. Should you still think there is a more elegant way to fulfill my task with these two bundles, I'll be grateful to get a good advice.
you can configure user-checker per firewall, your db user provider isn't really a user-provider because it doesn't have all the information that's needed to authenticate a user (e.g password)
so what i would do is , i would remove the db user provider and add a user checker instead, the main idea of the user checker is to add additional checks during the authentication process , in your case we need to check if the user is in the employee table or not
you need to do three things to implement this
implement UserCheckerInterface Symfony\Component\Security\Core\User\UserCheckerInterface
check if the user is in the employee table or not in checkPostAuth() method
expose your new user-checker as a service
services:
app.employee_user_checker:
class: Path\To\Class\EmployeeUserChecker
change your firewall config to use the new user-checker
security:
firewalls:
admin:
pattern: ^/admin
user_checker: app.employee_user_checker
#...
Read more
[Symfony\Component\Debug\Exception\ContextErrorException]
Catchable Fatal Error: Argument 2 passed to Symfony\Component\Security\Core\Authentication\Provider\SimpleAuthenticationProvider::__construct() must implement interface Symfony\Component\Security\Core\User\UserProviderInterface, instance of Delivve\WebBundle\Service\WebKeyUsersService given, called in /home/delivve-webservice/app/cache/de_/ap_DevDebugProjectContainer.php on line 4611 and defined
What happens is that I have an api that works, but now I need to make the web service log face or google account, but this error of the above, follow this tutorial to make
http://nyrodev.info/fr/posts/286/Connexions-OAuth-Multiple-avec-Symfony-2-3
And apena in OAuthMembersService.php file includes the useSymfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\UserProviderFactoryInterface; because symfony complained of is not having such imports.
I'm really doubt
I implemented the following classes:
<?php
namespace Delivve\WebBundle\Security;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthUser as BaseOAuthUser;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
class WebKeyUserProvider extends BaseOAuthUser {
protected $data;
public function __construct(UserResponseInterface $response) {
parent::__construct($response->getUsername());
$this->data = array(
'provider'=>$response->getResourceOwner()->getName(),
'providerId'=>$response->getUsername()
);
$vars = array(
'nickname',
'realname',
'email',
'profilePicture',
'accessToken',
'refreshToken',
'tokenSecret',
'expiresIn',
);
foreach($vars as $v) {
$fct = 'get'.ucfirst($v);
$this->data[$v] = $response->$fct();
}
}
public function getData() {
return $this->data;
}
/**
* {#inheritDoc}
*/
public function getRoles() {
return array('ROLE_OAUTH_USER');
}
}
<?php
namespace Delivve\WebBundle\Service;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\UserProviderFactoryInterface;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use Delivve\WebBundle\Security\WebKeyUserProvider;
class WebKeyUsersService implements UserProviderFactoryInterface, OAuthAwareUserProviderInterface {
public function loadUserByUsername($username) {
throw new Exception('loadByUsername not implemented');
}
public function supportsClass($class) {
return $class === "Delivve\\WebBundle\\Security\\WebKeyUserProvider";
}
public function refreshUser(\Symfony\Component\Security\Core\User\UserInterface $user) {
if (!$this->supportsClass(get_class($user))) {
throw new UnsupportedUserException(sprintf('Unsupported user class "%s"', get_class($user)));
}
return $user;
}
public function loadUserByOAuthUserResponse(UserResponseInterface $response) {
return new OAuthUser($response);
}
public function create(ContainerBuilder $container, $id, $config)
{
// TODO: Implement create() method.
}
public function getKey()
{
// TODO: Implement getKey() method.
}
public function addConfiguration(NodeDefinition $builder)
{
// TODO: Implement addConfiguration() method.
}
}
And these are my configurations:
routingSecurityOAuth.yml
hwi_oauth_login:
resource: "#HWIOAuthBundle/Resources/config/routing/login.xml"
prefix: /login
hwi_oauth_redirect:
resource: "#HWIOAuthBundle/Resources/config/routing/redirect.xml"
prefix: /connect
facebook_login:
pattern: /login/check-facebook
google_login:
pattern: /login/check-google
web_target:
pattern: /target
defaults: { _controller: DelivveWebBundle:Security:oauthTarget }
service
services:
web_key_user_provider:
class: Delivve\WebBundle\Service\WebKeyUsersService
security
security:
providers:
web_key_user_provider:
id: web_key_user_provider
firewalls:
web_key:
pattern: ^/web/*
anonymous: ~
provider: web_key_user_provider
oauth:
resource_owners:
facebook: "/web/login/check-facebook"
google: "/web/login/check-google"
# linkedin: "/web/login/check-linkedin"
login_path: /web/login
failure_path: /web/login
check_path: /web/login_check
default_target_path: /web/target
oauth_user_provider:
service: web_key_user_provider
default:
anonymous: ~
access_control:
- { path: ˆ/web/target, roles: ROLE_OAUTH_USER }
- { path: ˆ/web/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
routing
web_key_register:
pattern: /webRegister
defaults: { _controller: DelivveWebBundle:Security:webRegister }
web_key:
resource: "#DelivveWebBundle/Resources/config/routingSecurityOAuth.yml"
prefix: /web/
config
hwi_oauth:
firewall_name: web_key
resource_owners:
facebook:
type: facebook
client_id: %facebook_client_id%
client_secret: %facebook_client_secret%
scope: email
infos_url: "https://graph.facebook.com/me?fields=username,name,email,picture.type(large)"
paths:
email: email
profilepicture: picture.data.url
options:
display: popup
google:
type: google
client_id: %google_client_id%
client_secret: %google_client_secret%
scope: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"
paths:
email: email
profilepicture: picture
i'm new # symfony and absolutely new at doctrine. On the symfony page is an tutorial about build an login process in sf2. And i love it, BUT i cant work with doctrine and i dont wanna work with it (there are many thinks that dont work with doctrine... - e.g. enum´s, etc).
How i create an login controller, firewall setup, etc.. is explained very good. BUT! i would like to create it without doctrine... i have an existing database, and i love plain sql. :-)
How can i use plain sql in an UserInterface... that will work with the build-in login from sf2?
Thx a lot...
What you want to do is to plug in your own UserProvider:
http://symfony.com/doc/current/cookbook/security/entity_provider.html
In place of the Doctrine 2 Object Relational Manager (ORM) you might consider using the Doctrine 2 Database Access Layer(DBAL). This is a thin sql layer built on top of PDO. Has some helper routines for building sql.
http://symfony.com/doc/current/cookbook/doctrine/dbal.html
Of course you can just use PDO directly:
http://symfony.com/doc/current/cookbook/configuration/pdo_session_storage.html
Here is a solution I propose on Symfony 3.0.
As I implement an existing postgresql database and I want to re-use a lot of an already existing PHP code, ORM was not a fit in my case (too much timecost to do the reverse engineering). Hence I have been actively searching how to use Symfony without ORM. (I did implement DBAL because what I wrote for PDO works with it... so far ... with some minor fixes).
Let's start:
The important concept I needed to understand were taken from this page:
http://symfony.com/doc/current/cookbook/security/custom_provider.html + all the things about the security.yml file.
About the security file, it took me a while to understand that the node 'providers' had only two native option:'entity' or 'memory'. And with 'entity', one was bound to work with ORM. So I figured out that I needed to develop my own provider that would work with regular PDO.
Here some part of my code to give you an idea on how I finally made it work, you'll find below the following files:
security.yml (There are probably still some room for improvement here, as I haven't dig too much the 'firewall' part organization);
CustomUsersProvider.php : The class implementing the interface
UserProviderInterface (The class PdoCustom and its method getUser() are my own PDO cooking to retrieve the user from my DB);
services.yml: The service giving access to the class CustomUsersProvider and hence providing access to the 'provider' in the security file (if I unsderstood it correctly), I pass the DBAL database config as an argument in the service so it can be used in the instance of my object CustomUsersProvider;
CustomUsers.php : a class acting as an entity of my table
'custom_users', to work with the PDO::FETCH_CLASS type of PDO fetch; it implements Symfony interfaces: UserInterface and EquatableInterface;
You still have to implement the Symfony Controller SecurityController (find it here: http://symfony.com/doc/2.0/book/security.html) and its route to /login and Twig file.
You'll probably notice when reading the code that $email is used as $username;
[projectname]\app\config\security.yml
encoders:
CustomBundle\Entity\CustomUsers:
algorithm: [enter an encoding algorithm, eg: MD5, sha512, etc.]
role_hierarchy:
ROLE_NAME2: ROLE_NAME1
ROLE_NAME3: ROLE_NAME2
providers:
custom_users_provider:
id: custom_users_provider
firewalls:
main_login:
pattern: ^/login$
anonymous: ~
main:
pattern: ^/
anonymous: true
provider: custom_users_provider
form_login:
check_path: /login_check
login_path: /login
provider: custom_users_provider
username_parameter: email
password_parameter: password
logout: true
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/secured_for_role_name, role: ROLE_NAME }
[projectname]\CustomBundle\Security\CustomUsersProvider.php
<?php
namespace CustomBundle\Security;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use CustomBundle\DependencyInjection\PdoCustom;
use CustomBundle\Entity\CustomUsers;
class CustomUsersProvider implements UserProviderInterface
{
private $dbalConnection;
private $logger;
public function __construct($dbalConnection){
$this->dbalConnection = $dbalConnection;
////////////////EASTER EGG//////////////////////////
$this->logger = $GLOBALS['kernel']->getContainer()->get('logger');
$logger->info('EASTER EGG: YOU CAN ADD LOG THAT CAN BE FOUND UNDER [projectname]\var\logs\dev.log WHEN LAUNCHING THRU app_dev.php, WICH COULD BE USEFUL TOO');
////////////////////////////////////////////////////
}
public function loadUserByUsername($username)
{
$PdoCustom = new PdoCustom($this->dbalConnection);
$userData = $PdoCustom->getUser($username);
if ($userData) {
$password = $userData->password;
$salt = null;
$role = $userData->role;
$resToReturn = new CustomUsers();
$resToReturn->setCharact($username, $password, $role);
return $resToReturn;
}
throw new UsernameNotFoundException(
sprintf('Username "%s" does not exist.', $username)
);
}
public function refreshUser(UserInterface $user)
{
if (!$user instanceof CustomUsers) {
throw new UnsupportedUserException(
sprintf('Instances of "%s" are not supported.', get_class($user))
);
}
return $this->loadUserByUsername($user->getUsername());
}
public function supportsClass($class)
{
return $class === 'CustomBundle\Entity\CustomUsers';
}
}
?>
[projectname]\src\CustomBundle\Ressources\config\services.yml
custom_bundle.custom_users_provider.class : CustomBundle\Security\CustomUsersProvider
custom_users_provider:
class: %custom_bundle.custom_users_provider.class%
arguments: ["#doctrine.dbal.default_connection"]
[projectname]\CustomBundle\Entity\CustomUsers.php
<?php
namespace CustomBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\EquatableInterface;
class CustomUsers implements UserInterface, EquatableInterface {
public $email;
public $password;
public $role;
public function __construct(){
}
public function setCharact($email,$password,$role){
$this->email = $email;
$this->password = $password;
$this->status = $status;
}
public function getRoles(){
return $this->role;
}
public function getPassword(){
return $this->password;
}
public function getSalt(){
return null;
}
public function getUsername(){
return $this->email;
}
public function eraseCredentials(){
}
public function isEqualTo(UserInterface $user)
{
if (!$user instanceof CustomUsers) {
return false;
}
if ($this->user_password !== $user->getPassword()) {
return false;
}
//if ($this->salt !== $user->getSalt()) {
// return false;
//}
if ($this->email !== $user->getUsername()) {
return false;
}
return true;
}
}
?>
That's it, you still have some work to figure it all out by yourself but I hope that will give you directions that I had a really hard time to find on HOW TO USE SYMFONY WITHOUT ORM:))