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";

View File

@@ -1,5 +1,3 @@
import { accessTokenStore } from "$lib/stores";
export const requestLogin = async (email: string, password: string) => {
const res = await fetch("/api/auth/login", {
method: "POST",
@@ -8,13 +6,5 @@ export const requestLogin = async (email: string, password: string) => {
},
body: JSON.stringify({ email, password }),
});
if (!res.ok) {
return false;
}
const data = await res.json();
const token = data.accessToken as string;
accessTokenStore.set(token);
return true;
return res.ok;
};

View File

@@ -1,4 +1,4 @@
import { error, json } from "@sveltejs/kit";
import { error, text } from "@sveltejs/kit";
import ms from "ms";
import { z } from "zod";
import env from "$lib/server/loadenv";
@@ -10,7 +10,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
.object({
email: z.string().email().nonempty(),
password: z.string().nonempty(),
pubKey: z.string().nonempty().optional(),
pubKey: z.string().base64().nonempty().optional(),
})
.safeParse(await request.json());
if (!zodRes.success) error(400, "Invalid request body");
@@ -18,12 +18,15 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
const { email, password, pubKey } = zodRes.data;
const { accessToken, refreshToken } = await login(email.trim(), password.trim(), pubKey?.trim());
cookies.set("accessToken", accessToken, {
path: "/",
maxAge: Math.floor(ms(env.jwt.accessExp) / 1000),
sameSite: "strict",
});
cookies.set("refreshToken", refreshToken, {
path: "/api/auth",
maxAge: Math.floor(ms(env.jwt.refreshExp) / 1000),
httpOnly: true,
secure: true,
sameSite: "strict",
});
return json({ accessToken });
return text("Logged in", { headers: { "Content-Type": "text/plain" } });
};

View File

@@ -4,8 +4,11 @@ import type { RequestHandler } from "./$types";
export const POST: RequestHandler = async ({ cookies }) => {
const token = cookies.get("refreshToken");
if (!token) error(401, "Token not found");
if (!token) error(401, "Refresh token not found");
await logout(token.trim());
return text("Logged out");
cookies.delete("accessToken", { path: "/" });
cookies.delete("refreshToken", { path: "/api/auth" });
return text("Logged out", { headers: { "Content-Type": "text/plain" } });
};

View File

@@ -1,18 +1,20 @@
import { error, json } from "@sveltejs/kit";
import { refreshToken } from "$lib/server/services/auth";
import { error, text } from "@sveltejs/kit";
import { refreshTokens } from "$lib/server/services/auth";
import type { RequestHandler } from "./$types";
export const POST: RequestHandler = async ({ cookies }) => {
const token = cookies.get("refreshToken");
if (!token) error(401, "Token not found");
if (!token) error(401, "Refresh token not found");
const { accessToken, refreshToken: newToken } = await refreshToken(token.trim());
const { accessToken, refreshToken } = await refreshTokens(token.trim());
cookies.set("refreshToken", newToken, {
path: "/api/auth",
httpOnly: true,
secure: true,
cookies.set("accessToken", accessToken, {
path: "/",
sameSite: "strict",
});
return json({ accessToken });
cookies.set("refreshToken", refreshToken, {
path: "/api/auth",
sameSite: "strict",
});
return text("Token refreshed", { headers: { "Content-Type": "text/plain" } });
};

View File

@@ -4,7 +4,7 @@ import { authenticate } from "$lib/server/modules/auth";
import { registerPubKey } from "$lib/server/services/key";
import type { RequestHandler } from "./$types";
export const POST: RequestHandler = async ({ request }) => {
export const POST: RequestHandler = async ({ request, cookies }) => {
const zodRes = z
.object({
pubKey: z.string().base64().nonempty(),
@@ -12,7 +12,7 @@ export const POST: RequestHandler = async ({ request }) => {
.safeParse(await request.json());
if (!zodRes.success) error(400, "Invalid request body");
const { userId, clientId } = authenticate(request);
const { userId, clientId } = authenticate(cookies);
if (clientId) {
error(403, "Forbidden");
}