Sveltekit - OAuth - 端点重定向无法正常工作

Sveltekit - OAuth - Endpoint redirect doesn't work properly

我正在尝试在 sveltekit 应用程序中实施 oauth 身份验证。我目前正在尝试使用 Github.

进行身份验证

项目架构如下:

.src
├── app.css
├── app.html
├── node_modules
│   └── ...
├── components
│   └── ...
├── global.d.ts
├── hooks.ts
├── lib
│   └── ...
└── routes
    ├── index.svelte
    ├── __error.svelte
    ├── __layout.svelte 
    └── oauth
       └── github
           ├── callback.ts
           ├── login.ts
           └── logout.ts

index.svelte 包含 UI 个调用 login.ts 端点的元素。 login.ts 然后重定向到 Github 授权页面。

这里是index.svelte:

<script context="module">
    export async function load({ session }) {
        return {
            props: {
                user: session.user
            }
        };
    }
</script>

<script lang="ts">
    export let user;
    console.log('Welcome', user);
</script>

<a href="/oauth/github/login">Connect with Github</a>

这是终点./src/routes/oauth/github/login.ts:

export async function get(): Promise<{ status: number, headers: { location: string } }> {

    const ghAuthURL = 'https://github.com/login/oauth/authorize';
    const clientId = import.meta.env.VITE_GITHUB_CLIENT_ID;
    const sessionId = '1234';

    return {
        status: 302,
        headers: {
            location: `${ghAuthURL}?client_id=${clientId}&state=${sessionId}`
        }
    };
}

当我单击“与 Github 连接”link 时,我进入了我的应用程序的错误页面并显示 404 错误。这是我在 404 上看到的错误:

Error: Not found: /oauth/github/login
    at Renderer._get_navigation_result (http://127.0.0.1:3000/.svelte-kit/dev/runtime/internal/start.js:807:11)
    at Renderer.update (http://127.0.0.1:3000/.svelte-kit/dev/runtime/internal/start.js:626:38)
    at Renderer.handle_navigation (http://127.0.0.1:3000/.svelte-kit/dev/runtime/internal/start.js:615:14)
    at Router._navigate (http://127.0.0.1:3000/.svelte-kit/dev/runtime/internal/start.js:292:23)
    at http://127.0.0.1:3000/.svelte-kit/dev/runtime/internal/start.js:175:9

如果我重新加载这个错误页面,我会登陆 github 的授权页面,然后我就可以连接了。

我在这里缺少什么?谢谢你的帮助。

解决方法是给锚点传递一个属性rel="external"

<a href="/oauth/github/login" rel="external">Connect with Github</a>

在文档中找到了解决方案:

By default, the SvelteKit runtime intercepts clicks on elements and bypasses the normal browser navigation for relative (same-origin) URLs that match one of your page routes. We sometimes need to tell SvelteKit that certain links need to be handled by normal browser navigation. Examples of this might be linking to another page on your domain that's not part of your SvelteKit app or linking to an endpoint.

https://kit.svelte.dev/docs/a-options#rel-external