black-bits / laravel-cognito-auth

MIT License
89 stars 51 forks source link

Best approach to retrieving Access Token from AWS Request #31

Closed bluehaoran closed 3 years ago

bluehaoran commented 4 years ago

When CognitoClient::authenticate() is called, it returns an Aws\Result object. This contains useful information, specifically Access Tokens (which for instance can be used to identify the user to an AWS Cognito Identity Pool).

    "AuthenticationResult" => array:5 [▼
      "AccessToken" => "eyJraWQiOiIybGV5NGlRUEdcLzRkRjZ3MUNSNVdFS0hnbkJDZ2NxYjJQazZXa0oxc2RmMD0iLCJhbGciOiJSUzI1NiJ9...."
      "ExpiresIn" => 3600
      "TokenType" => "Bearer"
      "RefreshToken" => "eyJjdHkiOiJKV1QiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.aLM8vBERuFjeX5I3yz_1-ghRxPFSyG..."
      "IdToken" => "eyJraWQiOiJmQkdXcldaY2Q4MWpNKzNqTFhsSVwvdlJiK2ZTUHI4azBJZzBwRnBFK0M5bz0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI2ZjV..."
    ]

I'm sure I'm not the only person who could use this (I notice #16 ).

Can you suggest the best way to extend CognitoGuard and CognitoClient to provide this data to a Laravel Controller without breaking the StatefulGuard::attempt() interface?

I'm happy to do the leg-work and send you a pull-request, just need suggestions for the best way to do this without breaking it for all package users.

ryzr commented 4 years ago

Hmmm, so I guess this is the only block with the Result object available:

https://github.com/black-bits/laravel-cognito-auth/blob/master/src/Auth/CognitoGuard.php#L42-L63

Possibly a contract and trait could be created - which provides a method to temporarily store the result on the user object. In pseudo-code, something like:

protected function hasValidCredentials($user, $credentials)
{
    ...

    if ($user instanceof CognitoAuthenticable) {
        $user->setCognitoResult($result)
    }
}

And then in your LoginController, usage would look like:

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        $result = $user->getCognitoResult();
        $accessToken = $result ? $result['AccessToken'] : null;
    }

Alternatively, the result could be saved inside the guard? The only iffy thing about this, is IDEs wouldn't really understand auth()->cognitoResult() and Auth::cognitoResult()

What do you think?

note: I'm not a maintainer here - but I'm certainly interested in this package and its future development

bluehaoran commented 4 years ago

Thanks @ryzr ! At first glance, that's definitely much better than my first, second, or third thought. I'll think on it for a little longer, and then I will probably go down your route.