Авторизация symfony 3.0
Делаю авторизацию на Symfony, в реализации особых проблем нет, настроил проверку из базы данных, всё работает:
# app/config/security.yml
security::
DeliveryAdminBundleEntityUser:
algorithm: bcrypt
providers:
user_db_provider:
entity:
class: DeliveryAdminBundle:User
property: username
firewalls:
main:
pattern: ^/admin
provider: user_db_provider
anonymous: ~
form_login:
login_path: _security_login #login route
check_path: _security_check #credentials check route
failure_path: _security_login #failed login route
default_target_path: a_home #successfull login route
logout:
path: _security_logout #logout route
target: a_home #route to redirect after logout
access_control:
- { path: ^/admin/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin, roles: ROLE_ADMIN }
Также нужно по тому же роуту ^/admin настроить прямую авторизацию без ввода логина/пароля, а передавая в url тип авторизации – email, hash для проверки и авторизовывать в случае успешной проверки.
Здесь https://habrahabr.ru/post/134005/ описана реализация, но не могу разобраться как система будет “понимать”, какой тип использовать – прямой или через форму входа?
Как настроить авторизацию в symfony2?
Приветствую всех. Помогите, пожалуйста, разобраться и найти ошибку. Пытаюсь настроить авторизацию для админов сайта. Админов храню в базе. Делаю все по документации но авторизоваться никак не получается. При попытке авторизоваться отправляется форма и ничего не происходит.
#security.yml
security:
encoders:
AppMainBundleEntityUser:
algorithm: bcrypt
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
providers:
main_db_provider:
entity:
class: AppMainBundle:User
property: username
manager_name: ~
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login_firewall:
pattern: ^/admin/login$
anonymous: ~
main:
pattern: ^/
form_login:
check_path: app_main_admin_login
login_path: app_main_admin_login
always_use_default_target_path: true
default_target_path: app_main_admin_products_list
logout:
path: main_admin_logout
target: app_main_homepage
anonymous: ~
provider: main_db_provider
access_control:
- { path: ^/admin/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin, roles: ROLE_ADMIN }
#AppMainBundle/Entity/User
<?php
namespace AppMainBundleEntity;
use DoctrineORMMapping as ORM;
use SymfonyComponentSecurityCoreUserUserInterface;
/**
* User
*
* @ORMTable(name="users")
* @ORMEntity(repositoryClass="AppMainBundleRepositoryUserRepository")
*/
class User implements UserInterface, Serializable
{
/**
* @ORMColumn(type="integer")
* @ORMId
* @ORMGeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORMColumn(type="string", length=25, unique=true)
*/
private $username;
/**
* @ORMColumn(type="string", length=64)
*/
private $password;
/**
* @ORMColumn(name="is_active", type="boolean")
*/
private $isActive;
/**
* User constructor.
*/
public function __construct()
{
$this->isActive = true;
}
/**
* @return mixed
*/
public function getUsername()
{
return $this->username;
}
/**
* @return null
*/
public function getSalt()
{
return null;
}
/**
* @return mixed
*/
public function getPassword()
{
return $this->password;
}
/**
* @return array
*/
public function getRoles()
{
return array('ROLE_ADMIN');
}
public function eraseCredentials()
{
}
/** @see Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
));
}
/** @see Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
) = unserialize($serialized);
}
}
# AppMainBundle/Controller/SecurityController
<?php
namespace AppMainBundleController;
use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationRequest;
use SensioBundleFrameworkExtraBundleConfigurationTemplate;
use SymfonyComponentSecurityHttpAuthenticationAuthenticationUtils;
class SecurityController extends Controller
{
/**
* @var AuthenticationUtils
*/
private $authenticationUtils;
/**
* SecurityController constructor.
* @param AuthenticationUtils $authenticationUtils
*/
public function __construct(AuthenticationUtils $authenticationUtils)
{
$this->authenticationUtils = $authenticationUtils;
}
/**
* @Template("AppMainBundle:Auth:login.html.twig")
*
* @param Request $request
* @return array
*/
public function loginAction(Request $request)
{
$error = $this->authenticationUtils->getLastAuthenticationError();
$lastUsername = $this->authenticationUtils->getLastUsername();
return [
'last_username' => $lastUsername,
'error' => $error,
];
}
}
# login form
{% extends 'AppMainBundle::layout.html.twig' %}
{% block content %}
{% if error %}
<div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
<div class="content login">
<form action="{{ path('app_main_admin_login') }}" method="post" class="login__form">
<div class="login__inner">
<label class="login__form__label text" for="username">Логин</label><!--
--><input class="login__form__inp"
type="text"
id="username"
name="_username"
placeholder="Логин"
value="{{ last_username }}"/>
</div>
<div class="login__inner">
<label class="login__form__label text" for="password">Пароль</label><!--
--><input class="login__form__inp"
type="password"
id="password"
placeholder="Пароль"
name="_password"/>
</div>
<div class="login__inner">
<button class="login__form__btn" type="submit">Войти</button>
</div>
</form>
</div>
{% endblock %}
#routings
app_main_admin_login:
path: /admin/login
defaults: { _controller: app_main.security_controller:loginAction }