使用 symfony
LoginFormAuthenticator
,如何在 TODO 部分获取 azure 用户组。
请注意,获取 azure 用户所属的 AD 组需要 SSO 身份验证,但我不想通过该过程,只获取用户的组。有什么想法吗?
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
{
use TargetPathTrait;
public const LOGIN_ROUTE = 'login';
private UrlGeneratorInterface $urlGenerator;
public function __construct(UrlGeneratorInterface $urlGenerator)
{
$this->urlGenerator = $urlGenerator;
}
/**
* @inheritDoc
* @param Request $request
* @return bool
*/
public function supports(Request $request): bool
{
return $request->isMethod('POST') && $request->attributes->get('_route') === self::LOGIN_ROUTE;
}
/**
* @inheritDoc
* @param Request $request
* @return Passport
*/
public function authenticate(Request $request): Passport
{
$aufUsername = $request->request->get('_username', '');
$request->getSession()->set(Security::LAST_USERNAME, $aufUsername);
return new Passport(
new UserBadge($aufUsername, function() use ($aufUsername) {
// TODO
// fetch a AD user with email $aufUsername and then get AD groups he belongs to
}),
new PasswordCredentials($request->request->get('_password', '')),
[
new CsrfTokenBadge('authenticate', $request->request->get('_csrf_token')),
]
);
}
/**
* @inheritDoc
* @param Request $request
* @param TokenInterface $token
* @param string $firewallName
* @return Response|null
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
return new RedirectResponse($targetPath);
}
return new RedirectResponse($this->urlGenerator->generate('homepage'));
}
/**
* @inheritDoc
* @param Request $request
* @return string
*/
protected function getLoginUrl(Request $request): string
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
}