简体   繁体   中英

Symfony Oauth2 with gard

I am trying to configure guard with an OAuth 2 connection. I am trying to do this with a redirection in the getCredentials function to the Microsoft login website but I can't make it work. I don't know how I can make it worked. It seems there is no redirection possible in this function.

public function getCredentials(Request $request)
{
    $provider = new Microsoft([
            'clientId'          => '0000000032624',
            'clientSecret'      => 'my-secret',
            'redirectUri'       => 'https://mysite/oauthlogin'
    ]);

    if(!$request->query->has('code')){
        // If we don't have an authorization code then get one
        $authUrl = $provider->getAuthorizationUrl();
        $request->getSession()->set('oauth2state', $provider->getState());
        //This doesn't work
        return new RedirectResponse($authUrl);

    // Check given state against previously stored one to mitigate CSRF attack
    }elseif ( empty($request->query->get('state')) || ($request->query->get('state')!==$request->getSession()->get('oauth2state')) ){
        return null;
    }else{
        // Try to get an access token (using the authorization code grant)
        $token = $provider->getAccessToken('authorization_code', [
            'code' => $request->query->get('code')
        ]);
        try {
            //when log with microsoft, check if user is allowed
            // We got an access token, let's now get the user's details
            $user = $provider->getResourceOwner($token);
             } catch (Exception $e) {
            // Failed to get user details
        }
    }

}

public function getUser($credentials, UserProviderInterface $userProvider)
{       
    return $userProvider->loadUserByUsername($user->getEmail());
}

public function checkCredentials($credentials, UserInterface $user)
{
    // check credentials - e.g. make sure the password is valid
    // no credential check is needed in this case

    // return true to cause authentication success 
    return true;
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    $url = $this->router->generate('homepage');
    return new RedirectResponse($url);
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    $data = array(
            'message' => strtr($exception->getMessageKey(), $exception->getMessageData())           
            // or to translate this message
            // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
    );
    $request->getSession()->set(Security::AUTHENTICATION_ERROR, $data);
    $url = $this->router->generate('login');
    return new RedirectResponse($url);
}

Function getCredentials() is not supposed to return a Response , it provide the credentials used in getUser() .

In the getUser() documentation :

The credentials are the return value from getCredentials()

You may throw an AuthenticationException if you wish. If you return null, then a UsernameNotFoundException is thrown for you.

In case of exception thrown, onAuthenticationFailure() is called and here you can return your RedirectResponse .

For more detailled informations, see the source code of the \\Symfony\\Component\\Security\\Guard\\GuardAuthenticatorInterface which contains a lots of explanations in its methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM