Posts

Showing posts with the label Svelte

Google OAuth2 in Svelte + FastAPI: Create a Session Cookie from JWT

Image
Table of Contents Introduction What I Implement Frontend implementation with Svelte Backend implementation with FastAPI Conclusion Introduction I have implemented Google Sign-In functionality in a sample website built using Svelte and FastAPI. There are various methods to authenticate users in the backend API server after a successful Google Sign In. One common approach is to send the JWT received from Google in the request header as Authorization: "Bearer: JWT", and if the JWT is valid, authorization to access resources is granted. Another typical method involves issuing a JWT on the backend and using it for user authentication in the Authorization header. However, using JWT directly for session management poses a challenge in immediate invalidation if the JWT is leaked. Reference: Stop using JWT for sessions . Therefore, I implemented a method in which, following the receipt of the JWT from Google, FastAPI assigns a new session_id. This session_id is set in a co...

Svelte+FastAPIでSign in with Googleを試してみた

Image
目次 はじめに 実装するもの Svelteでのフロントエンドの実装 FastAPIでのバックエンド実装 まとめ はじめに SvelteとFastAPIを使用して構築したサンプルウェブサイトにGoogleのサインイン機能を実装しました。 Google Sign Inに成功した後、バックエンドのAPIサーバーにログインするためには、様々な方法が考えられます。 Googleから受け取ったJWTを、Requestヘッダに Authorization: "Bearer: JWT" として送信し、正しいJWTであれば、認証されます。 また、バックエンドでJWTを発行し、 Authorization ヘッダにセットして認証済みユーザーを識別する方法も一般的です。 しかし、JWTをそのままログインユーザーの識別に利用する場合、JWTの漏洩時に即時の無効化が難しい問題があります。 参考: Stop using JWT for sessions 。 そこで、GoogleからJWTを受け取った後、FastAPI側で新たにsession_idを発行し、Cookieを介してセッションを維持する方法で実装しました。 セッション情報はFastAPIのセッションデータベースで管理されており、管理者がいつでもセッションを無効にできます。 また、CookieにSecure属性とHttpOnly属性を付与することで、経路での盗聴防止やJavaScriptからのアクセス防止が可能になり、より安全なWebサイトの構築が可能です。 なお、SvelteもFastAPIも独学で学習中ですので、おかしな点があれば、アドバイスいただけると嬉しいです。 実装するもの 認証が実装されると、未ログイン時のアクセスはログインページにリダイレクトされ、そこでGoogleアカウントでログインできます。 Customerページは、認証に成功した場合にのみ表示できます。 FastAPIではSwagger UIによるドキュメントページが自動生成されます。 Svelteでのフロントエンドの実装 Svelteを使用してフロントエンドを実装します。 バックエンドからcustomerデータを取得し、テーブル表示するページにGoogle OAuth2を利用した認証機能を実装...