I'm trying to configure authentication on symfony2 with this configuration:
Security.yml
security:
encoders:
Symfony\Component\Security\Core\User\User: plaintext
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
providers:
in_memory:
memory:
users:
user: { password: userpass, roles: [ 'ROLE_USER' ] }
admin: { password: adminpass, roles: [ 'ROLE_ADMIN' ] }
firewalls:
admin_area:
pattern: ^/admin
provider: in_memory
anonymous: ~
form_login:
login_path: login
check_path: login_check
logout:
path: /logout
target: /
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin, roles: ROLE_ADMIN }
/src/MyBundle/Resources/Routing.yml
ies_cierva_encuesta_backend_admin:
pattern: /admin
defaults: { _controller: Bundle:Default:admin }
login:
pattern: /login
defaults: { _controller: Bundle:Login:login }
login_check:
pattern: /login_check
logout:
pattern: /logout
src/Bundle/Controller/LoginController.php
<?php
namespace ...
use ...
class LoginController extends Controller {
public function loginAction(Request $request) {
$session = $request->getSession();
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(
SecurityContext::AUTHENTICATION_ERROR
);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render(
'Bundle:Security:login.html.twig',
array(
// last username entered by the user
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
)
);
}
}
I'm getting this error:
"Unable to find the controller for path "/login_check". Maybe you forgot to add the matching route in your routing configuration?"
If I'm not wrong, this route doesn't need a Controller...
In http://symfony.com/doc/current/book/security.html, it is mentioned that
"Make sure that your check_path URL (e.g. /login_check) is behind the firewall you're using for your form login".
But the /login_check isn't behind the same firewall which you are using for form login.
firewalls:
admin_area:
pattern: ^/admin
provider: in_memory
anonymous: ~
form_login:
login_path: login
check_path: login_check
logout:
path: /logout
target: /
In the above configuration, pattern path "login_check" doesn't match "^/admin" pattern. Change the pattern accordingly to make it work.
Related
If I call / and am not logged in, I get the error ERR_TOO_MANY_REDIRECTS.
Actually, I should be redirected to the login page. Where’s the mistake?
security.yaml:
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: app_user_provider
logout:
path: app_logout
form_login:
login_path: app_login
check_path: app_login
access_control:
- { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY }
role_hierarchy:
ROLE_USER: ROLE_USER
ROLE_ADMIN: [ROLE_USER, ROLE_ALLOWED_TO_SWITCH]
Controller:
/**
* #Route("/{id}",defaults={"id" = null} , name="app_dashboard")
*/
public function index(PositiveTimeRepository $positiveTimeRepository, $id): Response
{
return $this->render('dashboard/index.html.twig', [
'positiveData' => $positiveTimeRepository->findBy([
'user' => $this->getUser()]),
'issetGetID' => $id
]);
}
SecurityController:
/**
* #Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('login/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error
]);
}
I updated my controllers and security.yaml
You don’t have to check for the roles in your controller yourself the security package does that with the firewall you defined, but you would have to define your login url:
firewalls:
main:
# ...
form_login:
# "login" is the name of the route created previously
login_path: login
check_path: login
Working on the security.yml file to create a reserved area as I can. How to prevent the browser's return button?
This is the content of my security.yml file:
# To get started with security, check out the documentation:
# https://symfony.com/doc/current/security.html
security:
# https://symfony.com/doc/current/security.html#b-configuring-how-users-are-loaded
encoders:
AppBundle\Entity\User: bcrypt
Symfony\Component\Security\Core\User\User: bcrypt
providers:
my_provider:
entity:
class: AppBundle:User
property: username
in_memory:
memory:
users:
admin: { password: $2y$13$voW4Dn5zM/uCMVcDM16KKeupoIMg2uf6t34SIhlZ6F7aIxEUKovk. }
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
secured_area:
anonymous: ~
http_basic: ~
pattern: ^/
form_login:
login_path: /login
check_path: /login
username_parameter: _username
password_parameter: _password
always_use_default_target_path: true
default_target_path: /home
failure_path: /login
remember_me: false
logout:
path: /logout
target: /login
invalidate_session: true
access_denied_handler: app.security.access_denied_handler
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: ~
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate
#http_basic: ~
# https://symfony.com/doc/current/security/form_login_setup.html
#form_login: ~
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/$, roles: IS_AUTHENTICATED_FULLY }
- { path: ^/home, roles: [ROLE_ADMIN, ROLE_TEACHER] }
- { path: ^/prodotti, roles: ROLE_ADMIN }
This is my controller file:
class SecurityController extends Controller {
public function homeAction(Request $request) {
if($this->get('security.context')->isGranted('ROLE_TEACHER')) {
}else {
return $this->redirect('http://symfony3.loc/login');
}
die();
return $this->render('AppBundle:Default:home.html.twig');
}
public function loginAction() {
$authenticationUtils = $this->get('security.authentication_utils');
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('AppBundle:Default:alogin.html.twig', array('last_username' => $lastUsername, 'error' => $error));
}
public function login_checkAction() {
}
public function logoutAction(Request $request) {
$session = new Session();
$session->clear();
return $this->redirect('http://symfony3.loc/login');
}
This is the route file:
home_page:
path: /home
defaults: { _controller: AppBundle:Security:home }
login:
path: /login
defaults: { _controller: AppBundle:Security:login }
logout:
path: /logout
defaults: { _controller: AppBundle:Security:logout }
login_check:
path: /login_check
You can write JavaScript code in your twig to prevent browser's back button to be clicked
<script type="text/javascript">
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
</script>
I use UserBundle and HWIO for social network, but If user have not socials I create custom registration, when user have email and password for email I try authentication but have many error last error:
Error: User account is disabled.
I don’t know how to be tune service.yml and HWIO still work and standart authentication help please
And know not working enter with HWIO:
Unable to find the controller for path "/login/check-vkontakte". The route is wrongly configured.
with this work fine security:
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
providers:
fos_userbundle:
id: fos_user.user_provider.username
my_custom_hwi_provider:
id: app.provider.user_provider
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_provider: form.csrf_provider
oauth:
resource_owners:
facebook: "/login/check-facebook"
vkontakte: "/login/check-vkontakte"
login_path: /login
failure_path: /login
oauth_user_provider:
#this is my custom user provider, created from FOSUBUserProvider - will manage the
#automatic user registration on your site, with data from the provider (facebook. google, etc.)
service: app.provider.user_provider
logout: true
anonymous: true
login:
pattern: ^/login$
security: false
remember_me:
key: "%secret%"
lifetime: 60 # 365 days in seconds
path: /
domain: ~ # Defaults to the current domain from $_SERVER
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/, role: ROLE_ADMIN }
this my security
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
PillsBundle\Entity\User:
algorithm: sha1
encode_as_base64: false
iterations: 1
Symfony\Component\Security\Core\User\User: plaintext
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
providers:
fos_userbundle:
id: fos_user.user_provider.username
my_custom_hwi_provider:
id: app.provider.user_provider
chain_provider:
chain:
providers: [user_db, in_memory]
user_db:
entity: { class: UserBundle\Entity\User, property: email }
in_memory:
memory:
users:
admin_tyty: { password: adminpass_tyty, roles: [ 'ROLE_ADMIN' ] }
firewalls:
admin_secured_area:
pattern: /(.*)
anonymous: ~
form_login:
provider: chain_provider
login_path: /auth/login
check_path: /auth/login_check
always_use_default_target_path: true
default_target_path: /?r=db
logout:
path: /auth/logout
target: /
invalidate_session: false
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
pattern: ^/
form_login:
provider: fos_userbundle
#csrf_provider: form.csrf_provider
oauth:
resource_owners:
facebook: "/login/check-facebook"
vkontakte: "/login/check-vkontakte"
login_path: /login
failure_path: /login
oauth_user_provider:
#this is my custom user provider, created from FOSUBUserProvider - will manage the
#automatic user registration on your site, with data from the provider (facebook. google, etc.)
service: app.provider.user_provider
logout: true
anonymous: true
login:
pattern: ^/login$
security: false
remember_me:
key: "%secret%"
lifetime: 60 # 365 days in seconds
path: /
domain: ~ # Defaults to the current domain from $_SERVER
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/, role: ROLE_ADMIN }
and my SecurityController Controller
/**
* #Route("/auth")
*/
class SecurityController extends Controller
{
/**
* #Route("/login", name="login_route")
* #Template()
*/
public function loginAction()
{
$request = $this->getRequest();
$session = $request->getSession();
$securityContext = $this->container->get('security.context');
if ( $securityContext->isGranted('IS_AUTHENTICATED_FULLY') ) {
return $this->redirect($this->generateUrl('get_all_posts'));
}
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return array(
'_last' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
);
}
If you have override the registration controller then Just enable the user in FOSUserBundle > RegistrationController class
If not then have a look in to this doc.
http://symfony.com/doc/current/bundles/FOSUserBundle/overriding_controllers.html
RegistrationController extends BaseController
{
public function registerAction(Request $request)
{
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->get('fos_user.registration.form.factory');
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user = $userManager->createUser();
$user->setEnabled(true);
}
I know that it is a common thing but I can't find what mistake I'm doing and I'm getting crazy.
I can't login by a login form, when I submit the form, it returns to itself without error and not authenticated.
Thanks in advance!
Here is my security.yml
security:
encoders:
Symfony\Component\Security\Core\User\User: plaintext
#Cityincheck\AppBundle\Entity\User:
#algorithm: bcrypt
#cost: 12
role_hierarchy:
ROLE_ADMIN: ROLE_USER
providers:
in_memory:
memory:
users:
ryan:
password: ryanpass
roles: 'ROLE_USER'
admin:
password: kitten
roles: 'ROLE_ADMIN'
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login_firewall:
pattern: ^/login$
anonymous: ~
admin_area:
pattern: ^/*
form_login:
check_path: /login_check
login_path: /login
provider: in_memory
default_target_path: /admin
logout:
path: admin_logout
target: admin_login
#anonymous: ~
#http_basic:
# realm: "Secured Demo Area"
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin, roles: ROLE_ADMIN }
My routing.yml
admin_login:
path: /login
defaults: { _controller: AppBundle:AccessControl:login }
admin_login_check:
path: /login_check
And my controller:
class AccessControlController extends Controller
{
public function loginAction(Request $request)
{
$session = $request->getSession();
// get the login error if there is one
if ($request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(
SecurityContextInterface::AUTHENTICATION_ERROR
);
} elseif (null !== $session && $session->has(SecurityContextInterface::AUTHENTICATION_ERROR)) {
$error = $session->get(SecurityContextInterface::AUTHENTICATION_ERROR);
$session->remove(SecurityContextInterface::AUTHENTICATION_ERROR);
} else {
$error = null;
}
// last username entered by the user
$lastUsername = (null === $session) ? '' : $session->get(SecurityContextInterface::LAST_USERNAME);
return $this->render(
'AppBundle::login.html.twig',
array(
// last username entered by the user
'last_username' => $lastUsername,
'error' => $error,
)
);
}
}
The problem is in your security.yml. When somebody send form, browser sent HTTP request to /login_check to check login and password. But app don't allow to do it as user are not authenticated.
You must add '/login_check' to access_control
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/login_check, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin, roles: ROLE_ADMIN }
Or that
access_control:
- { path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin, roles: ROLE_ADMIN }
I have a custom user provider, following the guide in:
http://symfony.com/doc/current/cookbook/security/custom_provider.html
All is working without errors, but I don't manage to access the restricted zone.
In my UserProvider class, I set $roles var to have array("ROLE_USER") and that's the permission I need to access route app/list, but when I go to app/list, Symfony redirects me to login again and again.
I've seen the debug toolbar and it results:
Username anon.
Authenticated? yes
Roles { }
Token class Symfony\Component\Security\Core\Authentication\Token\AnonymousToken
My security.yml file is:
security:
firewalls:
secured_area:
pattern: ^/
anonymous: ~
form_login: ~
http_basic:
realm: "Secured Demo Area"
form_login:
provider: webservice
login_path: login
check_path: login_check
always_use_default_target_path: true
default_target_path: listado_actas
logout:
path: logout
target: login
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
providers:
webservice:
id: webservice_user_provider
encoders:
Symfony\Component\Security\Core\User\User: plaintext
Actas\Gestion\UserBundle\Security\User\WebServiceUser:
id: my.encoder.service
My UserProvider class looks like the following. I just call an XML service that gives me a TOKEN that I will store in my UserClass:
public function loadUserByUsername($username)
{
$salt = "";
$roles = "";
// make a call to your webservice here
$password = $this->request->get('_password');
$xml_interface = new XMLInterfaceBundle();
$token = $xml_interface->requestLogin($username, $password);
if (strlen($token) > 10) {
$roles = array("ROLE_USER");
$salt = "";
return new WebserviceUser($username, $password, $salt, $roles, $token);
}
throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
}
This is my UserObject in DaoAuthenticationProvider::checkAuthentication()
Actas\Gestion\UserBundle\Security\User\WebserviceUser Object
(
[username:Actas\Gestion\UserBundle\Security\User\WebserviceUser:private] => 44886706X
[password:Actas\Gestion\UserBundle\Security\User\WebserviceUser:private] => 44886706XkCrDP
[salt:Actas\Gestion\UserBundle\Security\User\WebserviceUser:private] =>
[roles:Actas\Gestion\UserBundle\Security\User\WebserviceUser:private] => Array
(
[0] => ROLE_ADMIN
)
[my_token:Actas\Gestion\UserBundle\Security\User\WebserviceUser:private] =>
)
This is my routing.yml:
xml_interface:
resource: "#XMLInterfaceBundle/Resources/config/routing.yml"
prefix: /
actas:
resource: "#ActasBundle/Resources/config/routing.yml"
prefix: /
login:
pattern: /login
defaults: { _controller: UserBundle:Default:login }
login_check:
pattern: /login_check
logout:
pattern: /logout
Just try to set the Role_hierarchy as following:
security:
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
Don't forget to set the role of your User object as ROLE_ADMIN, for example, in order to match the role_hierarchy.