workos / authkit

The world's best login box powered by WorkOS and Radix.
https://authkit.com
MIT License
2.32k stars 90 forks source link

Access to fetch has been blocked by CORS policy #11

Closed srizvi closed 8 months ago

srizvi commented 11 months ago

Sometimes timing couldn't be more perfect, I'm so thrilled to be able to tap into the brainpower at WorkOS with AuthKit. I'm sure this problem is me. I've been following along the docs and the nextjs example, tried both the AuthKit version and Jason's, thank you for the awesome post btw!

Access to fetch at 'https://api.workos.com/user_management/authorize?client_id=client_01HGG60KYN9F25CHGM3TYV56WB&provider=authkit&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&response_type=code' (redirected from 'http://localhost:3000/account?_rsc=acgkz') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Any help or guidance would be appreciated as I'm in the process of working on this. Thanks!

benoitgrelard commented 11 months ago

Hey @srizvi, it looks like it could be related to that message. Do you have more info about what your environment is? (Software versions, Browser version, etc)

srizvi commented 11 months ago

Hey @srizvi, it looks like it could be related to that message. Do you have more info about what your environment is? (Software versions, Browser version, etc)

Thanks for getting back to me @benoitgrelard. I'm sorry I didn't share more details originally:

{"status":400,"error":"invalid_grant","errorDescription":"The code '01HGK04230T5JNZH6VP4Q8DQK9' has expired or is invalid.","rawData":{"error":"invalid_grant","error_description":"The code '01HGK04230T5JNZH6VP4Q8DQK9' has expired or is invalid."},"name":"OauthException","message":"Error: invalid_grant\nError Description: The code '01HGK04230T5JNZH6VP4Q8DQK9' has expired or is invalid."}

Thanks and appreciate you pointing out what I must be doing wrong at your convenience.

pmarsceill commented 11 months ago

@srizvi Thanks for the report. What version of Next are you running here?

srizvi commented 11 months ago

Hey @pmarsceill! The version from the two example repos. Authkit's and Jason's, from his website. Tried both, his is a fork of Authkit. Didn't change anything else. So "next": "14.0.1",

Hope this helps and thanks!

Edit: I added the latest updates from #12 too. :) Same result.

andy-hook commented 11 months ago

Hey @srizvi, thanks for the details.

Are you using any client side fetch calls in your code?

Just to triple check, if you freshly clone https://github.com/workos/next-authkit-example and provide your credentials, do you still encounter this issue?

srizvi commented 11 months ago

👋🏽 @andy-hook, followed the docs first, got the error. Tried the example repo from Authkit, same. Tried with Jason's version, following along from his post on his start branch, same. I don't believe there are any client calls in the example repos. The buttons, if I recall correct were calling their respective project endpoints which called authkit's. Thanks for your help, eager to get onboard.

andy-hook commented 11 months ago

Ah, that sounds frustrating. Would you be able to share your project code, or a reduced example that displays the same issue? I'll take a look and try my best to help from there.

srizvi commented 11 months ago

Hey @andy-hook thanks for the offer, much appreciated. I'm sure it's me, so grateful!

I think the easiest way to create a minimal reproduction would be to use either of these, which is what I did. I tried both with pnpm first, then npm too, just in case pnpm hoist issues.

I got the same issue on both. Thanks for the help!

andy-hook commented 11 months ago

Just noticed this additional error in your follow up:

{
  "status": 400,
  "error": "invalid_grant",
  "errorDescription": "The code '01HGK04230T5JNZH6VP4Q8DQK9' has expired or is invalid.",
  "rawData": {
    "error": "invalid_grant",
    "error_description": "The code '01HGK04230T5JNZH6VP4Q8DQK9' has expired or is invalid."
  },
  "name": "OauthException",
  "message": "Error: invalid_grant\nError Description: The code '01HGK04230T5JNZH6VP4Q8DQK9' has expired or is invalid."
}

This is returned by WorkOS and typically means the authorization code was already used.

Is there anything in your project that is referencing this code directly? or any reason this might be being used more than once?

The code is only valid for a single use, so navigating directly to: http://localhost:3000/callback?code=01HGK04230T5JNZH6VP4Q8DQK9

after the initial authentication request will return this error.

srizvi commented 11 months ago

Hey Andy,

Apologies for the confusion, if I refresh the browser window with the empty {}then the error you referenced is printed in the browser.

Edit: Fixed typo

andy-hook commented 11 months ago

Can you update your callback route handler like so:

https://github.com/workos/next-authkit-example/blob/adjust-error-handling/src/app/callback/route.ts#L46-L48

And let me know what error messaging you see when you try moving through the authentication flow?

Could you also check that you have set your JWT_SECRET_KEY correctly within your env variables file, this must have a value, even if it's simply a test string for now.

srizvi commented 11 months ago

Hey Andy, sorry for the late reply. Thanks for getting back to me. Sure, I'll give that a shot and let you know. I do have the JWT environment variable set.

PaulAsjes commented 8 months ago

Closing this for now as it's been inactive for a while. Please don't hesitate to reach out again if this is still an issue.

adss332 commented 8 months ago

Hello, i have the same problem on my symfony application. IDK in php guide - https://github.com/workos/workos-php, u dont use any JWT keys) so, i tried to use ur AuthKit form and my code looks like

#[Route('/callback', name: 'app_callback')]
public function callback(Request $request): Response
{
    $code = $request->query->get('code');
    $sso = new SSO();
    $profile = $sso->getProfileAndToken($code);
 }

it gave me redirect to http://localhost:8000/callback?code=01HQRFW4QX6MVZ0WM0AZ6X30Q4 and error {"error":"invalid_grant","error_description":"The code '01HQRFW4QX6MVZ0WM0AZ6X30Q4' has expired or is invalid."} BadRequestException

but in the way with my own code looks like

#[Route('/auth', name: 'app_auth')]
public function auth(): Response
{
    \WorkOS\WorkOS::setApiKey($_ENV['WORKOS_API_KEY']);
    \WorkOS\WorkOS::setClientId($_ENV['WORKOS_CLIENT_ID']);

    $authorizationUrl = (new \WorkOS\SSO())
        ->getAuthorizationUrl(
            null, //domain is deprecated, use organization instead
            'http://localhost:8000/callback', //redirectURI
            [], //state array, also empty
            null, //Provider which can remain null unless being used
            null, //Connection which is the WorkOS Organization ID,
            $_ENV['WORKOS_ORGANIZATION_ID'] //organization ID, to identify connection based on organization ID,
        );

    return $this->redirect($authorizationUrl);
}

it gave me error https://error.workos.com/sso/redirect-uri-invalid and sometimes Server Error (please reload the page) (but my url in settings http://127.0.0.1:8000/callback)

Could u help me with it ?

php version 8.2 symfony version 5.4 macOs 13.4 (22F66) chrome 122.0.6261.69

adss332 commented 8 months ago

Hi, could anybody answer me please? gmail nik.nyn96@gmail.com.

PaulAsjes commented 8 months ago

Hi @adss332, please don't re-open issues if your problem is different to the original issue.

In your case it's likely because you are using AuthKit with the SSO API rather than UserManagement. Try generating the redirect URL with:

WorkOS\WorkOS::setApiKey("sk_test_123");
WorkOS\WorkOS::setClientId("client_123");

$userManagement = new WorkOS\UserManagement();

$authorizationUrl = $userManagement->getAuthorizationUrl(
    redirectUri: "http://localhost:8000/callback",
    provider: 'authkit',
);

Then get the user profile later with:

$user = $userManagement->authenticateWithCode(    
    clientId: "client_123",
    code: $code,    
);
adss332 commented 8 months ago

@PaulAsjes Hello, thanks for answer, where i can continue discussion if i get another errors ?

PaulAsjes commented 8 months ago

Since this isn't an issue with AuthKit but rather your integration, I'd reach out to support via support@workos.com