JWT Token always return as Not Found Symfony2.8 - symfony-2.8

Hi I have configured lexik/jwt-authentication-bundle:v2.4 with Symfony2.8 And Following is my config.yml.
lexik_jwt_authentication:
private_key_path: "%kernel.root_dir%/config/jwt/private.pem" #
required for token creation
public_key_path: "%kernel.root_dir%/config/jwt/public.pem" #
required for token verification
pass_phrase: "%jwt_key_pass_phrase%" # required for token
creation, usage of an environment variable is recommended
token_ttl: 3600
And this is security.yml
firewalls:
login:
pattern: ^/api/login
stateless: true
anonymous: true
form_login:
check_path: /api/login_check
username_parameter: username
password_parameter: password
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
api:
pattern: ^/api
stateless: true
provider: my_provider
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
I am trying to get JWT Token using post man.
http://localhost/j1/web/app_dev.php/api/login_check
I get the Token as.
{
"token": "eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwidXNlcm5hbWUiOiJpbmZvQGFtaXJmcmVlbGFuY2UuY29tIiwiaWF0IjoxNTUwODQ0NjQ0LCJleHAiOjE1NTA4NDgyNDR9.YKDrQ7_PaMOoW3m_reWhGb8PoNkc6wsB9EX86JNwGW4yAeG7ezqvgA4Je6AUD6BtZgGExs2oFsJTWoTAAjCyf4ZyCoUaZ7m_M7s4tJkStHgR64q1kwl1bNu21Lj0sbuAs9jjxRHzHzcNE-v8eoQf26iiXvcT1WTfhEiWQ97xtWbnTTqYzt38BjgVrqDIWDrV2CaaX-W0mHb1Ibif1VkHTgRziq1gWYgv7nqIvVVDynjIueP1HBGVBSvJPKAzzSZNWE5rcijtNVHRuH_UV0vafq1owMs8KQ8vu6pK2lH22ozHkb8V0MWHeXloHGGznAHyFnY4NPPHOwQ74hQfRT2_ibgoJ8VHtoGDsxY_8n56uIRykxk1YoXYPBEZHVEF9rCZSzCm693U-I1JNM2o6thj81tBBzTEce6csa4TbYuBEybx4zBb3pHNGAYqF3qEis63ZCzlgYsPrWOqReljfMA61QqcMcs15g6iEJ5aABgxK0FF2AuFx4_fkUDJHrZOmiasxE3ATiO4tEEf4DPizLjMsnmXgzvWkzVt1-SjBUxFLJWPGA8pCvGXrXA4-giQLWCThQ_zJ7hbGJl1_rVLT-KBoBgjV0OYaoeINh2rWXXypqo36Xh02I62_vReOCcw-He5rX6TsCuyyNAHBnP2CufC47fP-8L_ZSPWYjPxxdgOlK4"
}
And I am sending the token to validate the token.
http://localhost/j1/web/app_dev.php/api/locationData/8489
Authorization: Bearer {token} with the request using post man. But I am getting alwas the result as JWT Not Found.
"code":401,"message":"JWT Token not found"}
So I have debug the code with JWTTokenAuthenticator , I found it get Authorization header in request properly, but the following method does not return the token back.
$jsonWebToken = $tokenExtractor->extract($request)
Here this alwasy return false. What to do can any one guide me please.
Thanks in advance.

Related

Using LexikJWTAuthenticationBundle with an LDAP Provider

I have a project that use Symfony API-Platform. I want to use LexikJWTAuthenticationBundle on my project but my users are stored in an Active Directory so I set an LDAP UserProvider. I tried to combine the setting of the two following documentation without success :
https://api-platform.com/docs/core/jwt/
https://symfony.com/doc/current/components/ldap.html
Here is what I have done
In security.yml :
security:
providers:
my_ldap:
ldap:
service: Symfony\Component\Ldap\Ldap
base_dn: OU=organization_unit,DC=domain,DC=local
search_dn: "OU=organization_unit,DC=domain,DC=local"
search_password: '%env(resolve:LDAP_PASSWORD)%'
default_roles: ROLE_USER
uid_key: uid
firewalls:
login:
pattern: ^/api/login
stateless: true
anonymous: true
json_login:
provider: my_ldap
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
api:
pattern: ^/api/
stateless: true
guard:
provider: my_ldap
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
In services.yml :
Symfony\Component\Ldap\Ldap:
arguments: ['#Symfony\Component\Ldap\Adapter\ExtLdap\Adapter']
Symfony\Component\Ldap\Adapter\ExtLdap\Adapter:
arguments:
- host: '%env(resolve:LDAP_HOST)%'
port: 636
# encryption: tls
options:
protocol_version: 3
referrals: false
But when I try to send the request to my_domain/api/login_check with following content :
{
"username": "my_user",
"password": "my_password"
}
I received this error as response:
{"code":401,"message":"Invalid credentials."}
I have resolved my issue by using a custom action that checks if the user exist using LDAP and get its roles. Then, if the freshly retrieved user is authorized to use the application, I create a new token and return it in the response. And finally the token is used to authentify the user for each call he do to the API.
Here is my security.yml
providers:
# provider to retrieve user from LDAP
my_ldap:
id: App\Security\LdapService
# provider to retrieve user from user
jwt:
lexik_jwt:
class: App\Security\User
firewalls:
login:
pattern: ^/api/login
stateless: true
anonymous: true
api:
pattern: ^/api/
stateless: true
guard:
provider: jwt
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
The login action in controller :
/**
* #Route("/api/login", name="api_login", methods={"POST"})
*/
public function loginCheck(Request $request, LdapService $ldapService, AuthenticationSuccessHandler $authenticationSuccessHandler, AuthenticationFailureHandler $authenticationFailureHandler){
$content = json_decode($request->getContent());
$response= new JsonResponse();
try{
$user=$ldapService->authenticate($content->username, $content->password);
return $authenticationSuccessHandler->handleAuthenticationSuccess($user);
}catch(AuthenticationException $e){
return $authenticationFailureHandler->onAuthenticationFailure($request, $e);
}
return $response;
}

Symfony not redirecting to login in AccessDeniedException

In my Symfony project (3.4) in AccessDenied Exception, it does not redirect to login path. Normally in Symfony projects if the user is not authenticated, it redirects to the login url. Is there anything which is needed to do in configuration?
Below is my security.yml
security:
access_denied_url: /oauth/v2/auth/login
encoders:
Symfony\Component\Security\Core\User\User: plaintext
Walkingspree\APIAuthBundle\Security\WebserviceUser:
algorithm: md5
iterations: 1
encode_as_base64: false
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
# https://symfony.com/doc/current/security.html#b-configuring-how-users-are-loaded
providers:
in_memory:
memory: ~
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
oauth_token:
pattern: ^/oauth/v2/token
security: false
oauth_authorize:
pattern: ^/oauth/v2/auth
anonymous: true
stateless: false
#form_login:
# provider: walkingspree_members
# login_path: /oauth/v2/auth/login
# check_path: /oauth/v2/auth/login/check
logout:
path: /oauth/logout
target: /
register:
pattern: ^/service/register
security: false
resetpw:
pattern: ^/service/account/password/reset
security: false
site:
pattern: ^/service/
fos_oauth: true
stateless: true
# 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
access_control:
- { path: ^/api, roles: ROLE_USER } #form_login: ~
# { path: ^/auth/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
Thank you.
[2018-10-11 12:52:55] request.INFO: Matched route "fos_oauth_server_authorize". {"route":"fos_oauth_server_authorize","route_parameters":{"_controller":"fos_oauth_server.controller.authorize:authorizeAction","_route":"fos_oauth_server_authorize"},"request_uri":"http://localhost/oauth/v2/auth?client_id=3_5m8giw18bkowccck8k0s8gwooockscgskkkwscsgcgsosogog0&redirect_uri=https%3A%2F%2Fapi.walkingspree.com%2FNaS&response_type=code","method":"GET"} []
[2018-10-11 12:52:55] security.INFO: Populated the TokenStorage with an anonymous Token. [] []
[2018-10-11 12:52:55] event.DEBUG: Notified event "kernel.controller_arguments" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\IsGrantedListener::onKernelControllerArguments". {"event":"kernel.controller_arguments","listener":"Sensio\\Bundle\\FrameworkExtraBundle\\EventListener\\IsGrantedListener::onKernelControllerArguments"} []
[2018-10-11 12:52:55] security.DEBUG: Access denied, the user is not fully authenticated; redirecting to authentication entry point. {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException(code: 403): This user does not have access to this section. at /srv/com.walkingspree.api/vendor/friendsofsymfony/oauth-server-bundle/Controller/AuthorizeController.php:157)"} []
[2018-10-11 12:52:55] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException: "Full authentication is required to access this resource." at /srv/com.walkingspree.api/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php line 126 {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\InsufficientAuthenticationException(code: 0): Full authentication is required to access this resource. at /srv/com.walkingspree.api/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php:126, Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException(code: 403): This user does not have access to this section. at /srv/com.walkingspree.api/vendor/friendsofsymfony/oauth-server-bundle/Controller/AuthorizeController.php:157)"} []

Symfony2: Access anonymously path

I use the FOSRestbundle with mopa/wsse-authentication-bundle (WSSE authentication).
Everything works fine (Authentication and RESTful api).
But i want to make 1 specific path public (without authentication).
Path i want to make public: ^/api/users
I tried following settings but i still get a 403 Forbidden status for the api/users path.
(security.yml)
jms_security_extra:
secure_all_services: false
expressions: true
security:
encoders:
***\UserBundle\Entity\User: plaintext
role_hierarchy:
ROLE_USER: [ROLE_API_USER]
providers:
***_users:
entity: { class: UserBundle:User }
firewalls:
wsse_secured:
pattern: ^/api
anonymous: true
stateless: true
wsse:
nonce_dir: null
lifetime: 300
provider: ***_users
access_control:
- { path: ^/api/users, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/(css|js), roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/(_wdt|_profiler)
If you want to make api/users/ page public that is accessible to everybody without any sort of authentication, you can think of keeping out of WSSE authentication. To do that, you can specify the url pattern for which WSSE authentication will not be applied. e.g. in below example I have specified a pattern to skip URLs having the form as "api/users/".
in short I am suggesting to skip WSSE authentication for the "users" page using the "pattern"
wsse_secured:
pattern: ^/api/[^users].*
wsse:
nonce_dir: null
lifetime: 300
provider: ***_users

Sitewide http auth interfering with Symfony2 app authentication

I have a site under development with the following structure:
public_html/
index.php
symfony_app/
other_app/
Currently I have the root of the site behind Basic HTTP authentication during the development testing phase. I couldn't figure out why my Symfony2 authentication for a valid user (myusername) was always redirecting to the Symfony login page. In the logs after successful Symfony login
security.INFO: User "myusername" has been authenticated successfully [] []
I found:
security.INFO: Basic Authentication Authorization header found for user "otherusername" [] []
..which is the user required by .htpasswd in the root of the site. So it seems that I have an issue with, for lack of a better term, nested http authentication.
Is it possible to have a Symfony app living behind http auth without the two clashing?
Security.yml
jms_security_extra:
secure_all_services: false
expressions: true
security:
encoders:
My\UserBundle\Entity\User:
algorithm: sha1
encode_as_base64: false
iterations: 1
role_hierarchy:
ROLE_ADMIN: ROLE_USER
providers:
administrators:
entity: { class: MyUserBundle:User }
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/login$
security: false
secured_area:
pattern: ^/
http_basic: ~
form_login:
login_path: login
check_path: login_check
always_use_default_target_path: true
logout:
path: /logout
switch_user: true
access_control:
- { path: ^/, roles: ROLE_USER, requires_channel: https }

Symfony2: login does not work on first try after clearing cookies

When trying to log in, Symfony2 tells me that I provided the wrong credentials. Second try works. Any ideas why this could happen?
To reproduce the behaviour, I have to logout, clear cookies, go to the login page again and log in again.
I am using FOSUserBundle.
config.yml:
framework:
#esi: ~
secret: asdfsadfasdf
#translator: { fallback: en }
charset: UTF-8
router: { resource: "%kernel.root_dir%/config/routing.yml" }
form: true
csrf_protection: true
validation: { enable_annotations: true }
templating: { engines: ['twig'], assets_version: v1.2 } #assets_version: SomeVersionScheme
translator: { fallback: de }
session:
default_locale: de
auto_start: false
lifetime: 1000000
...
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:
fos_userbundle:
id: fos_user.user_manager
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/login$
security: false
public:
pattern: ^/.*
form_login:
provider: fos_userbundle
check_path: /login_check
remember_me: true
remember_me:
key: aaasfasdfasdfsadfsadf
lifetime: 1296000 #15 days in second
path: /
anonymous: true
logout: true
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY}
- { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY}
#- { path: ^/_internal, roles: IS_AUTHENTICATED_ANONYMOUSLY, ip: 127.0.0.1 }
- { path: ^/events/create, roles: ROLE_USER }
#...
acl:
connection: default
routing.yml:
_imagine:
resource: .
type: imagine
_index:
resource: "#AjadoEventHubBundle/Controller/IndexController.php"
type: annotation
fos_comment_api:
type: rest
resource: "#FOSCommentBundle/Resources/config/routing.yml"
prefix: /api
fos_user_security:
resource: "#FOSUserBundle/Resources/config/routing/security.xml"
...
#FOSUserBundle/Resources/config/routing/security.xml:
<routes xmlns="http://symfony.com/schema/routing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">
<route id="fos_user_security_login" pattern="/login">
<default key="_controller">FOSUserBundle:Security:login</default>
</route>
<route id="fos_user_security_check" pattern="/login_check">
<default key="_controller">FOSUserBundle:Security:check</default>
</route>
<route id="fos_user_security_logout" pattern="/logout">
<default key="_controller">FOSUserBundle:Security:logout</default>
</route>
</routes>
On my opinion, this is expected behaviour as you enabled anonymous authentication :
You request your app url, without being logged => a session cookie is created with your session ID
An anonymous token is created
You clear cookie => no more session id to identify you
Next request, no token is attached to your login request...
I'm not familiar with symfony, however, I have experienced the same problem when the authentication check looked for a valid cookie, but the cookie was being created after the check--thus causing it to pass the second time, never the first.
By default Symfony require that a session must be exist before the submitting of the form
from the docs
# by default, a session must exist before submitting an authentication request
# if false, then Request::hasPreviousSession is not called during authentication
# new in Symfony 2.3
In order to over come this you could set "require_previous_session" (which is by default true) to false in the "security.yml" as under "form_login" like this:
require_previous_session: false
You could read more about it in Symfony docs in the following link
SecurityBundle Configuration ("security")
I had this problem and I solved it following the answer here Symfony 2 “Your session has timed out or you have disabled cookies”.
#AlterPHP was right, you have to login twice because the first time you are getting an error like this:
Authentication request failed. (...) Your session has timed out, or you have disabled cookies.
As you don't have a session started, with this request a new session is created. Next time you try to login, as the session was created, you can login.
You had to set the option require_previous_session: false in your app/config/security.yml file to avoid looking for a previous session:
security:
firewalls:
main:
form_login:
require_previous_session: false