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

(OAuth2) Call token endpoint twice - auto logout on refresh page #626

Closed
truongnmt opened this issue Jan 28, 2021 · 4 comments
Closed

(OAuth2) Call token endpoint twice - auto logout on refresh page #626

truongnmt opened this issue Jan 28, 2021 · 4 comments

Comments

@truongnmt
Copy link

Hello, first thanks for a awesome work!!!

I'm using laravel 6.2, jwt-auth 1, vuejs2, vue-auth 2.21.16-beta

Trying to implement Sign in with Github, but I got some weird issues, trying to fix for 2 weeks already!!! 💦 @websanova
Here is my setup:

oauth2GithubDriver.js custom OAuth2 driver

export default {
  url: 'https://github.com/login/oauth/authorize',
  params: {
    client_id: 'cc91e96004f2ebc00cae',
    redirect_uri: function() { return this.options.getUrl() + '/sso/callback' },
    response_type: 'code',
    scope: 'user_email read:user',
  },
}

app.ts

Vue.use(VueAuth, {
  auth: require('@websanova/vue-auth/drivers/auth/bearer.js'),
  http: require('@websanova/vue-auth/drivers/http/axios.1.x.js'),
  router: require('@websanova/vue-auth/drivers/router/vue-router.2.x.js'),
  githubOauth2Data: oauth2Github,
  githubData: {
    method: 'POST',
    redirect: '/',
    url: 'auth/sso',
  },
  rolesVar: 'type_id',
  parseUserData: user => user,
});

AuthLogin - WORK

  private sso(): void {
    this.$auth.oauth2({
      provider: 'github',
      state: {
        staySignedIn: true,
        rememberMe: true,
      },
      rememberMe: true,
    });
  }

Redirect to github just fine, and return authorization code

AuthCallback

    mounted() {
      console.log("mounted");
      if (this.$route.query.state) {
        if (typeof this.$route.query.state === 'string')
        this.state = JSON.parse(this.$route.query.state);
      }
      if (this.$route.query.code) {
        if (typeof this.$route.query.code === 'string')
          this.code = this.$route.query.code;
      }
      this.$auth.oauth2({
        code: true,
        provider: 'github',
        params: {
          code: this.code,
        },
        success: function(res) {
          console.log('success')
        },
        error: function(res) {
          console.log('error')
        },
      });
    }

(I put console.log here and see that the "mounted" appears twice 🤔 which cause a bug later)
Redirect to callback, vue then pass the authorization code to laravel API

AuthController.php

public function sso(Request $request)
    {
        $invoker = new CognitoAuthRequest();

        $tokenResponse = $invoker->invokeTokenRequest([
            'loginResult' => $request->all(),
            'appUrl'      => config('app.url')
        ]);

        $tokens = \json_decode(
            $tokenResponse->getBody(), true
        );

        $tokenParts = explode(".", $tokens['id_token']);
        $tokenPayload = base64_decode($tokenParts[1]);
        $jwtPayload = json_decode($tokenPayload, true);

        $user = User::where('email', '=', $jwtPayload['email'])->first();
        if($user) {
            $token = $this->guard()->login($user);
            return $this->respondWithToken($token);
        } else {
            $user = new User();
            $user->type_id = 2;
            $user->name = $jwtPayload['username'];
            $user->email = $jwtPayload['email'];
            $user->password = Hash::make(Str::random(12));
            $user->save();

            $token = $this->guard()->login($user);
            if ($request->rememberMe) {
                $this->guard()->factory()->setTTL(env('JWT_TTL', 7*24*3600));
            }
            return $this->respondWithToken($token);
        }
    }

Then laravel grab the authorization code and send POST request to github token endpoint to exchange code for token, this works no problem. Then laravel use jwt-token to generate access token and send response to vue.

From here I got really confused:

  • 🤔 I see request from vue to laravel API to fetch user info /api/user and this return 200 OK. I can't find the source code where vue-auth triggered this request
  • 😵 The POST request to token endpoint is sent twice, the first time the request is 200 OK, the tokens is return but the second is failed with 400 Bad Request. Obviously with the same code can only be exchanged once. Github response is correct behaviour but I don't know why vue send request to API twice (as I put console.log in mounted() and it shown twice)
    • image
  • 😵 Auto logout on refresh page
    • if I login using email/password, refresh page no problem
    • login using SSO, after refresh page, token in local storage is deleted
      • also I see that if I login by SSO, I don't have the field 'rememberMe' in session 🤔
      • image
      • image

The SSO login works, I get user information, have access token but I got 2 errors above.

@websanova
Copy link
Owner

Ah not sure but seems you have a mixture of old and new code maybe. Perhaps make sure you are using latest version of the plugin first otherwise the docs might be a bit off.

@truongnmt
Copy link
Author

Thanks for your response. I will try newer version 😉. Btw which version do you prefer with my current stack? Version 3 or 4?

I'm using laravel 6.2, jwt-auth 1, vuejs2, vue-auth 2.21.16-beta

@websanova
Copy link
Owner

latest version, just check the install guide ;-)

@truongnmt
Copy link
Author

Latest version working flawlessly! Thanks for your support! <3

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