Symfony2 Firewall: User has right role but "Access denied" - symfony

I can't get my firewall rule working correctly. I have a user that has the role D-COMPLIANCEDIALOG, and a firewall rule, that grants access to that rule: - { path: ^/ , roles: D-COMPLIANCEDIALOG }. I still get an access denied (Access denied, the user is neither anonymous, nor remember-me.).
#security.yml
security:
encoders:
Symfony\Component\Security\Core\User\User: plaintext
providers:
reddot:
id: reddot_user_provider
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
secured_area:
pattern: ^/
anonymous: ~
http_basic: ~
simple_form:
authenticator: reddot_authenticator
check_path: login_check
login_path: login
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/ , roles: D-COMPLIANCEDIALOG }
User data from symfony profiler:
Username admin
Authenticated? yes
Roles [D-COMPLIANCEDIALOG]
Inherited Roles { }
Token class Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken
What I checked:
The controller has no own security settings
The role name does not seem to have a typo
It is really the last line in the firewall rule, if I remove it, I do have access.

The role name is incorrect. Please check the documentation Security - Roles
All roles you assign to a user must begin with the ROLE_ prefix. Otherwise, they won't be handled by Symfony's security system in the normal way (i.e. unless you're doing something advanced, assigning a role like FOO to a user and then checking for FOO as described below will not work).
I have faced the same issue when entered 'incorrect' role name and was confused by the error message too.

Although Symfony suggest prefixing the roles with ROLE_.. You can still use your custom roles via Securing by an Expression like:
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/ , allow_if: "has_role('D-COMPLIANCEDIALOG')"}

Related

How to restrict json_login route with only POST method?

I use lexik JWT to secure my api and i can login with it.
But the login route works with get and post request when i test with postman.
I want to restrict with POST only.
To do so i tried to add - { path: ^/auth/login_check, roles: PUBLIC_ACCESS, methods:['POST'] } in the access control but it does not do the trick.
I have no error but i still can do get request and have my token back.
security:
enable_authenticator_manager: true
# https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: email
# used to reload user from session & other features (e.g. switch_user)
# used to reload user from session & other features (e.g. switch_user)
# used to reload user from session & other features (e.g. switch_user)
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
api_login:
pattern: ^/auth/login
provider: app_user_provider
stateless: true
json_login:
username_path: email
check_path: /auth/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
api:
pattern: ^/api
stateless: true
jwt: ~
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#the-firewall
# https://symfony.com/doc/current/security/impersonating_user.html
# switch_user: true
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
- { path: ^/auth/login, roles: PUBLIC_ACCESS }
- { path: ^/auth/login_check, roles: PUBLIC_ACCESS, methods:['POST'] }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
So i found the answer myself. The methods option in access_control is a matching option and it does not restrict.
To restrict a route to a specific option, it has to be set in the route like this
#[Route('/my_route', name: 'my_route',methods: ['POST'])]

Symfony 4 + API Plantform +LexikJWTAuthenticationBundle Bad Credential

Good afternoon. Please i'm using LexikJWTAuthenticationBundle in a symfony 4 api project. I'm using UserProvider for Doctrine.
After Configure Doctrine User Provider, I've install and configure LexikJWTAuthenticationBundle. But when i tried to athentificate using Postman on the url http://localhost:8000/api/login_check whith this JSON {"username":"ak",
"password":"ak"} I've this error: {
"code": 401,
"message": "Bad credentials"
}.
See below my Security.yaml config file. I've read forums to tried to solve this issue but i've not yet found the solution. Can you please help me?
security:
encoders:
App\Entity\Utilisateur:
algorithm: bcrypt
providers:
#in_memory: { memory: ~ }
our_db_provider:
entity:
class: App\Entity\Utilisateur
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/api/login
stateless: true
anonymous: true
json_login:
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:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
main:
pattern: ^/
user_checker: App\Security\UtilisateurChecker
anonymous: true
provider: our_db_provider
access_control:
- { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
Have you missed a piece of configuration during installation? I dont see the lexik one:
lexik_jwt_authentication:
secret_key: '%kernel.project_dir%/config/jwt/private.pem' # required for token creation
public_key: '%kernel.project_dir%/config/jwt/public.pem' # required for token verification
pass_phrase: 'your_secret_passphrase' # required for token creation, usage of an environment variable is recommended
token_ttl: 3600
Good morning All. I've found the solution of my problem. In fact, i was typing a bad User Password.
To solve this article, i've used this article https://numa-bord.com/miniblog/symfony-4-les-base-dune-gestion-des-utilisateurs-inscription-connexion-droits-dacces/
I've created au database user by using create user command implemented in the article.
After i have been connected with this previous created user sucessfully. ApiPlatform generate a web tocken for me.
Thank you very much

Symfony4 Two authentification methods in security

I want two authentications methods in my application.
One for the entity User, and other (admin) with a plaintext.
Very simple.
Thus, when I configure security.yaml, I specify the providers:
security:
providers:
user:
entity:
class: App\Entity\User
property: username
in_memory:
memory:
users:
admin:
password: admin
roles: 'ROLE_ADMIN'
encoders:
App\Entity\User: bcrypt
Symfony\Component\Security\Core\User\User: plaintext
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
admin:
provider: in_memory
pattern: ^/admin/
guard:
provider: in_memory
form_login:
login_path: admin_login
check_path: admin_login
logout:
path: /admin/logout
target: /
default:
provider: user
anonymous: ~
guard:
provider: user
form_login:
login_path: login
check_path: login
default_target_path: login_redirect
use_referer: true
logout:
path: /logout
target: /
access_control:
- { path: ^/admin/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin, roles: ROLE_ADMIN }
- { path: ^/dashboard, roles: ROLE_USER }
And return the error:
In GuardAuthenticationFactory.php line 121:
Because you have multiple guard configurators, you need to set the "guard.e
ntry_point" key to one of your configurators ()
Then, if I have to set the guard.entry_point, I need do something like this:
admin:
entry_point: app.form_admin_authenticator
main:
entry_point: app.form_user_authenticator
And therefore, if I undestard, I need to configure a Authentication Listener like this: https://symfony.com/doc/current/components/security/authentication.html
(btw, this particular help page is very ambiguous and incomplete)
Is it necessary? It seems too complex for my purpose
I ran into this particular error. My situation might be a little different, but I had a similar need to authenticate using different authentication strategies depending on the entry point to the application.
One thing your config doesn't include is a reference to any Guard Authenticator objects. See this documentation for an intro to what role those objects play, and how to define them. Symfony's Security package is pretty complicated, and I found that using Guard Authenticators made the process a lot simpler for my use case.
Here is an example of a security.yaml config referencing two different authenticators. The entry_point configuration tells Symfony which one to try first, because in my particular case, Symfony otherwise wouldn't know which authentication strategy to apply first to an incoming request.
security:
providers:
user:
id: App\My\UserProviderClass
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: ~
logout:
path: app_logout
guard:
entry_point: App\My\MainAuthenticator
authenticators:
- App\My\MainAuthenticator
- App\My\OtherAuthenticator
Custom Guard Authenticators contain a method called supports. This method takes the incoming request as its only argument, and returns true or false based on whether the given authenticator should be applied to the incoming request. A common practice might be to check the request's Symfony route name (as defined by the controller) or perhaps something like the full URI for the request. For example:
/**
* Does the authenticator support the given Request?
*
* If this returns false, the authenticator will be skipped.
*
* #param Request $request
*
* #return bool
*/
public function supports(Request $request): bool
{
$matchesMyRoute = 'some_route_name' ===
$request->attributes->get('_route');
$matchesMyUri = '/path/to/secured/resource' ===
$request->getUri();
return $matchesMyRoute || $matchesMyUri;
}
You can imagine that if multiple Guard Authenticators exist in the same application, it's likely the case that one would only want them to apply to a request of a certain type, whether the differentiation is based on the kind of auth applied (eg. a header with an API key vs. a stateful session cookie), whether the difference is more about the specific route being hit, or perhaps a combination of factors.
In this case, telling Symfony which Guard Authenticator to try first may be important for your security strategy, or may have performance ramifications. For example, if you had two authenticators, and one had to hit the database to verify a stateful session, but another could verify the request's authentication statelessly, eg. by verifying a JWT's signature, you'd probably want to make the JWT authenticator run first, because it might not need to make a round trip to the database to authenticate the request.
See this article for a deeper explanation: https://symfonycasts.com/screencast/symfony-security/entry-point

Users are disconnected in 5/6 minutes

With Symfony 3.3.16, my users are disconnected in 5/6 minutes. I don't understand.
This problem is only in production (OVH), not in dev.
session.gc_maxlifetime : 1440
security.yml :
security:
encoders:
AppBundle\Entity\User: bcrypt
providers:
database_users:
entity:
class: AppBundle\Entity\User
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
pattern: ^/
anonymous: true
simple_form:
username_parameter: _email
authenticator: AppBundle\Security\Authenticator
check_path: login
login_path: login
success_handler: AppBundle\Handler\AuthenticationSuccessHandler
logout:
path: logout
handlers: [AppBundle\Handler\LogoutHandler]
success_handler: AppBundle\Handler\LogoutSuccessHandler
access_control:
- { path: '^/administration', roles: ROLE_ADMIN }
- { path: '^/user', roles: ROLE_USER }
Can you help me ?
In the symfony configuration reference, you can configure the session lifetime setting:
cookie_lifetime
This determines the lifetime of the session - in seconds. The default
value - null - means that the session.cookie_lifetime value from
php.ini will be used. Setting this value to 0 means the cookie is
valid for the length of the browser session.
gc_maxlifetime
This determines the number of seconds after which data will be seen as "garbage" and potentially cleaned up. Garbage collection may occur during session start and depends on gc_divisor and gc_probability.
Check their value in the config.yml and config_prod.yml
I understand you have already checked the the value of the php.ini value session.gc_maxlifetime

Symfony access_control not applied 'per-host' rule

Morning folks,
mainly i want to secure all call against a url that starts with /api/internal.
All endpoints that start with this path are only for internal calls, e.g. in a ajax-search box. So right me when i am wrong but i thought it would be a good idea to secure this via host definition in access_roles
I tried it with the following security.yml
security:
role_hierarchy:
ROLE_myproject_USER: ROLE_USER
ROLE_TEAMMANAGER: ROLE_USER
ROLE_ADMIN: [ROLE_TEAMMANAGER]
providers:
dashboard_users:
ldap:
service: myproject.ldap
# my ldap config
custom_user_provider:
id: myproject.factory.scale_user
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
api_internal:
pattern: ^/api/internal
security: true
host: myproject.dev
api_doc:
pattern: ^/api/doc
security: false
api_login:
pattern: ^/api/login
stateless: true
anonymous: true
api:
pattern: ^/api
stateless: true
provider: custom_user_provider
guard:
authenticators:
- myproject.api_login_authenticator
main:
anonymous: ~
form_login_ldap:
login_path: myproject_login
check_path: myproject_login
service: myproject.ldap
dn_string: 'Verbund\{username}'
logout:
path: myproject_logout
target: /
access_control:
- { path: ^/api/internal, host: myproject.dev }
But i get this error:
InvalidConfigurationException in SecurityExtension.php line 481:
No authentication listener registered for firewall "api_internal".
Side information: In this project there a 3 different sections:
/api/internal/**** - should only be accessible from the website itself
/api/ - should be accessible via REST, is secured via JWTToken
the Website itself - is secured via form login and LDAP
Thankful for any help you can provide.
Max
In order to have hosts secured, use access_control
access_control:
# require ROLE_ADMIN for /admin*
- { path: ^/admin, roles: ROLE_ADMIN }
where the path is your desired host.
In order to have everything for a subhost secured use
- { path: ^/admin/*, roles: ROLE_ADMIN }
remove other firewalls than main and dev!
Please refer to http://symfony.com/doc/2.8/security.html for more information

Resources