shopware / frontends

Shopware Frontends is a framework for building custom, headless storefronts with Shopware 6.
https://frontends.shopware.com
MIT License
176 stars 49 forks source link

[FEATURE] api-next: allow passing directly the oauth credentials instead of session data #553

Closed shyim closed 9 months ago

shyim commented 9 months ago

Description

Right now when you create an admin client, you have to pass the "sessionData" which is the oauth API response. It's annoying to craft this by own. There should be an optional field where I can put the password or client credentials grant data, and it fetches his token

Use Case

Make easier to use the SDK

Proposed Solution

No response

Alternatives Considered

const auth = (await (
  await fetch(`${process.env.BASE_URL}/api/oauth/token`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      client_id: "administration",
      grant_type: "password",
      username: "admin",
      password: "shopware",
    }),
  })
).json()) as {
  access_token?: string;
  refresh_token: string;
  expires_in: number;
};

Additional Context

No response

patzick commented 9 months ago

hey @shyim, sessionData is not required if you don't have it on creation you simply don't pass it. In example we do use cookies for storing session data, but you can use other storage or just keep it memory (default behaviour, then you don't even need to pass onAuthChange behaviour).

Then you need to log in, depending on the grant type there are different approaches, but the simplest one with password:

await client.invoke("token post /oauth/token", {
      grant_type: "password",
      client_id: "administration",
      scopes: "write",
      username: "USERNAME",
      password: "PASSWORD",
    });

and from now on (unless your credentials are correct) you can access all other endpoints. Let me know if you need any further clarification

shyim commented 9 months ago

That's kinda exactly what I did and I think it's bad for the Client to do that manually. My expectation would be, I can pass the credentials optionally to the object in the createAdminClient. and then when the sessionData is empty, you authorize it for me.

something like this:

export const adminApiClient = createAdminAPIClient<operations, operationPaths>({
  baseURL: `${process.env.SHOP_URL}/api`,
  credentials: {
      grant_type: "password",
      client_id: "administration",
      scopes: "write",
      username: "USERNAME",
      password: "PASSWORD",
    }
});

and then I can invoke directly without further thinking about the Client

shyim commented 9 months ago

maybe a real world example helps :) https://github.com/shopwareLabs/k6-shopware/blob/main/fetch-fixtures.ts

patzick commented 9 months ago

thanks @shyim, that's a good use-case for scripting and not managing the session during runtime. I created PR back to you with improvements in that area. Looking forward for more feedback! 🙌