Access Token 저장 방식 변경

This commit is contained in:
static
2024-12-28 16:54:46 +09:00
parent 1d0c309878
commit c09a0b4aa0
10 changed files with 44 additions and 83 deletions

View File

@@ -1,48 +1,15 @@
import { get } from "svelte/store";
import { accessTokenStore } from "$lib/stores";
const refreshToken = async () => {
const res = await fetch("/api/auth/refreshToken", {
method: "POST",
credentials: "same-origin",
});
if (!res.ok) {
accessTokenStore.set(null);
throw new Error("Failed to refresh token");
}
const data = await res.json();
const token = data.accessToken as string;
accessTokenStore.set(token);
return token;
};
const callAPIInternal = async (
input: RequestInfo,
init: RequestInit | undefined,
token: string | null,
retryIfUnauthorized = true,
): Promise<Response> => {
if (!token) {
token = await refreshToken();
retryIfUnauthorized = false;
}
const res = await fetch(input, {
...init,
headers: {
...init?.headers,
Authorization: `Bearer ${token}`,
},
});
if (res.status === 401 && retryIfUnauthorized) {
return await callAPIInternal(input, init, null, false);
}
return res;
return await fetch("/api/auth/refreshToken", { method: "POST" });
};
export const callAPI = async (input: RequestInfo, init?: RequestInit) => {
return await callAPIInternal(input, init, get(accessTokenStore));
let res = await fetch(input, init);
if (res.status === 401) {
res = await refreshToken();
if (!res.ok) {
return res;
}
res = await fetch(input, init);
}
return res;
};

View File

@@ -1,4 +1,4 @@
import { error } from "@sveltejs/kit";
import { error, type Cookies } from "@sveltejs/kit";
import jwt from "jsonwebtoken";
import env from "$lib/server/loadenv";
@@ -35,13 +35,13 @@ export const verifyToken = (token: string) => {
}
};
export const authenticate = (request: Request) => {
const accessToken = request.headers.get("Authorization");
if (!accessToken?.startsWith("Bearer ")) {
error(401, "Access token required");
export const authenticate = (cookies: Cookies) => {
const accessToken = cookies.get("accessToken");
if (!accessToken) {
error(401, "Access token not found");
}
const tokenPayload = verifyToken(accessToken.slice(7));
const tokenPayload = verifyToken(accessToken);
if (tokenPayload === TokenError.EXPIRED) {
error(401, "Access token expired");
} else if (tokenPayload === TokenError.INVALID || tokenPayload.type !== "access") {

View File

@@ -71,7 +71,7 @@ export const logout = async (refreshToken: string) => {
await revokeRefreshToken(jti);
};
export const refreshToken = async (refreshToken: string) => {
export const refreshTokens = async (refreshToken: string) => {
const { jti: oldJti, userId, clientId } = await verifyRefreshToken(refreshToken);
const newJti = uuidv4();

View File

@@ -1,3 +0,0 @@
import { writable } from "svelte/store";
export const accessTokenStore = writable<string | null>(null);

View File

@@ -1,2 +1 @@
export * from "./auth";
export * from "./key";