DEV Community

Integrate Oauth2 for Symfony 4

Mert Simsek on August 22, 2018

We are going to easily integrate with KnpUOAuth2ClientBundle for Symfony 4. You can read the detail about it, https://github.com/knpuniversity/oaut...
Collapse
 
clementinioo profile image
B1905

Hi,

I have tried this for Symfony 4.2.2.
When i edit my security.yaml, i have this error : " Unrecognized option "knpu_oauth2_client" under "security". Available options are "access_control", "access_decision_manager", "access_denied_url", "always_authenticate_before_granting", "encoders", "erase_credentials", "firewalls", "hide_user_not_found", "providers", "role_hierarchy", "session_fixation_strategy". "

I don't know how can i solve it ?

Collapse
 
inchnus profile image
MedRyanReychico

Hi ,
Did you found a solution for this problem , cause i have the same and couldn't fix it ?

Collapse
 
_mertsimsek profile image
Mert Simsek • Edited

Hi fellas,

Thank you for reply, I tried to get same error and I did as I said in this article and I got same error. I found the solution.

You have to insert these lines. security and knpu_oauth2_client must be same level for yaml format. Don't push knpu_oauth2_client to under security section.

security:

    # https://symfony.com/doc/current/security.html#b-configuring-how-users-are-loaded
    providers:
        my_provider:
            entity: { class: App:User, property: username }

    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            anonymous: ~
            logout:
                path: /logout
                target: /login
            logout_on_user_change: true

            guard:
                authenticators:
                    - App\Security\GoogleAuthenticator

knpu_oauth2_client:
            clients:
                google:
                    type: google
                    client_id: '%env(resolve:GOOGLE_CLIENT_ID)%'
                    client_secret: '%env(resolve:GOOGLE_CLIENT_SECRET)%'
                    redirect_route: connect_google_check
                    redirect_params: {}
Collapse
 
julienlav profile image
julien-lav • Edited

Hi, thanks a lot for this tutorial, I followed all the steps but I still have this error :

{
"status": false,
"message": "User not found!"
}

I tried a var_dump(($this->getUser());
and I get NULL

So I don't know what is wrong, thanks for your help :)

Collapse
 
_mertsimsek profile image
Mert Simsek

Hi Julien,

Where do you write var_dump($this->getUser()); ?

You should try to write dumping the User into GoogleAuthenticator class and getUser() method? And in my opinion, keep on line-by-line with this way that class.

Collapse
 
julienlav profile image
julien-lav

Ok I'll try this, I was tryin in the Google Controller... probably not the best idea

Thread Thread
 
julienlav profile image
julien-lav • Edited

So I think I'm half way there, I had to change this, so I'm adding users in the bdd via google.

Once again, thanks a lot for you're toturial :)

Thread Thread
 
_mertsimsek profile image
Mert Simsek

Don't mention it :) I got happy for you

Collapse
 
dechans profile image
Hans DECAESTEKER

Hi,
Is it possible for you to explain how to mix a form login (simple page with forms) and the knpu oauth in a api that using lexik and jwt please ? I can log to my api with sending json to the login_check path that send me the jwt token and then use it to play with api route, but in a mixed login, how to implement it to connect with google and receive the jwt token (it is maybe a stupid question but i need to know it)
Thanks for this very great tut

Collapse
 
bali48 profile image
Muhammad Bilal • Edited

thepracticaldev.s3.amazonaws.com/i...
The App\Security\GoogleAuthenticator::getUser() method must return a UserInterface. You returned App\Entity\User.
I don't know how can i solve it ?

Collapse
 
_mertsimsek profile image
Mert Simsek

Apparently, you need to implement UserInterface to User Entity class. Open the User entity file and import this line,

class User implement UserInterface

Collapse
 
mbj97 profile image
MBJ-97

First thank you so much bro for this tutorial It helped me a lot and saved my project but there's one problem ... these infos doen't save to my database directly

Collapse
 
_mertsimsek profile image
Mert Simsek

Thanks for the answer. What's the matter with the database?

Collapse
 
mbj97 profile image
MBJ-97

The infos that we brought from google doesn't persist / flush

Thread Thread
 
_mertsimsek profile image
Mert Simsek • Edited

Is there anything error or what?

public function getUser($credentials, UserProviderInterface $userProvider)
    {
        /** @var GoogleUser $googleUser */
        $googleUser = $this->getGoogleClient()
            ->fetchUserFromToken($credentials);

        $email = $googleUser->getEmail();

        $user = $this->em->getRepository('App:User')
            ->findOneBy(['email' => $email]);
        if (!$user) {
            $user = new User();
            $user->setEmail($googleUser->getEmail());
            $user->setFullname($googleUser->getName());
            $user->setCreatedAt(new \DateTime(date('Y-m-d H:i:s')));
            $this->em->persist($user);
            $this->em->flush();
        }

        return $user;
    }

This code should insert your user data into your database.

Thread Thread
 
mbj97 profile image
MBJ-97

I had a little problem in my code and it worked thanks again , I want to ask you please how can I retrieve the Date of birth

Thread Thread
 
_mertsimsek profile image
Mert Simsek

As I read, there is a scope about it. Here you are, the documentation.

developers.google.com/people/v1/ho...

You need to add this scope as the documentation.

googleapis.com/auth/user.birthday....

Thread Thread
 
mbj97 profile image
MBJ-97

where shall I add it ?

Thread Thread
 
_mertsimsek profile image
Mert Simsek

In fact, I don't know but Could try this? I've changed user_fields line.
Also, check out developers.google.com/+/web/api/re...

knpu_oauth2_client:
    clients:
        google:
            # must be "google" - it activates that type!
            type: google
            # add and configure client_id and client_secret in parameters.yml
            client_id: '%env(resolve:GOOGLE_CLIENT_ID)%'
            client_secret: '%env(resolve:GOOGLE_CLIENT_SECRET)%'
            # a route name you'll create
            redirect_route: connect_google_check
            redirect_params: {}
            # Optional value for sending access_type parameter. More detail: https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters
            # access_type: ''
            # Optional value for sending hd parameter. More detail: https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
            # hosted_domain: ''
            # Optional value for additional fields to be requested from the user profile. If set, these values will be included with the defaults. More details: https://developers.google.com/+/web/api/rest/latest/people
            user_fields: {'birthday'}
            # whether to check OAuth2 "state": defaults to true
            # use_state: true
Thread Thread
 
mbj97 profile image
MBJ-97

It didnt worked :(

Collapse
 
sasa1007 profile image
Sasa Milivojevic • Edited

HI I thing that something Google changed in past couple days

github.com/thephpleague/oauth2-goo...

so I dont know how to override so I can make it work - until somene fix the bundle.

Collapse
 
_mertsimsek profile image
Mert Simsek

I check it out the issue, I assume you find a solution, right?

Collapse
 
sasa1007 profile image
Sasa Milivojevic

Oh yes sorry I didnt write

in googleController should be

public function connectAction(ClientRegistry $clientRegistry)
{
    return $clientRegistry
        ->getClient('google')
        ->redirect([], [
            'prompt' => 'consent',
        ]);
}
Thread Thread
 
_mertsimsek profile image
Mert Simsek

Perfect! Nowadays, I move to Symfony 5, thanks a lot!

Collapse
 
sasa1007 profile image
Sasa Milivojevic

Hi,

I implement new symfony security

symfony.com/doc/current/security.html

and now I have this error

Argument 1 passed to Symfony\Component\Security\Http\Authenticator\Debug\TraceableAuthenticator::__construct() must implement interface Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface, instance of App\Security\GoogleAuthAuthenticator given, called in /opt/app/vendor/symfony/security-http/Authenticator/Debug/TraceableAuthenticatorManagerListener.php on line 60

Collapse
 
marcomorandin profile image
MarcoMorandin

Hi,
I have tried this for Symfony 5. I cannot do the authentication because when I have done the login with google it returns {"status":false,"message":"User not found!"}.
I cannot understand what's wrong, can you help me?

Collapse
 
_mertsimsek profile image
Mert Simsek

Hi @marcomorain

Actually, I haven't moved to Symfony 5 version. However, it might be an easy way because most things got easier regarding security on that version as I know.

Collapse
 
byhaskell profile image
Alexander

Thank you, very quickly helped set up!

Collapse
 
_mertsimsek profile image
Mert Simsek

I'm glad to hear that :)

Collapse
 
zouhir923 profile image
harabazan zouhir

Image description

Hi,
I don't know exactly why I am facing this error

error
<< Attempted to load class "AbstractGuardAuthenticator" from namespace "Symfony\Component\Security\Guard".
Did you forget a "use" statement for another namespace? >>

Collapse
 
raphaelmouton profile image
Raphael Mouton

Really cool ! Thanks a lot ! Works perfectly for me !
I'm going to try the same with facebook :)

Collapse
 
_mertsimsek profile image
Mert Simsek • Edited

That's superb! I am pleased.
Yes, i integrated Facebook last week. It happened fine :)

Collapse
 
sasa1007 profile image
Sasa Milivojevic

Great tutorial everything works great

Collapse
 
_mertsimsek profile image
Mert Simsek

I'm glad to hear it from you :)

Collapse
 
babababou profile image
babababou

Hey great tuto ! thks !
Can you make a little one for facebook ??? Because I really can't do it....

Tks you :)

Collapse
 
_mertsimsek profile image
Mert Simsek

Hi,

Thank you for pretty reply :) In fact, there is a document related as you want. Here you are :)

github.com/knpuniversity/oauth2-cl...

Collapse
 
thomascms45 profile image
ThomasCms

@babababou did you success ? Cause I'm following knpuniversity documentation but I feel like I have to be in HTTPS...

Collapse
 
sasa1007 profile image
Sasa Milivojevic

Hi,

If I try to login but I dont have gmail account, I get epmty form for login on gmail account, but I want if there is no gmail account to redirect user on other url for log in.

Can you help?

Collapse
 
sfmok profile image
Mokhtar Tlili

I'm wondering about which purpose you create UserProvider. It looks you didn't use it in Authenticator

Collapse
 
disvroian profile image
disvroian

There is no OAuth2 client called "google". Available are:
This is what i have. Can someone help me ?

Collapse
 
_mertsimsek profile image
Mert Simsek

what is excatly the issue? Can you clarify it more?

Collapse
 
saninshakya profile image
San sh

How can I store the username at session after successful login?