JMS\Serializer\Exception\RuntimeException: Resources are not supported in serialized data. Path: Monolog\Handler\StreamHandler -> etc - fosuserbundle

I'm working with Symfony 4 and i have installed JMS serializer with FOSRest bundle.
So every time i've got an error i've got this message :
JMS\Serializer\Exception\RuntimeException: Resources are not supported in serialized data. Path: Monolog\Handler\StreamHandler -> Symfony\Bridge\Monolog\Logger -> Symfony\Component\Cache\Adapter\PhpFilesAdapter -> Symfony\Component\Cache\Adapter\TraceableAdapter -> Symfony\Component\Cache\Adapter\PhpArrayAdapter -> Symfony\Component\Cache\DoctrineProvider -> Doctrine\Common\Annotations\CachedReader -> Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener -> Symfony\Component\EventDispatcher\EventDispatcher -> Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher -> ContainerYCXy4ht\srcTestDebugProjectContainer -> FOS\RestBundle\Request\ParamFetcher -> Symfony\Component\HttpFoundation\ParameterBag -> Symfony\Component\HttpFoundation\Request -> Symfony\Component\HttpKernel\Exception\HttpException
And after the real error and i dont understand why ? I use JMS contrib recipe :
/packages/dev/jms_serializer.yaml
jms_serializer:
visitors:
json:
options:
- JSON_PRETTY_PRINT
- JSON_UNESCAPED_SLASHES
- JSON_PRESERVE_ZERO_FRACTION
/packages/prod/jms_serializer.yaml
jms_serializer:
visitors:
json:
options:
- JSON_UNESCAPED_SLASHES
- JSON_PRESERVE_ZERO_FRACTION
/packages/jms_serializer
jms_serializer:
visitors:
xml:
format_output: '%kernel.debug%'
So i don't understand why this behavior ?
If someone could help me ?
Thanks by advance

I found the solution it was an fos_rest configuration error
Before
fos_rest:
exception:
enabled: true
exception_controller: 'fos_rest.exception.controller:showAction'
param_fetcher_listener: force
body_listener: true
format_listener:
enabled: true
rules:
- { path: '^/api', priorities: ['json'], prefer_extension: true}
- { path: '^/', priorities: [ 'html', '*/*'], fallback_format: html, prefer_extension: true }
view:
view_response_listener: 'force'
After
fos_rest:
param_fetcher_listener: force
format_listener:
enabled: true
rules:
- { path: '^/api', priorities: ['json'], prefer_extension: true}
- { path: '^/', priorities: [ 'html', '*/*'], fallback_format: html, prefer_extension: true }
view:
view_response_listener: 'force'

Related

How to set global property for react using esbuild

According to the docs using define is the suggested way of setting the env properties for a build.
When I run my app with I get a process is not defined error.
My esconfig is as follows:
await build({
entryPoints: ['./src/index.tsx'],
outdir: './build',
bundle: true,
incremental: true,
metafile: true,
target: 'es6',
loader: { '.png': 'file' },
minify: !dev,
sourcemap: 'inline',
define: { 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development') },
plugins: [
sassPlugin(),
svg(),
copy({
resolveFrom: 'cwd',
assets: {
from: ['./public/*'],
to: ['./build2/*'],
},
}),
copy({
resolveFrom: 'cwd',
assets: {
from: ['./public/images/*'],
to: ['./build2/images/*'],
},
}),
],
watch: dev
? {
onRebuild: (error) => {
if (error) {
console.error(error);
} else {
console.log('rebuild done');
}
},
}
: false,
});
I'm also open to other ways of setting global properties to control the configuration.
I've resorted to writing a config/env file before the build starts.
My react app then just needs to know where the env file is located.
const config: IEnv = {
ENV: process.env.NODE_ENV ? process.env.NODE_ENV : 'development',
USE_EMU: process.env.USE_EMU === '1' ? true : false,
USE_DEV: process.env.USE_DEV === '1' ? true : false,
VERSION: process.env.VERSION ? process.env.VERSION : 'dev',
};
fs.writeFileSync('src/env.json', JSON.stringify(config), { encoding: 'utf8' });
You are getting process is not defined error because you actually do not define process in define option, you do define process.env.NODE_ENV.
It may be counterintuitively but it is how define option is used. It doesn't actually defines variable and just replaces all tokens that look like define key with corresponding value.

Netlify build passed but shows only html css

I need help on netlify deployments. Actually it deploys and shows "Published" but I tried Gatsby build and nothing related to fail or any netlify failed deployment but once it is published in Live then it only shows html & css.
Navbar menu and dropdowns doesn't works. But in localhost, it shows everythings.
I don't understand why after Netlify deployment the website doesn't looks like my local.
Dev console shows these warnings:
-React-Hot-Loader: react-🔥-dom patch is not detected. React 16.6+ features may not work.
-You may be attempting to nest <Helmet> components within each other, which is not allowed. Refer to our API for more information.
-Warning: componentWillMount has been renamed, and is not recommended for use. See https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html for details.
What I tried:
-Check old commits.
-Check public folder in local apache server.
-Clear gatsby cache, netlify cache and redeploy.
Nothing worked if you got any idea I would like to test please
Here is the gatsby log:
gatsby build
success open and validate gatsby-configs - 0.111s
success load plugins - 1.952s
success onPreInit - 0.034s
success delete html and css files from previous builds - 0.049s
success initialize cache - 0.009s
success copy gatsby files - 0.113s
success onPreBootstrap - 0.015s
success createSchemaCustomization - 0.008s
-> wordpress__wp_v2 fetched : 1
-> wordpress__wp_example.wordpress.com fetched : 1
Path: /wp/v2/sites/example.wordpress.com/jetpack-global-styles?per_page=100&page=1
The server response was "403 Forbidden"
Inner exception message: "Sorry, you are not allowed to do that."
-> wordpress__POST fetched : 59
-> wordpress__PAGE fetched : 2
-> wordpress__wp_media fetched : 90
-> wordpress__wp_blocks fetched : 1
-> wordpress__wp_feedback fetched : 0
-> wordpress__wp_jp_pay_order fetched : 0
-> wordpress__wp_jp_pay_product fetched : 0
-> wordpress__wp_block_areas fetched : 0
-> wordpress__wp_types fetched : 1
-> wordpress__wp_statuses fetched : 1
-> wordpress__wp_taxonomies fetched : 1
-> wordpress__CATEGORY fetched : 13
-> wordpress__TAG fetched : 7
-> wordpress__wp_users fetched : 2
-> wordpress__wp_me fetched : 1
-> wordpress__wp_comments fetched : 0
-> wordpress__wp_search fetched : 61
-> wordpress__wp_settings fetched : 1
Path: /wp/v2/sites/example.wordpress.com/themes?per_page=100&page=1
The server response was "400 Bad Request"
Inner exception message: "Missing parameter(s): status"
success source and transform nodes - 15.832s
warn Multiple node fields resolve to the same GraphQL field `wordpress__wp_media.guid` - [`guid`, `guid___NODE`].
warn Multiple node fields resolve to the same GraphQL field `wordpress__POST.jetpack_featured_media_url` -
success building schema - 1.044s
success createPages - 0.149s
warn Non-deterministic routing danger: Attempting to create page: "/contact/", but page "/contact" already exists
This could lead to non-deterministic routing behavior
success createPagesStatefully - 0.244s
success onPreExtractQueries - 0.003s
success update schema - 0.055s
success extract queries from components - 0.755s
success write out requires - 0.010s
success write out redirect data - 0.005s
success Build manifest and related icons - 0.168s
success onPostBootstrap - 0.194s
â €
info bootstrap finished - 29.155 s
â €
success Building production JavaScript and CSS bundles - 59.710s
success Rewriting compilation hashes - 0.005s
success run queries - 61.016s - 97/97 1.59/s
[ ] 0.001 s 0/98 0% Building static HTML for pages
i18next: languageChanged en
i18next: languageChanged en
i18next: initialized {
debug: true,
initImmediate: true,
ns: [ 'translation' ],
defaultNS: 'translation',
fallbackLng: [ 'en' ],
fallbackNS: false,
whitelist: false,
nonExplicitWhitelist: false,
load: 'languageOnly',
preload: false,
simplifyPluralSuffix: true,
keySeparator: '.',
nsSeparator: ':',
pluralSeparator: '_',
contextSeparator: '_',
partialBundledLanguages: false,
saveMissing: false,
updateMissing: false,
saveMissingTo: 'fallback',
saveMissingPlurals: true,
missingKeyHandler: false,
missingInterpolationHandler: false,
postProcess: false,
returnNull: true,
returnEmptyString: true,
returnObjects: false,
joinArrays: false,
returnedObjectHandler: [Functi18next: initialized {
debug: true,
initImmediate: true,
ns: [ 'translation' ],
defaultNS: 'translation',
fallbackLng: [ 'en' ],
fallbackNS: false,
whitelist: false,
nonExplicitWhitelist: false,
load: 'languageOnly',
preload: false,
simplifyPluralSuffix: true,
keySeparator: '.',
nsSeparator: ':',
pluralSeparator: '_',
contextSeparator: '_',
partialBundledLanguages: false,
saveMissing: false,
updateMissing: false,
saveMissingTo: 'fallback',
saveMissingPlurals: true,
missingKeyHandler: false,
missingInterpolationHandler: false,
postProcess: false,
returnNull: true,
returnEmptyString: true,
returnObjects: false,
joinArrays: false,
returnedObjectHandler: [Function: returnedObjectHandler],
parseMissingKeyHandler: false,
appendNamespaceToMissingKey: false,
appendNamespaceToCIMode: false,
overloadTranslationOptionHandler: [Function: handle],
interpolation: { escapeValue: false },
resources: { en: { translation: [Object] }, fr: { translation: [Object] } },
react: { wait: true, nsMode: 'default' }
}
ion: returnedObjectHandler],
parseMissingKeyHandler: false,
appendNamespaceToMissingKey: false,
appendNamespaceToCIMode: false,
overloadTranslationOptionHandler: [Function: handle],
interpolation: { escapeValue: false },
resources: { en: { translation: [Object] }, fr: { translation: [Object] } },
react: { wait: true, nsMode: 'default' }
[============== ] 11.817 s 50/98 51% Building static HTML for pages
success Building static HTML for pages - 12.124s - 98/98 8.08/s
success onPostBuild - 0.381s
info Done building in 103.31746359 sec
Edit:
This installation solved my issue :)
npm install #hot-loader/react-dom

Symfony 3.3 FOSRestBundle + FOSUserBundle + PUGXMultiuserBundle Registration with postman CSRF protection is invalid

i'm using symfony 3.3, i build my application with FOSUserbundle and PUGXMultiuserBundle and everything is ok. and now i'm trying to create my API REST with FOSRestBundle, i got a problem when i'm trying to register a new user with postman.
{
"code": 400,
"message": "Validation Failed",
"errors": {
"errors": [
"The CSRF token is invalid. Please try to resubmit the form."
],
"children": {
"email": {},
"username": {},
"plainPassword": {
"children": {
"first": {},
"second": {}
}
}
}
}
}
i used this example to build my API REST and it is good but didn't work with PUGXMultiuserBundle
enter link description here
and this is my class for registration a new user
<?php
namespace Taseera\EndpointBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\Controller\Annotations;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Routing\ClassResourceInterface;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* #RouteResource("registration", pluralize=false)
*/
class RegistrationUserOneController extends FOSRestController implements ClassResourceInterface
{
/**
* #Annotations\Post("/register-company")
*/
public function registerAction(Request $request)
{
//$request = $this->getRequest();
$formFactory = $this->get('fos_user.registration.form.factory');
$form = $formFactory->createForm(array('csrf_protection' => false));
$discriminator = $this->container->get('pugx_user.manager.user_discriminator');
$discriminator->setClass('Taseera\UserBundle\Entity\UserOne');
$userManager = $this->container->get('pugx_user_manager');
$user = $userManager->createUser();
$dispatcher = $this->get('event_dispatcher');
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form->setData($user);
$form->submit($request->request->all());
if ( ! $form->isValid()) {
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);
if (null !== $response = $event->getResponse()) {
return $response;
}
return $form;
}
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
if ($event->getResponse()) {
return $event->getResponse();
}
$userManager->updateUser($user);
$response = new JsonResponse(
[
'msg' => $this->get('translator')->trans('registration.flash.user_created', [], 'FOSUserBundle'),
'token' => $this->get('lexik_jwt_authentication.jwt_manager')->create($user), // creates JWT
],
Response::HTTP_CREATED,
[
'Location' => $this->generateUrl(
'get_profile',
[ 'user' => $user->getId() ],
UrlGeneratorInterface::ABSOLUTE_URL
)
]
);
$dispatcher->dispatch(
FOSUserEvents::REGISTRATION_COMPLETED,
new FilterUserResponseEvent($user, $request, $response)
);
return $response;
}
}
i'm using also "lexikjwt-authentication-bundle", "jms/serializer-bundle", "nelmio/api-doc-bundle" and "nelmio/cors-bundle"
this is my security.yml:
security:
encoders:
FOS\UserBundle\Model\UserInterface: bcrypt
role_hierarchy:
ROLE_ADMIN: [ROLE_USER, ROLE_COMPANY]
ROLE_SUPER_ADMIN: ROLE_ADMIN
providers:
fos_userbundle:
id: fos_user.user_provider.username_email
firewalls:
admin:
pattern: ^/admin(.*)
form_login:
provider: fos_userbundle
login_path: admin_login
check_path: admin_login_check
# check_path verification de l'autentification
default_target_path: /admin
logout:
path: /admin/logout
target: /admin/login
anonymous: true
company:
pattern: ^/company(.*)
form_login:
provider: fos_userbundle
login_path: company_login
check_path: company_login_check
# check_path verification de l'autentification
default_target_path: /company/profile
logout:
path: /company/logout
target: /company/login
anonymous: true
main:
pattern: ^/
form_login:
provider: fos_userbundle
login_path: fos_user_security_login
check_path: fos_user_security_check
csrf_token_generator: security.csrf.token_manager
default_target_path: taseerafrontend_homepage
always_use_default_target_path: true
logout: true
anonymous: true
api:
pattern: ^/endpoint
stateless: true
lexik_jwt: ~
healthcheck:
pattern: ^/endpoint/ping$
anonymous: true
api_docs:
pattern: ^/endpoint/doc
anonymous: true
api_register:
pattern: ^/endpoint/register-company
anonymous: true
security: false
api_password_reset:
pattern: ^/endpoint/password/reset
anonymous: true
api_login:
pattern: ^/endpoint/login
stateless: true
anonymous: true
form_login:
check_path: /endpoint/login
require_previous_session: false
username_parameter: username
password_parameter: password
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
logout: true
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/endpoint/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/logout$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/login_check$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/, role: ROLE_ADMIN }
- { path: ^/company/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/company/logout$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/company/login_check$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/company/, role: ROLE_COMPANY }
and this is my config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
# Put parameters here that don't need to change on each machine where the app is deployed#https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
locale: ar
category_directory: '%kernel.root_dir%/../web/backend/img/category'
user_one_company_directory: '%kernel.root_dir%/../web/backend/img/company'
medias_directory: '%kernel.root_dir%/../web/backend/img/medias'
framework:
#esi: ~
translator: ~
secret: '%secret%'
router:
resource: '%kernel.project_dir%/app/config/routing.yml'
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
#serializer: { enable_annotations: true }
templating:
engines: ['twig']
default_locale: '%locale%'
trusted_hosts: ~
session:
# https://symfony.com/doc/current/reference/configuration/framework.html#handler-id
handler_id: session.handler.native_file
save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'
fragments: ~
http_method_override: true
assets: ~
php_errors:
log: true
# Twig Configuration
twig:
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
form_themes:
- 'bootstrap_3_layout.html.twig'
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
host: '%database_host%'
port: '%database_port%'
dbname: '%database_name%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
# if using pdo_sqlite as your database driver:
# 1. add the path in parameters.yml
e.g. database_path: '%kernel.project_dir%/var/data/data.sqlite'
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
#path: '%database_path%'
orm:
auto_generate_proxy_classes: '%kernel.debug%'
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: '%mailer_transport%'
host: '%mailer_host%'
username: '%mailer_user%'
password: '%mailer_password%'
spool: { type: memory }
# app/config/config.yml
fos_user:
db_driver: orm # other valid values are 'mongodb' and 'couchdb'
firewall_name: main
user_class: Taseera\UserBundle\Entity\User
from_email:
address: "%mailer_user%"
sender_name: "%mailer_user%"
service:
user_manager: pugx_user_manager
registration:
confirmation:
enabled: true
change_password:
form:
type:
\UserBundle\Form\ChangePasswordFormType # or 'fos_user_change_password' on Symfony < 2.8
name: fos_user_company_change_password_form
validation_groups: [ChangePassword, Default]
#profile:
# form:
# type: Taseera\CompanyBundle\Form\ProfileFormType # or 'fos_user_profile' on Symfony < 2.8
# name: fos_user_company_profile
# validation_groups: [Profile, Default]
pugx_multi_user:
users:
user_one:
entity:
class: Taseera\UserBundle\Entity\UserOne
registration:
form:
type: Taseera\UserBundle\Form\Type\RegistrationUserOneFormType
name: fos_user_registration_form
validation_groups: [Registration, Default]
template: TaseeraUserBundle:Registration:user_one.form.html.twig
profile:
form:
type: Taseera\UserBundle\Form\ProfileUserOneFormType
name: fos_user_company_profile
validation_groups: [Profile, Default]
user_two:
entity:
class: Taseera\UserBundle\Entity\UserTwo
registration:
form:
type: Taseera\UserBundle\Form\Type\RegistrationUserTwoFormType
#name: fos_user_registration_form
validation_groups: [Registration, Default]
template: TaseeraUserBundle:Registration:user_two.form.html.twig
profile:
form:
type: Taseera\UserBundle\Form\ProfileUserTwoFormType
fos_rest:
body_listener: true
param_fetcher_listener: force
view:
view_response_listener: 'force'
formats:
json: true
xml: false
rss: false
mime_types:
json: ['application/json', 'application/x-json']
jpg: ['image/jpeg']
png: ['image/png']
routing_loader:
default_format: json
include_format: false
format_listener:
enabled: true
rules:
- { path: '^/endpoint', priorities: ['json', 'xml'], fallback_format: json, prefer_extension: true }
- { path: '^/', priorities: [ 'text/html', '*/*'], fallback_format: html, prefer_extension: true }
exception:
enabled: true
#JMS Serializer
jms_serializer: ~
# CSA Guzzle
csa_guzzle:
profiler: "%kernel.debug%"
# Lexik JWT Bundle
lexik_jwt_authentication:
private_key_path: "%jwt_private_key_path%"
public_key_path: "%jwt_public_key_path%"
pass_phrase: "%jwt_key_pass_phrase%"
token_ttl: "%jwt_token_ttl%"
# Nelmio CORS
nelmio_cors:
defaults:
allow_origin: ["%cors_allow_origin%"]
allow_methods: ["POST", "PUT", "GET", "DELETE", "OPTIONS"]
allow_headers: ["Content-Type", "Authorization"]
max_age: 3600
paths:
'^/': ~
# Nelmio API Doc
nelmio_api_doc: ~
i found the solution and it's worked for me
i must desactivate the csrf_protection in the RegistrationUserOneFormType related to my entity UserOne like this
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'csrf_protection' => false,
));
}

webpack-dev-server proxy not working

My app uses a Python backend so when I'm running locally I need to proxy my requests to a different port than what Webpack is running on.
I've tried several different ways of making this work:
devServer: {
contentBase: outDir,
proxy: [
{
path: "**",
target: "http://localhost:8000",
secure: false,
bypass: function(req, res, options) {
if(req.url === '' || req.url === '/') {
res.statusCode = 302;
res.setHeader('Location', '/a/');
return '/a/';
}
var frontend = new RegExp("^\/$^|\/a\/index\.html|^\/a\/|^\/a$|^\/styleguide");
if (frontend.test(req.url)) return req.url;
}
}
],
// serve index.html for all 404 (required for push-state)
historyApiFallback: true,
},
And this:
proxy: [{
context: '/',
target: 'http://localhost:8000',
}],
Both of those will at least show a message similar to this when it starts up: [HPM] Proxy created: ** -> http://localhost:8000. When I look at the docs and do something like this, it doesn't work either (I don't even get a message about the proxy running):
proxy: {
"/": "http://localhost:8000"
}
Is there something obvious I'm doing wrong? I'be been trying every combination that I can think of to make it work.
Try to add changeOrigin: true. Don't forget to change API pattern.
proxy: {
'/api/**': {
target: 'http://localhost:8000',
secure: false,
changeOrigin: true
},
}

LexikJWTBundle: no route found for POST /api/login_check

I am using LexikJWTBundle to authenticate an ionic angularjs app to a symfony2REST API.
My issue is that when I try to authenticate the user, Symfony returns : no route found for POST /api/login_check.
EDIT
I had put the route in my rest routing file so the resulting route was /api/api/login_check.
Now the error is: Unable to find the controller for path "/api/login_check".
It looks like LexikJWTBundle doesn't intercept the call.
End EDIT
I precise that my api is working fine w/o authentication and uses CORS though NelmioCorsBundle.
Here is my routing.yml portion:
api_login_check:
path: /api/login_check
Here is my config.yml
lexik_jwt_authentication:
private_key_path: %kernel.root_dir%/var/jwt/private.pem # ssh private key path
public_key_path: %kernel.root_dir%/var/jwt/public.pem # ssh public key path
pass_phrase: 'passphrase' # ssh key pass phrase
token_ttl: 86400 # token ttl - defaults to 86400
Here is my security.yml:
# app/config/security.yml
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
providers:
fos_userbundle:
id: fos_user.user_provider.username_email
firewalls:
dev:
pattern: ^/{_{profiler|wdt}}/
security: false
switch_user: true
main:
pattern: .*
form_login:
provider: fos_userbundle
csrf_provider: form.csrf_provider
logout: true
anonymous: true
switch_user: true
# JWT SETUP
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
require_previous_session: false
# JWT SETUP
api:
pattern: ^/api
stateless: true
lexik_jwt:
authorization_header:
enabled: true
prefix: Bearer
query_parameter:
enabled: true
name: bearer
access_control:
# JWT SETUP
- { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
Ok I found the issue: the firewall main should be located at the end because all routes maches this pattern and therefore prevent from going through other firewalls.
Stupid mistake again !
Thank you #keyboardSmaher for your help.
Now the security.yml looks like this:
# app/config/security.yml
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
providers:
fos_userbundle:
id: fos_user.user_provider.username_email
firewalls:
dev:
pattern: ^/{_{profiler|wdt}}/
security: false
switch_user: true
api_login:
pattern: ^/api/login
stateless: true
anonymous: true
provider: fos_userbundle
form_login:
check_path: api_login_check
require_previous_session: false
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: fos_userbundle
lexik_jwt: ~
main:
pattern: .*
form_login:
provider: fos_userbundle
csrf_provider: form.csrf_provider
logout: true
anonymous: true
switch_user: true
# JWT SETUP
# JWT SETUP
role_hierarchy:
ROLE_DELEGATION: [ROLE_USER]
ROLE_EXPORT: [ROLE_USER]
ROLE_USER_ADMIN: [ROLE_USER]
ROLE_LIST_ADMIN: [ROLE_USER]
ROLE_IMPORT: [ROLE_USER]
ROLE_MOBILE: [ROLE_USER]
ROLE_ADMIN: [ROLE_USER, ROLE_ALLOWED_TO_SWITCH]
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ALLOWED_TO_SWITCH]
access_control:
- { path: ^/$, role: ROLE_USER}
# - { path: ^/api, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/contacts, role: ROLE_USER }
- { path: ^/profile, roles: ROLE_USER }
- { path: ^/entites, role: ROLE_USER }
- { path: ^/export, role: ROLE_EXPORT }
- { path: ^/titres, roles: ROLE_ADMIN }
- { path: ^/categories, roles: ROLE_ADMIN }
- { path: ^/services, roles: ROLE_ADMIN }
- { path: ^/groupes, roles: ROLE_ADMIN }
- { path: ^/admin, roles: ROLE_ADMIN }
- { path: ^/imports, roles: ROLE_IMPORT }
- { path: ^/utilisateurs, roles: ROLE_USER_ADMIN }
- { path: ^/register, role: ROLE_SUPER_ADMIN }
- { path: ^/group, roles: ROLE_USER_ADMIN }
# JWT SETUP
- { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
For form log in to work, you need to create the check_path route. The route has to point to an empty controller and it is intercepted by the security system.
Just create an empty controller for /api/login_check and point your api_login_check route to it.
This information is in the documentation below.
Documentation

Resources