Validating username password with LexikJWTAuthenticationBundle before authentication
I want to perform traditional validation of username( character count and valid email) and password (character count) before authentication is performed.
The users are in database and I don't want to hit the database before this validation gives a go.
I have LexikJWTAuthenticationBundle set up with Symfony 4.1 and it is working. There is no controller as the authentication is completely being handled by the bundle.
I am not sure how can I perform above mentioned validation. Please help.
Find below my security config to get some idea what I already have set up.
security:
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH ]
encoders:
AppEntityUser:
id: app.bcrypt_plus_encoder
providers:
db_user_provider:
entity:
class: AppEntityUser
# the property to query by - e.g. username, email, etc
property: email
# if you're using multiple entity managers
# manager_name: customer
firewalls:
guest:
pattern: ^/api/guest
stateless: true
anonymous: true
login:
pattern: ^/api/login
user_checker: AppSecurityUserChecker
stateless: true
anonymous: true
provider: db_user_provider
json_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: AppSecurityHttpAuthenticationAuthenticationFailureHandler
require_previous_session: false
username_path: email
password_path: passw
api:
pattern: ^/api
stateless: true
guard:
provider: db_user_provider
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
access_control:
- { path: ^/api/guest, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
symfony validation jwt symfony4 lexikjwtauthbundle
|
show 1 more comment
I want to perform traditional validation of username( character count and valid email) and password (character count) before authentication is performed.
The users are in database and I don't want to hit the database before this validation gives a go.
I have LexikJWTAuthenticationBundle set up with Symfony 4.1 and it is working. There is no controller as the authentication is completely being handled by the bundle.
I am not sure how can I perform above mentioned validation. Please help.
Find below my security config to get some idea what I already have set up.
security:
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH ]
encoders:
AppEntityUser:
id: app.bcrypt_plus_encoder
providers:
db_user_provider:
entity:
class: AppEntityUser
# the property to query by - e.g. username, email, etc
property: email
# if you're using multiple entity managers
# manager_name: customer
firewalls:
guest:
pattern: ^/api/guest
stateless: true
anonymous: true
login:
pattern: ^/api/login
user_checker: AppSecurityUserChecker
stateless: true
anonymous: true
provider: db_user_provider
json_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: AppSecurityHttpAuthenticationAuthenticationFailureHandler
require_previous_session: false
username_path: email
password_path: passw
api:
pattern: ^/api
stateless: true
guard:
provider: db_user_provider
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
access_control:
- { path: ^/api/guest, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
symfony validation jwt symfony4 lexikjwtauthbundle
i seems like you need to create a EventListener onKernelRequest before the authentication
– Puya Sarmidani
Nov 21 '18 at 20:34
Did you try annotation validation, my be it will be fired?
– Ahmed bhs
Nov 21 '18 at 21:00
@AhmedEBENHASSINE I didn't try annotation but i tried YAML. It is not fired.
– Himal
Nov 21 '18 at 23:02
@PuyaSarmidani I am not a huge fan of events, I think they just add extra burden and makes architecture less organized, but I think there is no other way either.
– Himal
Nov 21 '18 at 23:04
I think my first idea was wrong, anyway I tried to override the SymfonyComponentSecurityHttpFirewallUsernamePasswordFormAuthenticationListener but It throws an exception ...
– Ahmed bhs
Nov 23 '18 at 18:51
|
show 1 more comment
I want to perform traditional validation of username( character count and valid email) and password (character count) before authentication is performed.
The users are in database and I don't want to hit the database before this validation gives a go.
I have LexikJWTAuthenticationBundle set up with Symfony 4.1 and it is working. There is no controller as the authentication is completely being handled by the bundle.
I am not sure how can I perform above mentioned validation. Please help.
Find below my security config to get some idea what I already have set up.
security:
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH ]
encoders:
AppEntityUser:
id: app.bcrypt_plus_encoder
providers:
db_user_provider:
entity:
class: AppEntityUser
# the property to query by - e.g. username, email, etc
property: email
# if you're using multiple entity managers
# manager_name: customer
firewalls:
guest:
pattern: ^/api/guest
stateless: true
anonymous: true
login:
pattern: ^/api/login
user_checker: AppSecurityUserChecker
stateless: true
anonymous: true
provider: db_user_provider
json_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: AppSecurityHttpAuthenticationAuthenticationFailureHandler
require_previous_session: false
username_path: email
password_path: passw
api:
pattern: ^/api
stateless: true
guard:
provider: db_user_provider
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
access_control:
- { path: ^/api/guest, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
symfony validation jwt symfony4 lexikjwtauthbundle
I want to perform traditional validation of username( character count and valid email) and password (character count) before authentication is performed.
The users are in database and I don't want to hit the database before this validation gives a go.
I have LexikJWTAuthenticationBundle set up with Symfony 4.1 and it is working. There is no controller as the authentication is completely being handled by the bundle.
I am not sure how can I perform above mentioned validation. Please help.
Find below my security config to get some idea what I already have set up.
security:
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH ]
encoders:
AppEntityUser:
id: app.bcrypt_plus_encoder
providers:
db_user_provider:
entity:
class: AppEntityUser
# the property to query by - e.g. username, email, etc
property: email
# if you're using multiple entity managers
# manager_name: customer
firewalls:
guest:
pattern: ^/api/guest
stateless: true
anonymous: true
login:
pattern: ^/api/login
user_checker: AppSecurityUserChecker
stateless: true
anonymous: true
provider: db_user_provider
json_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: AppSecurityHttpAuthenticationAuthenticationFailureHandler
require_previous_session: false
username_path: email
password_path: passw
api:
pattern: ^/api
stateless: true
guard:
provider: db_user_provider
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
access_control:
- { path: ^/api/guest, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
symfony validation jwt symfony4 lexikjwtauthbundle
symfony validation jwt symfony4 lexikjwtauthbundle
edited Nov 22 '18 at 8:18


Ahmed bhs
9111521
9111521
asked Nov 21 '18 at 20:16
HimalHimal
61
61
i seems like you need to create a EventListener onKernelRequest before the authentication
– Puya Sarmidani
Nov 21 '18 at 20:34
Did you try annotation validation, my be it will be fired?
– Ahmed bhs
Nov 21 '18 at 21:00
@AhmedEBENHASSINE I didn't try annotation but i tried YAML. It is not fired.
– Himal
Nov 21 '18 at 23:02
@PuyaSarmidani I am not a huge fan of events, I think they just add extra burden and makes architecture less organized, but I think there is no other way either.
– Himal
Nov 21 '18 at 23:04
I think my first idea was wrong, anyway I tried to override the SymfonyComponentSecurityHttpFirewallUsernamePasswordFormAuthenticationListener but It throws an exception ...
– Ahmed bhs
Nov 23 '18 at 18:51
|
show 1 more comment
i seems like you need to create a EventListener onKernelRequest before the authentication
– Puya Sarmidani
Nov 21 '18 at 20:34
Did you try annotation validation, my be it will be fired?
– Ahmed bhs
Nov 21 '18 at 21:00
@AhmedEBENHASSINE I didn't try annotation but i tried YAML. It is not fired.
– Himal
Nov 21 '18 at 23:02
@PuyaSarmidani I am not a huge fan of events, I think they just add extra burden and makes architecture less organized, but I think there is no other way either.
– Himal
Nov 21 '18 at 23:04
I think my first idea was wrong, anyway I tried to override the SymfonyComponentSecurityHttpFirewallUsernamePasswordFormAuthenticationListener but It throws an exception ...
– Ahmed bhs
Nov 23 '18 at 18:51
i seems like you need to create a EventListener onKernelRequest before the authentication
– Puya Sarmidani
Nov 21 '18 at 20:34
i seems like you need to create a EventListener onKernelRequest before the authentication
– Puya Sarmidani
Nov 21 '18 at 20:34
Did you try annotation validation, my be it will be fired?
– Ahmed bhs
Nov 21 '18 at 21:00
Did you try annotation validation, my be it will be fired?
– Ahmed bhs
Nov 21 '18 at 21:00
@AhmedEBENHASSINE I didn't try annotation but i tried YAML. It is not fired.
– Himal
Nov 21 '18 at 23:02
@AhmedEBENHASSINE I didn't try annotation but i tried YAML. It is not fired.
– Himal
Nov 21 '18 at 23:02
@PuyaSarmidani I am not a huge fan of events, I think they just add extra burden and makes architecture less organized, but I think there is no other way either.
– Himal
Nov 21 '18 at 23:04
@PuyaSarmidani I am not a huge fan of events, I think they just add extra burden and makes architecture less organized, but I think there is no other way either.
– Himal
Nov 21 '18 at 23:04
I think my first idea was wrong, anyway I tried to override the SymfonyComponentSecurityHttpFirewallUsernamePasswordFormAuthenticationListener but It throws an exception ...
– Ahmed bhs
Nov 23 '18 at 18:51
I think my first idea was wrong, anyway I tried to override the SymfonyComponentSecurityHttpFirewallUsernamePasswordFormAuthenticationListener but It throws an exception ...
– Ahmed bhs
Nov 23 '18 at 18:51
|
show 1 more comment
1 Answer
1
active
oldest
votes
Hello if you want to handle request username and password, you can just add Guard Authenticator and add your logical condition in << supports >> function like this :
<?php
namespace AppSecurity;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentSecurityCoreExceptionUsernameNotFoundException;
class UserAuthenticator extends AbstractGuardAuthenticator
{
public function supports(Request $request)
{
// here you can handle your request an throw exception if not valid
// throw new UsernameNotFoundException(
// sprintf('Username "%s" does not exist.', 'test')
// );
// dump($request->getContent());die;
return $request->headers->has('X-AUTH-TOKEN');
}
public function getCredentials(Request $request)
{
return array(
'token' => $request->headers->get('X-AUTH-TOKEN'),
);
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$apiKey = $credentials['token'];
if (null === $apiKey) {
return;
}
return $userProvider->loadUserByUsername($apiKey);
}
public function checkCredentials($credentials, UserInterface $user)
{
return true;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = array(
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
);
return new JsonResponse($data, Response::HTTP_FORBIDDEN);
}
public function start(Request $request, AuthenticationException $authException = null)
{
$data = array(
// you might translate this message
'message' => 'Authentication Required'
);
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
public function supportsRememberMe()
{
return false;
}
}
and just add your Guard in security.yml like this :
security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
encoders:
AppEntityUser: bcrypt
providers:
jwt:
lexik_jwt: ~
user_provider:
entity:
class: AppEntityUser
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/api/login
stateless: true
anonymous: true
provider: user_provider
json_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
guard:
authenticators:
- AppSecurityUserAuthenticator
Could you explain why support and nit checkCredentials() function ?
– Ahmed bhs
Nov 24 '18 at 11:34
you can see it in this url: symfony.com/doc/current/security/guard_authentication.html
– rapaelec
Nov 25 '18 at 8:22
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53419857%2fvalidating-username-password-with-lexikjwtauthenticationbundle-before-authentica%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Hello if you want to handle request username and password, you can just add Guard Authenticator and add your logical condition in << supports >> function like this :
<?php
namespace AppSecurity;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentSecurityCoreExceptionUsernameNotFoundException;
class UserAuthenticator extends AbstractGuardAuthenticator
{
public function supports(Request $request)
{
// here you can handle your request an throw exception if not valid
// throw new UsernameNotFoundException(
// sprintf('Username "%s" does not exist.', 'test')
// );
// dump($request->getContent());die;
return $request->headers->has('X-AUTH-TOKEN');
}
public function getCredentials(Request $request)
{
return array(
'token' => $request->headers->get('X-AUTH-TOKEN'),
);
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$apiKey = $credentials['token'];
if (null === $apiKey) {
return;
}
return $userProvider->loadUserByUsername($apiKey);
}
public function checkCredentials($credentials, UserInterface $user)
{
return true;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = array(
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
);
return new JsonResponse($data, Response::HTTP_FORBIDDEN);
}
public function start(Request $request, AuthenticationException $authException = null)
{
$data = array(
// you might translate this message
'message' => 'Authentication Required'
);
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
public function supportsRememberMe()
{
return false;
}
}
and just add your Guard in security.yml like this :
security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
encoders:
AppEntityUser: bcrypt
providers:
jwt:
lexik_jwt: ~
user_provider:
entity:
class: AppEntityUser
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/api/login
stateless: true
anonymous: true
provider: user_provider
json_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
guard:
authenticators:
- AppSecurityUserAuthenticator
Could you explain why support and nit checkCredentials() function ?
– Ahmed bhs
Nov 24 '18 at 11:34
you can see it in this url: symfony.com/doc/current/security/guard_authentication.html
– rapaelec
Nov 25 '18 at 8:22
add a comment |
Hello if you want to handle request username and password, you can just add Guard Authenticator and add your logical condition in << supports >> function like this :
<?php
namespace AppSecurity;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentSecurityCoreExceptionUsernameNotFoundException;
class UserAuthenticator extends AbstractGuardAuthenticator
{
public function supports(Request $request)
{
// here you can handle your request an throw exception if not valid
// throw new UsernameNotFoundException(
// sprintf('Username "%s" does not exist.', 'test')
// );
// dump($request->getContent());die;
return $request->headers->has('X-AUTH-TOKEN');
}
public function getCredentials(Request $request)
{
return array(
'token' => $request->headers->get('X-AUTH-TOKEN'),
);
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$apiKey = $credentials['token'];
if (null === $apiKey) {
return;
}
return $userProvider->loadUserByUsername($apiKey);
}
public function checkCredentials($credentials, UserInterface $user)
{
return true;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = array(
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
);
return new JsonResponse($data, Response::HTTP_FORBIDDEN);
}
public function start(Request $request, AuthenticationException $authException = null)
{
$data = array(
// you might translate this message
'message' => 'Authentication Required'
);
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
public function supportsRememberMe()
{
return false;
}
}
and just add your Guard in security.yml like this :
security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
encoders:
AppEntityUser: bcrypt
providers:
jwt:
lexik_jwt: ~
user_provider:
entity:
class: AppEntityUser
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/api/login
stateless: true
anonymous: true
provider: user_provider
json_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
guard:
authenticators:
- AppSecurityUserAuthenticator
Could you explain why support and nit checkCredentials() function ?
– Ahmed bhs
Nov 24 '18 at 11:34
you can see it in this url: symfony.com/doc/current/security/guard_authentication.html
– rapaelec
Nov 25 '18 at 8:22
add a comment |
Hello if you want to handle request username and password, you can just add Guard Authenticator and add your logical condition in << supports >> function like this :
<?php
namespace AppSecurity;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentSecurityCoreExceptionUsernameNotFoundException;
class UserAuthenticator extends AbstractGuardAuthenticator
{
public function supports(Request $request)
{
// here you can handle your request an throw exception if not valid
// throw new UsernameNotFoundException(
// sprintf('Username "%s" does not exist.', 'test')
// );
// dump($request->getContent());die;
return $request->headers->has('X-AUTH-TOKEN');
}
public function getCredentials(Request $request)
{
return array(
'token' => $request->headers->get('X-AUTH-TOKEN'),
);
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$apiKey = $credentials['token'];
if (null === $apiKey) {
return;
}
return $userProvider->loadUserByUsername($apiKey);
}
public function checkCredentials($credentials, UserInterface $user)
{
return true;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = array(
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
);
return new JsonResponse($data, Response::HTTP_FORBIDDEN);
}
public function start(Request $request, AuthenticationException $authException = null)
{
$data = array(
// you might translate this message
'message' => 'Authentication Required'
);
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
public function supportsRememberMe()
{
return false;
}
}
and just add your Guard in security.yml like this :
security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
encoders:
AppEntityUser: bcrypt
providers:
jwt:
lexik_jwt: ~
user_provider:
entity:
class: AppEntityUser
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/api/login
stateless: true
anonymous: true
provider: user_provider
json_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
guard:
authenticators:
- AppSecurityUserAuthenticator
Hello if you want to handle request username and password, you can just add Guard Authenticator and add your logical condition in << supports >> function like this :
<?php
namespace AppSecurity;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentSecurityCoreExceptionUsernameNotFoundException;
class UserAuthenticator extends AbstractGuardAuthenticator
{
public function supports(Request $request)
{
// here you can handle your request an throw exception if not valid
// throw new UsernameNotFoundException(
// sprintf('Username "%s" does not exist.', 'test')
// );
// dump($request->getContent());die;
return $request->headers->has('X-AUTH-TOKEN');
}
public function getCredentials(Request $request)
{
return array(
'token' => $request->headers->get('X-AUTH-TOKEN'),
);
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$apiKey = $credentials['token'];
if (null === $apiKey) {
return;
}
return $userProvider->loadUserByUsername($apiKey);
}
public function checkCredentials($credentials, UserInterface $user)
{
return true;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = array(
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
);
return new JsonResponse($data, Response::HTTP_FORBIDDEN);
}
public function start(Request $request, AuthenticationException $authException = null)
{
$data = array(
// you might translate this message
'message' => 'Authentication Required'
);
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
public function supportsRememberMe()
{
return false;
}
}
and just add your Guard in security.yml like this :
security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
encoders:
AppEntityUser: bcrypt
providers:
jwt:
lexik_jwt: ~
user_provider:
entity:
class: AppEntityUser
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/api/login
stateless: true
anonymous: true
provider: user_provider
json_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
guard:
authenticators:
- AppSecurityUserAuthenticator
<?php
namespace AppSecurity;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentSecurityCoreExceptionUsernameNotFoundException;
class UserAuthenticator extends AbstractGuardAuthenticator
{
public function supports(Request $request)
{
// here you can handle your request an throw exception if not valid
// throw new UsernameNotFoundException(
// sprintf('Username "%s" does not exist.', 'test')
// );
// dump($request->getContent());die;
return $request->headers->has('X-AUTH-TOKEN');
}
public function getCredentials(Request $request)
{
return array(
'token' => $request->headers->get('X-AUTH-TOKEN'),
);
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$apiKey = $credentials['token'];
if (null === $apiKey) {
return;
}
return $userProvider->loadUserByUsername($apiKey);
}
public function checkCredentials($credentials, UserInterface $user)
{
return true;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = array(
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
);
return new JsonResponse($data, Response::HTTP_FORBIDDEN);
}
public function start(Request $request, AuthenticationException $authException = null)
{
$data = array(
// you might translate this message
'message' => 'Authentication Required'
);
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
public function supportsRememberMe()
{
return false;
}
}
<?php
namespace AppSecurity;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentSecurityCoreExceptionUsernameNotFoundException;
class UserAuthenticator extends AbstractGuardAuthenticator
{
public function supports(Request $request)
{
// here you can handle your request an throw exception if not valid
// throw new UsernameNotFoundException(
// sprintf('Username "%s" does not exist.', 'test')
// );
// dump($request->getContent());die;
return $request->headers->has('X-AUTH-TOKEN');
}
public function getCredentials(Request $request)
{
return array(
'token' => $request->headers->get('X-AUTH-TOKEN'),
);
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$apiKey = $credentials['token'];
if (null === $apiKey) {
return;
}
return $userProvider->loadUserByUsername($apiKey);
}
public function checkCredentials($credentials, UserInterface $user)
{
return true;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = array(
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
);
return new JsonResponse($data, Response::HTTP_FORBIDDEN);
}
public function start(Request $request, AuthenticationException $authException = null)
{
$data = array(
// you might translate this message
'message' => 'Authentication Required'
);
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
public function supportsRememberMe()
{
return false;
}
}
security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
encoders:
AppEntityUser: bcrypt
providers:
jwt:
lexik_jwt: ~
user_provider:
entity:
class: AppEntityUser
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/api/login
stateless: true
anonymous: true
provider: user_provider
json_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
guard:
authenticators:
- AppSecurityUserAuthenticator
security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
encoders:
AppEntityUser: bcrypt
providers:
jwt:
lexik_jwt: ~
user_provider:
entity:
class: AppEntityUser
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/api/login
stateless: true
anonymous: true
provider: user_provider
json_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
guard:
authenticators:
- AppSecurityUserAuthenticator
answered Nov 24 '18 at 0:38


rapaelecrapaelec
18724
18724
Could you explain why support and nit checkCredentials() function ?
– Ahmed bhs
Nov 24 '18 at 11:34
you can see it in this url: symfony.com/doc/current/security/guard_authentication.html
– rapaelec
Nov 25 '18 at 8:22
add a comment |
Could you explain why support and nit checkCredentials() function ?
– Ahmed bhs
Nov 24 '18 at 11:34
you can see it in this url: symfony.com/doc/current/security/guard_authentication.html
– rapaelec
Nov 25 '18 at 8:22
Could you explain why support and nit checkCredentials() function ?
– Ahmed bhs
Nov 24 '18 at 11:34
Could you explain why support and nit checkCredentials() function ?
– Ahmed bhs
Nov 24 '18 at 11:34
you can see it in this url: symfony.com/doc/current/security/guard_authentication.html
– rapaelec
Nov 25 '18 at 8:22
you can see it in this url: symfony.com/doc/current/security/guard_authentication.html
– rapaelec
Nov 25 '18 at 8:22
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53419857%2fvalidating-username-password-with-lexikjwtauthenticationbundle-before-authentica%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
i seems like you need to create a EventListener onKernelRequest before the authentication
– Puya Sarmidani
Nov 21 '18 at 20:34
Did you try annotation validation, my be it will be fired?
– Ahmed bhs
Nov 21 '18 at 21:00
@AhmedEBENHASSINE I didn't try annotation but i tried YAML. It is not fired.
– Himal
Nov 21 '18 at 23:02
@PuyaSarmidani I am not a huge fan of events, I think they just add extra burden and makes architecture less organized, but I think there is no other way either.
– Himal
Nov 21 '18 at 23:04
I think my first idea was wrong, anyway I tried to override the SymfonyComponentSecurityHttpFirewallUsernamePasswordFormAuthenticationListener but It throws an exception ...
– Ahmed bhs
Nov 23 '18 at 18:51