Symfony add csrf token check for other pages - php

Official documentation (https://symfony.com/doc/current/security.html) of symfony states, to user CSRF protection I should add
# config/packages/security.yaml
security:
# ...
firewalls:
secured_area:
# ...
form_login:
# ...
enable_csrf: true
It works only for login form. This article (https://symfony.com/doc/current/security/csrf.html#csrf-protection-in-symfony-forms) says, that I can user method isCsrfTokenValid in the controller to check the token. I have another page, not, login page, where I want to check csrf token. Can you configure it somehow in the security.yaml or isCsrfTokenValid is the only way?

Related

How do I redirect to a dynamic custom route after register with FOSUserBundle

I've been looking for a while for this, but can't find the answer.
Expected behavior:
User goes on a product page
User wants to buy the product, so he needs to login / register (with a modal)
User doesn't have an account so he registers
After registration (there is no email confirmation), user is signed in and redirected to the current product page
User can proceed to checkout, etc...
This behavior is working in the case of a login, with the use of the _target_path parameter in the form.
However, this parameter does not apply in registration. This is kinda annoying, where did I miss something out ? I am looking into implementing a Listener on the registration success event but it seems really odd to not being as simple as for the login form.
Edit: found my solution, see my own answer below
Answering for those wondering too.
TL;DR : the registration process does not follow the login's
Thanks to #yceruto for the comment.
I made a quick listener on the REGISTRATION_SUCCESS event:
/**
* #param FormEvent $event
*/
public function redirectOnRegistration(FormEvent $event)
{
$route = $event->getRequest()->headers->get('referer', $this->router->generate('homepage'));
$response = new RedirectResponse($route);
$event->setResponse($response);
}
(I redirect on homepage if there is no referer).
In your security settings you must turn on referer:
firewalls:
dev:
pattern: ^/(_(profiler|wdt|console)|css|images|js)/
security: false
main:
pattern: ^/any_pattern
anonymous: ~
form_login:
login_path: any_pattern_login
check_path: any_pattern_login
use_referer: true
logout: true
access_denied_handler: app.security.access_denied_handler
guard:
authenticators:
- app.api_authenticator
provider: api_provider
logout:
path: any_pattern_logout
invalidate_session: true

Symfony 2 after login do some extra job

In this case, after a successful login, I need to update the user's login time into the underlying table.
The User entity currently implements UserInterface and is doing fine. Just want to add some extra code to log the login date time of the user.
Searched the site and seemed to me to use an EventListener etc is a bit heavy. Other lighter alternatives?
You can implement a Success Hander.
Write a class that implement the AuthenticationSuccessHandlerInterface:
Define it as a service (you can inject other services like doctrine
or the security context, in your case the Session)
Add the handler service in the security config like:
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
secured_area:
pattern: ^/
anonymous: ~
form_login:
login_path: login
check_path: login_check
success_handler: some.service.id
logout:
path: logout
target: /
Check this for a complete example and the reference doc for all the symfony2 security configuration options (you can configure the failure_handler also).
In my working solutions I implements the method onSecurityInteractiveLogin in my listener as:
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
$user = $event->getAuthenticationToken()->getUser();
$user->setLastLogin(new \Datetime());
// Entity manager injected by container in the service definition
$this->em->persist($user);
$this->em->flush();
}
Hope this help

Form-less authentication using standard Symfony2 security

I have the following scenario: I have a secured area of my domain under the pattern "/register", for which I have associated a fixed user called "registrant", with the unique role USER_REGISTRANT. The relevant security.yml sections are:
providers:
in_memory:
memory:
users:
registrant: { password: registrant, roles: 'REGISTERING_USER' }
firewalls:
register:
pattern: ^/register/.*
anonymous: false
form_login:
login_path: /register/initiate_registration
check_path: /register/start_registration
My goal is the following: whenever the user tries to enter the "/register" security context, she should be automatically authenticated as the user "registrant", without any form interaction or other user-side authentication steps.
I want to achieve this using the standard form-login mechanisms in Symfony2, i.e. when the user is sent to the login_path, the system should simply generate the necessary token/form data and pass it to check_path, just as would be done if the user had filled in a form and submitted it.
The general outline of the logic should go something like this:
/**
* #Route("/register/initiate_registration", name="initiate_registration")
*/
public function startAction() {
// TODO: Generate form data etc here
return $this->redirect($this->generateUrl('start_registration'));
}
What steps should be taken in the login_path controller in order to get the functionality desired above?
Is this docs can be usefull for you security?

Symfony2 - detect if user is inside a secure firewall

I'm trying to find out if a user is inside a secure firewall.
security.yml:
firewalls:
non_secure_area:
pattern: ^/
anonymous: true
secure_area:
pattern: ^/admin
form_login:
#etc.
logout:
#etc.
So I need to know if the user is inside the 'secure_area' secure part of the site.
I have used this, but of course it only tells me if somebody is 'logged in' AND on a HTTPS page. There must be a better way:
if( $request->isSecure() && $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') ) {
}
You can get security token and access provider key on it.
$token = $securityContext->getToken();
$providerKey = $token->getProviderKey(); // secured_area
Dont forget to check that token exist and its not an instance of AnonymousToken
If you are into something that is ContainerAware, you may get the Request, and then the URI [see docs]:
$request = $this->container->get('request');
$uri = $request->getUri();
Then you can check such string against /admin as you wish.

Symfony2 anonymous and authenticated on same route

I would have liked in Symfony2 "v2.1" a page that can be accessed without authentication and Authenticated.
I used the anonymous, but here is a token of the Authenticated User Anonymous and not be proper token.
Does anyone have a solution
As mentioned in the security:
Anonymous users are technically authenticated, meaning that the
isAuthenticated() method of an anonymous user object will return true.
//if you want myPage to be accessible by everyone
security:
firewalls:
secured_area:
pattern: ^/
anonymous: ~
access_control:
- { path: ^/myPage, roles: IS_AUTHENTICATED_ANONYMOUSLY }
If you remove the anonymous key, the firewall will always make a user fully authenticate immediately.

Categories