keystatic icon indicating copy to clipboard operation
keystatic copied to clipboard

allow explicitly providing redirect_uri for github sign in

Open stefanprobst opened this issue 1 year ago • 5 comments

when trying to deploy keystatic on our infrastructure, i am running into an issue with the redirect_uri setting for github sign in.

the callback uri in the github app is configured to use the /api/keystatic/github/oauth/callback route on the domain the app is deployed to, however the redirect_uri actually used by keystatic is using a hostname internal to our cluster infra. (in our case, the correct hostname would be only on x-forwarded-host header)

which means i cannot sign in, but instead see this error:

An error occurred when trying to authenticate with GitHub:
The redirect_uri MUST match the registered callback URL for this application.

the redirect_uri query param is constructed here by keystatic:

https://github.com/Thinkmill/keystatic/blob/bcc3c69638c3affd758215289f572ac22afadfa5/packages/keystatic/src/api/generic.ts#L375-L378

allowing to set the redirect url explicitly via environment variable would work around this issue i think.

stefanprobst avatar Mar 15 '24 11:03 stefanprobst

Could you share what framework you're using? I believe Next.js respects x-forwarded-host in the URL passed to route handlers but I think Astro might not, we could probably handle that ourselves

emmatown avatar Mar 20 '24 01:03 emmatown

i am using Next.js (14.2.0-canary.30), and am currently using a work-around modelled after this comment, which seems to do the trick:

import { makeRouteHandler } from "@keystatic/next/route-handler";

import config from "@/keystatic.config";

const { GET: _GET, POST: _POST } = makeRouteHandler({ config });

function rewriteUrl(request: Request) {
    const forwardedHost = request.headers.get("x-forwarded-host");
    const forwardedProto = request.headers.get("x-forwarded-proto");

    if (forwardedHost && forwardedProto) {
        const url = new URL(request.url);

        url.hostname = forwardedHost;
        url.protocol = forwardedProto;
        url.port = "";

        return new Request(url, request);
    }

    return request;
}

export function GET(request: Request) {
    return _GET(rewriteUrl(request));
}

export function POST(request: Request) {
    return _POST(rewriteUrl(request));
}

EDIT: same thing is needed for the preview/draft mode endpoint

stefanprobst avatar Mar 20 '24 08:03 stefanprobst

I am also running into this error using Remix + Vite deployed to fly.io.

No issues authenticating locally with github but then i receive An error occurred when trying to authenticate with GitHub: The redirect_uri MUST match the registered callback URL for this application. when i try to sign in against my hosted app.

grunklejp avatar Mar 20 '24 12:03 grunklejp