Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

403 http code when redirecting in onAuthenticationSuccess with azure oauth2 #401

Open
mohamedTaiebBsf opened this issue Apr 11, 2023 · 2 comments

Comments

@mohamedTaiebBsf
Copy link

mohamedTaiebBsf commented Apr 11, 2023

In symfony 6.2, I implement the azure Oauth2 authentication, but got 403 when redirecting to homepage in onAuthenticationSuccess method;

In controller:

`
/**
* @param ClientRegistry $clientRegistry
* @return mixed
*
* @route("/auth/azure", name="connect_azure")
*/
public function loginWithAzure(ClientRegistry $clientRegistry)
{
return $clientRegistry
->getClient('azure')
->redirect(
[
'openid',
'profile',
'email',
'offline_access',
'User.Read',
'Group.Read.All',
'GroupMember.Read.All'
]
);
}

/**
 * @param Request $request
 * @param ClientRegistry $clientRegistry
 *
 * @Route("/connect/azure/check", name="connect_azure_check")
 */
public function connectAzureCheck(Request $request, ClientRegistry $clientRegistry)
{
}

`

In Security.yaml:
`
security:
enable_authenticator_manager: true

password_hashers:
App\Entity\Utilisateurs\AllUserFinal:
algorithm: auto

providers:
app_user_provider:
entity:
class: App\Entity\Utilisateurs\AllUserFinal
property: aufUsername
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: app_user_provider
custom_authenticators:
- App\Security\AzureOauthAuthenticator
logout:
path: logout
access_control:`

In knpu_oauth2_client.yaml:
knpu_oauth2_client: clients: azure: type: azure client_id: '%env(AZURE_CLIENT_ID)%' client_secret: '%env(AZURE_CLIENT_SECRET)%' redirect_route: connect_azure_check redirect_params: { } default_end_point_version: 2.0 use_state: false

Authenticator class:
`use App\Entity\Entite;
use App\Entity\Utilisateurs\AllUserFinal;
use Doctrine\ORM\EntityManagerInterface;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use KnpU\OAuth2ClientBundle\Security\Authenticator\OAuth2Authenticator;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;

class AzureOauthAuthenticator extends OAuth2Authenticator implements AuthenticationEntryPointInterface
{
private ClientRegistry $clientRegistry;
private EntityManagerInterface $entityManager;
private RouterInterface $router;
private TokenStorageInterface $tokenStorage;

public function __construct(
    ClientRegistry $clientRegistry,
    EntityManagerInterface $entityManager,
    RouterInterface $router,
    TokenStorageInterface $tokenStorage
)
{
    $this->clientRegistry = $clientRegistry;
    $this->entityManager = $entityManager;
    $this->router = $router;
    $this->tokenStorage = $tokenStorage;
}

public function supports(Request $request): ?bool
{
    return $request->attributes->get('_route') === 'connect_azure_check';
}

public function authenticate(Request $request): Passport
{
    $client = $this->clientRegistry->getClient('azure');
    $accessToken = $this->fetchAccessToken($client);

    return new SelfValidatingPassport(
        new UserBadge($accessToken->getToken(), function () use ($accessToken, $client) {
            $azureUser = $client->fetchUserFromToken($accessToken)->toArray();
            $email = $azureUser["preferred_username"];

            $existingUser = $this->entityManager
                ->getRepository(AllUserFinal::class)
                ->findOneBy(['aufMail' => $email]);

            if ($existingUser) {
                return $existingUser;
            }

            $user = new AllUserFinal();
            $user->setAufNom($azureUser["name"])
                ->setAufPrenom($azureUser["name"])
                ->setAufMail($email);

            $this->entityManager->persist($user);
            $this->entityManager->flush();

            return $user;
        })
    );
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
    $targetUrl = $this->router->generate('espacePersonnel');

    return new RedirectResponse($targetUrl);
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
    $message = strtr($exception->getMessageKey(), $exception->getMessageData());

    return new Response($message, Response::HTTP_FORBIDDEN);
}

/**
 * Called when authentication is needed, but it's not sent.
 * This redirects to the 'login'.
 */
public function start(Request $request, AuthenticationException $authException = null): Response
{
    return new RedirectResponse(
        $this->router->generate("connect_azure"),
        Response::HTTP_TEMPORARY_REDIRECT
    );
}

}`

@weaverryan
Copy link
Member

After the redirect (so, on the 403 page), if you look at the web debug toolbar, are you authenticated as any user? Or not logged in still? If you are logged in, when you click the security icon in the web debug toolbar, what roles does your user have? Also on that 403 page, if you click the security icon in the web debug toolbar, you should be able to see the "Access decision log" where you can see why you were denied access. Is there anything interesting there?

@mohamedTaiebBsf
Copy link
Author

@weaverryan
If we look at the web debug toolbar in redirect page, the user is till not logged in.
In fact, in onAuthenticationSuccess, if we debug the token, we do have the authenticated user, but when I redirected to the home page, it gives 403, the user is lost somewhere. But when I refresh the page, I'am logged in. This issue is happened when I'am already not loggedIn in my azure account
I need to tell you that I desactivate state in knpu_oauth2_client.yml file (use_state: false) to not face "invalid parameter Invalid state passed in parameters callback url" issue. maybe it is a sort of my problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants