Tustin / psn-php

A PHP wrapper for the PSN API
https://tustin.dev/psn-php/
MIT License
356 stars 73 forks source link

Client does not have grant type: 'authorization_code' #232

Closed vicegold closed 1 year ago

vicegold commented 1 year ago

Client does not have grant type: 'authorization_code'

This error comes up when trying to login with an npsso. Is that something new?

Btw. that error from the API also triggers an uncaught ApiException:

Fatal error: Uncaught Tustin\Haste\Exception\ApiException in /project/vendor/tustin/haste/src/Http/Middleware/ResponseHandlerMiddleware.php:59 Stack trace: #0 /project/vendor/tustin/haste/src/Http/Middleware/ResponseHandlerMiddleware.php(32): Tustin\Haste\Http\Middleware\ResponseHandlerMiddleware->handleErrorResponse(Object(GuzzleHttp\Psr7\Response), Object(Tustin\Haste\Http\JsonStream)) #1 /project/vendor/guzzlehttp/promises/src/FulfilledPromise.php(41): Tustin\Haste\Http\Middleware\ResponseHandlerMiddleware->__invoke(Object(GuzzleHttp\Psr7\Response)) #2 /project/vendor/guzzlehttp/promises/src/TaskQueue.php(48): GuzzleHttp\Promise\FulfilledPromise::GuzzleHttp\Promise\{closure}() #3 /project/vendor/guzzlehttp/promises/src/Promise.php(248): GuzzleHttp\Promise\TaskQueue->run(true) #4 /project/vendor/guzzlehttp/promises/src/Promise.php(224): GuzzleHttp\Promise in /project/vendor/tustin/haste/src/Http/Middleware/ResponseHandlerMiddleware.php on line 59
jeroenbourgois commented 1 year ago

Experiencing the same issue. I'll try to dig a bit further, must be a recent change since everything was working fine until this morning.

recordsome commented 1 year ago

They changed the client_id This one doesn't work anymore: ac8d161a-d966-4728-b0ea-ffec22f69edc

jeroenbourgois commented 1 year ago

@recordsome that seems correct, but which ID should work? I'll try to reverse engineer the apk if I can. I tried another ID I at https://andshrew.github.io/PlayStation-Trophies/#/APIv2?id=powershell-7. The original ID has no Location header whatsoever, the latter does but then I get the authorization_code error.

So it must be another ID still...

So these dont' work anymore:

wescopeland commented 1 year ago

Best solution is probably to pull it straight from the mobile app

jeroenbourgois commented 1 year ago

@wescopeland I'll try but I have never done that ^^ do you have any experience?

wescopeland commented 1 year ago

I do but unfortunately I won't be able to attack it for another 10 hours or so :-( What I've done previously is set up a man-in-the-middle VPN between my phone and computer using Charles and then sniff all the incoming+outgoing traffic.

recordsome commented 1 year ago

If you do a search by uuid in the android application code, it will not find it in plain text. So it's obfuscated

They also added protection against traffic sniffing some time ago. So now it's not possible on ios to see what's going on in the webview during authorization

wescopeland commented 1 year ago

On the mobile app I am seeing the following URL being called:

https://ca.account.sony.com/api/authz/v3/oauth/authorize

with the following query params:

response_type: "code"
service_logo: "ps"
access_type: "offline"
scope: "psn:mobile.v2.core"
client_id: "70156ca4-e84e-4836-ade8-b254b76a9d9f"
token_format: "jwt"

There are a few more query params but they are probably specific to my account. I pulled this using Charles for iOS and sniffing the traffic.

Note that when I feed these query params into psn-api's function for exchanging an NPSSO for an access code, I get a new error saying "Invalid token".

recordsome commented 1 year ago

@wescopeland Parameter 'client_id' is malformed. it's missing 2 characters yet. Maybe you copied it wrong?

wescopeland commented 1 year ago

@wescopeland Parameter 'client_id' is malformed. it's missing 2 characters yet. Maybe you copied it wrong?

Yes, updated. It appears I am able to get a code but I am not able to exchange the code for access and refresh tokens.

recordsome commented 1 year ago

@wescopeland Is there a redirect_uri there in the link?

wescopeland commented 1 year ago

It's the same as before, "com.playstation.PlayStationApp://redirect"

recordsome commented 1 year ago

@wescopeland https://ca.account.sony.com/api/authz/v3/oauth/authorize?response_type=code&service_logo=ps&access_type=offline&token_format=jwt&scope=psn%3Amobile.v2.core&client_id=70156ca4-e84e-4836-ade8-b254b76a9d9f&redirect_uri=com.playstation.PlayStationApp%3A%2F%2Fredirect

The link doesn't work

jeroenbourgois commented 1 year ago

@wescopeland I see similar behaviour. I can spot the following as a response:

  body: "{\"error\":\"invalid_scope\",\"error_code\":4153,\"error_description\":\"Invalid scope\"}",

Looking into it further.

wescopeland commented 1 year ago

@wescopeland ca.account.sony.com/api/authz/v3/oauth/authorize?response_type=code&service_logo=ps&access_type=offline&token_format=jwt&scope=psn%3Amobile.v2.core&client_id=70156ca4-e84e-4836-ade8-b254b76a9d9f&redirect_uri=com.playstation.PlayStationApp%3A%2F%2Fredirect

The link doesn't work

  const AUTH_BASE_URL = "https://ca.account.sony.com/api/authz/v3/oauth";

  const queryString = new URLSearchParams({
    access_type: "offline",
    client_id: "70156ca4-e84e-4836-ade8-b254b76a9d9f",
    redirect_uri: "com.playstation.PlayStationApp://redirect",
    response_type: "code",
    scope: "psn:mobile.v2.core"
  }).toString();

  const requestUrl = `${AUTH_BASE_URL}/authorize?${queryString}`;

  const response = await fetch(requestUrl, {
    headers: {
      Cookie: `npsso=${npssoToken}`
    },
    redirect: "manual"
  });

This is the code I am executing to get a successful 302 response with an access code.

recordsome commented 1 year ago

@wescopeland Link is working now. I just was logged in and didn't understand

recordsome commented 1 year ago

@wescopeland Also need change parameters In the request to receive tokens by code POST https://ca.account.sony.com/api/authz/v3/oauth/token

There is a Header Basic YWM4ZDE2MWEtZDk2Ni00NzI4LWIwZWEtZmZlYzIyZjY5ZWRjOkRFaXhFcVhYQ2RYZHdqMHY=

Need to update also. Can you check what's going What happens next webview. We need to check the token receipt request

wescopeland commented 1 year ago

The /token call unfortunately is completely failing for me. In the mobile app I am seeing them hit a different /token endpoint. I don't know if it has always been this way or if this is a recent change.

In the iOS mobile app, after /authorize, I see:

POST https://ca.account.sony.com/api/v1/oauth/token
Dherevo commented 1 year ago

Hi, I'm working on a Laravel and after setting de Npsso it returns an exception error, I think a bad request 400. It is possible that is the same thing and they changed something on the API?

Thanks.

wescopeland commented 1 year ago

Yes, you are likely facing the same issue we are trying to hunt down.

Dherevo commented 1 year ago

Yes, you are likely facing the same issue we are trying to hunt down.

Ok, thank you.

jeroenbourgois commented 1 year ago

After using the token url you posted above, I for now get the following response:

# Note: the 'JSON: %{' is just Elixir, I decoded the return body from the POST
JSON: %{
  "docs" => "https://auth.api.sonyentertainmentnetwork.com/docs/",
  "error" => "invalid_grant",
  "error_code" => 1,
  "error_description" => "Bad request"
}

I'm guessing it is not the correct token url after all... If only we could read the docs they supply :laughing:

wescopeland commented 1 year ago

Yeah I am feeling a bit stuck here, as it seems "psn:mobile.v1" and "psn:clientapp" are no longer valid scopes for the auth code endpoint.

jeroenbourgois commented 1 year ago

@wescopeland I agree. I tried a couple of combinations of those two and the new one you found, but the only one even passing the initial auth call is psn:mobile.v2.core.

recordsome commented 1 year ago

@jeroenbourgois What request are you making to get invalid_grant?

Tustin commented 1 year ago

On the mobile app I am seeing the following URL being called:

https://ca.account.sony.com/api/authz/v3/oauth/authorize

with the following query params:

response_type: "code"
service_logo: "ps"
access_type: "offline"
scope: "psn:mobile.v2.core"
client_id: "70156ca4-e84e-4836-ade8-b254b76a9d9f"
token_format: "jwt"

There are a few more query params but they are probably specific to my account. I pulled this using Charles for iOS and sniffing the traffic.

Note that when I feed these query params into psn-api's function for exchanging an NPSSO for an access code, I get a new error saying "Invalid token".

Is it possible for you to find the client_secret in the request? Or if not, possibly the Authorization header that should be getting sent to authz/v3/oauth/token? I'm assuming since Sony changed the entire scope that they probably just deleted the old OAuth client. I don't have my environment set up atm to sniff the new requests unfortunately.

jeroenbourgois commented 1 year ago

I hope this is not too convoluted:

%HTTPoison.Response{
  status_code: 400,
  body: "{\"error\":\"invalid_grant\",\"error_description\":\"Bad request\",\"docs\":\"https://auth.api.sonyentertainmentnetwork.com/docs/\",\"error_code\":1}",
  headers: [
    {"Server", "nginx"},
    {"Content-Type", "application/json;charset=UTF-8"},
    {"X-Psn-Request-Id", "9ab2aee91f117d5c0dd2092a4dfd25b3"},
    {"X-Psn-Correlation-Id", "eb617da6-63f0-4ed6-9636-cabb62f6eb78"},
    {"X-RequestId", "9ab2aee91f117d5c0dd2092a4dfd25b3"},
    {"X-CorrelationId", "eb617da6-63f0-4ed6-9636-cabb62f6eb78"},
    {"X-Content-Type-Options", "nosniff"},
    {"Cache-Control", "no-store"},
    {"Content-Length", "135"},
    {"Date", "Tue, 13 Dec 2022 17:42:02 GMT"},
    {"Connection", "close"},
    {"Set-Cookie",
     SOME_COOKIE; Domain=.sony.com; Path=/; Expires=Tue, 20 Dec 2022 17:42:02 GMT; Max-Age=604800; Secure"},
    {"Set-Cookie",
     SOME_COOKIE; Domain=.sony.com; Path=/; Expires=Tue, 13 Dec 2022 21:42:02 GMT; Max-Age=14400"}
  ],
  request_url: "https://ca.account.sony.com/api/v1/oauth/token",
  request: %HTTPoison.Request{
    method: :post,
    url: "https://ca.account.sony.com/api/v1/oauth/token",
    headers: [
      {"Authorization",
       "Basic MDk1MTUxNTktNzIzNy00MzcwLTliNDAtMzgwNmU2N2MwODkxOnVjUGprYTV0bnRCMktxc1A="},
      {"Content-Type", "application/x-www-form-urlencoded"}
    ],
    body: "code=v3.dmdr&grant_type=authorization_code&redirect_uri=com.playstation.PlayStationApp%3A%2F%2Fredirect&scope=psn%3Amobile.v2.core&token_format=jwt",
    params: %{},
    options: []
  }
}

Note I also updated the Basic AUTH hash I found somewhere else. So as @Tustin was hinting at, it could be part of the solution to have the correct Basic auth hash.

Ragowit commented 1 year ago

https://github.com/andshrew/PlayStation-Trophies/commit/64ae205beff6dbfdfa7bbc684351c5b838bc69aa

Tustin commented 1 year ago

Thanks @Ragowit and @andshrew for the solution! Seems to be fine now -- I've pushed it to master and will draft a release for PHP <8.1 version, along with a new version that works for PHP 8.1 🥳

Reuns commented 1 year ago

I've upgraded from the master... I still have the issue :/ Am I the only one ? @Ragowit @Tustin ?

Tustin commented 1 year ago

I've upgraded from the master... I still have the issue :/ Am I the only one ? @Ragowit @Tustin ?

Are you getting the same error as before? If so, please double check the Client.php file that you have in your vendor/psn-php folder and ensure the new client_id is set.

Reuns commented 1 year ago

Are you getting the same error as before? If so, please double check the Client.php file that you have in your vendor/psn-php folder and ensure the new client_id is set.

I've checked it twice.

And this is the error

Fatal error: Uncaught Tustin\Haste\Exception\ApiException in /core/vendor/tustin/haste/src/Http/Middleware/ResponseHandlerMiddleware.php:58 Stack trace: /core/vendor/tustin/haste/src/Http/Middleware/ResponseHandlerMiddleware.php(32): Tustin\Haste\Http\Middleware\ResponseHandlerMiddleware->handleErrorResponse() /core/vendor/guzzlehttp/promises/src/FulfilledPromise.php(41): Tustin\Haste\Http\Middleware\ResponseHandlerMiddleware->__invoke() /core/vendor/guzzlehttp/promises/src/TaskQueue.php(48): GuzzleHttp\Promise\FulfilledPromise::GuzzleHttp\Promise{closure}() /core/vendor/guzzlehttp/promises/src/Promise.php(248): GuzzleHttp\Promise\TaskQueue->run() /core/vendor/guzzlehttp/promises/src/Promise.php(224): GuzzleHttp\Promise\Promise->invokeWaitFn() /core/vendor/guzzlehttp/promises/src/Promise.php(269): GuzzleHttp\Promise\Promise->waitIfPending() /core/vendor/guzzlehttp/promises/src/Promise.php(226): GuzzleHttp\Promise\Promise->invokeWaitList() /core/vendor/guzzlehttp/promises/src/Promise.php(62): GuzzleHttp\Promise\Promise->waitIfPending() /core/vendor/guzzlehttp/guzzle/src/Client.php(187): GuzzleHttp\Promise\Promise->wait() /core/vendor/guzzlehttp/guzzle/src/ClientTrait.php(95): GuzzleHttp\Client->request() /core/vendor/tustin/haste/src/Http/HttpClient.php(52): GuzzleHttp\Client->post() /core/vendor/tustin/psn-php/src/Client.php(139): Tustin\Haste\Http\HttpClient->post() /core/psnApi/psnapi.class.php(46): Tustin\PlayStation\Client->loginWithRefreshToken() {main} thrown in /core/vendor/tustin/haste/src/Http/Middleware/ResponseHandlerMiddleware.php on line 58

vicegold commented 1 year ago

I also still have issues with the update:

{"error":"invalid_scope","error_description":"Invalid scope","error_code":4153,"error_uri":"https://auth.api.sonyentertainmentnetwork.com/openapi/docs","error_details":{"parameter":"[psn:clientapp, psn:mobile.v1]"}}

{"error":{"referenceId":"51ee451e-5f5c-474e-ae19-96cef245473e","code":3415813,"message":"Friend finder requires a valid account","reason":"invalid_parameter","source":"api"}}

Ragowit commented 1 year ago

@vicegold You haven't updated. The error code states "{"parameter":"[psn:clientapp, psn:mobile.v1]"}}", the new version have clientapp updated to "psn:mobile.v2.core" (among other things)

vicegold commented 1 year ago

@vicegold You haven't updated. The error code states "{"parameter":"[psn:clientapp, psn:mobile.v1]"}}", the new version have clientapp updated to "psn:mobile.v2.core" (among other things)

I did, the issue is, that only loginWithNpsso was updated. loginWithRefreshToken still uses the old parameters.

Tustin commented 1 year ago

@vicegold You haven't updated. The error code states "{"parameter":"[psn:clientapp, psn:mobile.v1]"}}", the new version have clientapp updated to "psn:mobile.v2.core" (among other things)

I did, the issue is, that only loginWithNpsso was updated. loginWithRefreshToken still uses the old parameters.

You're right, my mistake. Will push a fix right now!

vicegold commented 1 year ago

@Tustin Awesome, thank you! Can you also release a 3.0.4 when you get the chance please? :)

Tustin commented 1 year ago

@Tustin Awesome, thank you! Can you also release a 3.0.4 when you get the chance please? :)

Should be good to go now :) Let me know if there's any other issues!

Reuns commented 1 year ago

Perfect. Many thanks once again !