diff --git a/spring-jwt/.gitattributes b/spring-jwt/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/spring-jwt/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/spring-jwt/.gitignore b/spring-jwt/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/spring-jwt/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/spring-jwt/build.gradle.kts b/spring-jwt/build.gradle.kts new file mode 100644 index 0000000..573572a --- /dev/null +++ b/spring-jwt/build.gradle.kts @@ -0,0 +1,43 @@ +plugins { + java + id("org.springframework.boot") version "3.3.5" + id("io.spring.dependency-management") version "1.1.6" +} + +group = "io.github.jlzhjp" +version = "0.0.1-SNAPSHOT" + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +configurations { + compileOnly { + extendsFrom(configurations.annotationProcessor.get()) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.springframework.boot:spring-boot-starter-data-jpa") + implementation("org.springframework.boot:spring-boot-starter-security") + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("io.jsonwebtoken:jjwt-impl:0.11.5") + implementation("io.jsonwebtoken:jjwt-api:0.11.5") + implementation("io.jsonwebtoken:jjwt-jackson:0.11.5") + compileOnly("org.projectlombok:lombok") + runtimeOnly("com.h2database:h2") + annotationProcessor("org.projectlombok:lombok") + testImplementation("org.springframework.boot:spring-boot-starter-test") + testImplementation("org.springframework.security:spring-security-test") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} + +tasks.withType { + useJUnitPlatform() +} diff --git a/spring-jwt/frontend/.gitignore b/spring-jwt/frontend/.gitignore new file mode 100644 index 0000000..a547bf3 --- /dev/null +++ b/spring-jwt/frontend/.gitignore @@ -0,0 +1,24 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/spring-jwt/frontend/.prettierrc.json b/spring-jwt/frontend/.prettierrc.json new file mode 100644 index 0000000..cce9d3c --- /dev/null +++ b/spring-jwt/frontend/.prettierrc.json @@ -0,0 +1,3 @@ +{ + "semi": false +} diff --git a/spring-jwt/frontend/README.md b/spring-jwt/frontend/README.md new file mode 100644 index 0000000..74872fd --- /dev/null +++ b/spring-jwt/frontend/README.md @@ -0,0 +1,50 @@ +# React + TypeScript + Vite + +This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. + +Currently, two official plugins are available: + +- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh +- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh + +## Expanding the ESLint configuration + +If you are developing a production application, we recommend updating the configuration to enable type aware lint rules: + +- Configure the top-level `parserOptions` property like this: + +```js +export default tseslint.config({ + languageOptions: { + // other options... + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + }, +}) +``` + +- Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked` +- Optionally add `...tseslint.configs.stylisticTypeChecked` +- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config: + +```js +// eslint.config.js +import react from 'eslint-plugin-react' + +export default tseslint.config({ + // Set the react version + settings: { react: { version: '18.3' } }, + plugins: { + // Add the react plugin + react, + }, + rules: { + // other rules... + // Enable its recommended rules + ...react.configs.recommended.rules, + ...react.configs['jsx-runtime'].rules, + }, +}) +``` diff --git a/spring-jwt/frontend/bun.lockb b/spring-jwt/frontend/bun.lockb new file mode 100644 index 0000000..4c2e80f Binary files /dev/null and b/spring-jwt/frontend/bun.lockb differ diff --git a/spring-jwt/frontend/eslint.config.js b/spring-jwt/frontend/eslint.config.js new file mode 100644 index 0000000..179d176 --- /dev/null +++ b/spring-jwt/frontend/eslint.config.js @@ -0,0 +1,30 @@ +import js from "@eslint/js" +import globals from "globals" +import reactHooks from "eslint-plugin-react-hooks" +import reactRefresh from "eslint-plugin-react-refresh" +import reactCompiler from "eslint-plugin-react-compiler" +import tseslint from "typescript-eslint" + +export default tseslint.config( + { ignores: ["dist"] }, + { + extends: [js.configs.recommended, ...tseslint.configs.recommended], + files: ["**/*.{ts,tsx}"], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + plugins: { + "react-hooks": reactHooks, + "react-refresh": reactRefresh, + "react-compiler": reactCompiler, + }, + rules: { + ...reactHooks.configs.recommended.rules, + "react-refresh/only-export-components": [ + "warn", + { allowConstantExport: true }, + ], + }, + } +) diff --git a/spring-jwt/frontend/index.html b/spring-jwt/frontend/index.html new file mode 100644 index 0000000..e4b78ea --- /dev/null +++ b/spring-jwt/frontend/index.html @@ -0,0 +1,13 @@ + + + + + + + Vite + React + TS + + +
+ + + diff --git a/spring-jwt/frontend/package.json b/spring-jwt/frontend/package.json new file mode 100644 index 0000000..53ec55e --- /dev/null +++ b/spring-jwt/frontend/package.json @@ -0,0 +1,42 @@ +{ + "name": "frontend", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "lint": "eslint .", + "preview": "vite preview" + }, + "dependencies": { + "@tanstack/react-query": "^5.61.0", + "react": "^19.0.0-rc.1", + "react-dom": "^19.0.0-rc.1", + "react-router-dom": "^7.0.0-pre.6" + }, + "overrides": { + "@types/react": "npm:types-react@rc", + "@types/react-dom": "npm:types-react-dom@rc" + }, + "devDependencies": { + "@eslint/js": "^9.13.0", + "@tanstack/eslint-plugin-query": "^5.60.1", + "@types/react": "npm:types-react@rc", + "@types/react-dom": "npm:types-react-dom@rc", + "@vitejs/plugin-react": "^4.3.3", + "autoprefixer": "^10.4.20", + "babel-plugin-react-compiler": "^19.0.0-beta-0dec889-20241115", + "daisyui": "^4.12.14", + "eslint": "^9.13.0", + "eslint-plugin-react-compiler": "^19.0.0-beta-0dec889-20241115", + "eslint-plugin-react-hooks": "^5.0.0", + "eslint-plugin-react-refresh": "^0.4.14", + "globals": "^15.11.0", + "postcss": "^8.4.49", + "tailwindcss": "^3.4.15", + "typescript": "~5.6.2", + "typescript-eslint": "^8.11.0", + "vite": "^5.4.10" + } +} diff --git a/spring-jwt/frontend/public/vite.svg b/spring-jwt/frontend/public/vite.svg new file mode 100644 index 0000000..e7b8dfb --- /dev/null +++ b/spring-jwt/frontend/public/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/spring-jwt/frontend/src/assets/react.svg b/spring-jwt/frontend/src/assets/react.svg new file mode 100644 index 0000000..6c87de9 --- /dev/null +++ b/spring-jwt/frontend/src/assets/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/spring-jwt/frontend/src/components/Preloader.tsx b/spring-jwt/frontend/src/components/Preloader.tsx new file mode 100644 index 0000000..56008d8 --- /dev/null +++ b/spring-jwt/frontend/src/components/Preloader.tsx @@ -0,0 +1,7 @@ +export default function Preloader() { + return ( +
+ +
+ ) +} diff --git a/spring-jwt/frontend/src/index.css b/spring-jwt/frontend/src/index.css new file mode 100644 index 0000000..bd6213e --- /dev/null +++ b/spring-jwt/frontend/src/index.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; \ No newline at end of file diff --git a/spring-jwt/frontend/src/lib/AuthorizationProvider.tsx b/spring-jwt/frontend/src/lib/AuthorizationProvider.tsx new file mode 100644 index 0000000..3b19a18 --- /dev/null +++ b/spring-jwt/frontend/src/lib/AuthorizationProvider.tsx @@ -0,0 +1,33 @@ +import { useState, type ReactNode } from "react" +import { createContext } from "react" + +type AuthorizationInfo = { + token: string +} + +type AuthorizationContextType = { + auth: AuthorizationInfo | undefined + setAuth: (info: AuthorizationInfo | undefined) => void +} + +const AuthorizationContext = createContext({ + setAuth: () => {}, + auth: undefined, +}) + +const AuthorizationProvider = ({ children }: { children?: ReactNode }) => { + const [authorizationInfo, setAuthorizationInfo] = useState< + AuthorizationInfo | undefined + >(undefined) + + return ( + + {children} + + ) +} + +export default AuthorizationProvider +export { AuthorizationContext } diff --git a/spring-jwt/frontend/src/lib/api.ts b/spring-jwt/frontend/src/lib/api.ts new file mode 100644 index 0000000..3c48cc1 --- /dev/null +++ b/spring-jwt/frontend/src/lib/api.ts @@ -0,0 +1,63 @@ +import { + ApiError, + AuthenticationRequest, + AuthenticationResponse, + RegisterRequest, + UserInfoResponse, +} from "./types" + +export const getUser = async (token: string) => { + const res = await fetch("http://localhost:8080/user", { + headers: { + Authorization: `Bearer ${token}`, + }, + }) + const user: UserInfoResponse = await res.json() + return user +} + +export const getNotice = async (token: string) => { + const res = await fetch("http://localhost:8080/notice", { + headers: { + Authorization: `Bearer ${token}`, + }, + }) + const notice = await res.text() + return notice +} + +export const login = async (request: AuthenticationRequest) => { + const res = await fetch("http://localhost:8080/auth/authenticate", { + method: "POST", + body: JSON.stringify(request), + headers: { + "Content-Type": "application/json", + }, + }) + + if (!res.ok) { + const error = (await res.json()) as ApiError + throw error + } + + const data = (await res.json()) as AuthenticationResponse + return data +} + +export const signup = async (request: RegisterRequest) => { + const res = await fetch("http://localhost:8080/auth/signup", { + method: "POST", + body: JSON.stringify(request), + headers: { + "Content-Type": "application/json", + }, + }) + + if (!res.ok) { + const error = (await res.json()) as ApiError + throw error + } + + const data = (await res.json()) as AuthenticationResponse + return data +} diff --git a/spring-jwt/frontend/src/lib/types.ts b/spring-jwt/frontend/src/lib/types.ts new file mode 100644 index 0000000..170cb54 --- /dev/null +++ b/spring-jwt/frontend/src/lib/types.ts @@ -0,0 +1,32 @@ +export type ApiError = { + timestamp: number + error: string + message: string +} + +export type AuthenticationResponse = { + token: string +} + +export type AuthenticationRequest = { + email: string + password: string +} + +export type Role = "ADMIN" | "USER" + +export type RegisterRequest = { + firstname: string + lastname: string + email: string + password: string + role: Role +} + +export type UserInfoResponse = { + firstname: string + lastname: string + email: string + role: string + authorities: string[] +} diff --git a/spring-jwt/frontend/src/lib/useJWT.ts b/spring-jwt/frontend/src/lib/useJWT.ts new file mode 100644 index 0000000..2015560 --- /dev/null +++ b/spring-jwt/frontend/src/lib/useJWT.ts @@ -0,0 +1,6 @@ +import { use } from "react" +import { AuthorizationContext } from "./AuthorizationProvider" + +export default function useJWT() { + return use(AuthorizationContext).auth?.token +} diff --git a/spring-jwt/frontend/src/main.tsx b/spring-jwt/frontend/src/main.tsx new file mode 100644 index 0000000..4cedab8 --- /dev/null +++ b/spring-jwt/frontend/src/main.tsx @@ -0,0 +1,37 @@ +import { StrictMode } from "react" +import { createRoot } from "react-dom/client" +import { + createBrowserRouter, + createRoutesFromElements, + Route, + RouterProvider, +} from "react-router-dom" +import "./index.css" +import NoticeView from "./routes/NoticeView.tsx" +import SignupView from "./routes/SignupView.tsx" +import LoginView from "./routes/LoginView.tsx" +import AuthorizationProvider from "./lib/AuthorizationProvider.tsx" +import { QueryClient, QueryClientProvider } from "@tanstack/react-query" +import Layout from "./routes/Layout.tsx" + +const router = createBrowserRouter( + createRoutesFromElements( + }> + } /> + } /> + } /> + + ) +) + +const queryClient = new QueryClient() + +createRoot(document.getElementById("root")!).render( + + + + + + + +) diff --git a/spring-jwt/frontend/src/routes/Layout.tsx b/spring-jwt/frontend/src/routes/Layout.tsx new file mode 100644 index 0000000..e7af834 --- /dev/null +++ b/spring-jwt/frontend/src/routes/Layout.tsx @@ -0,0 +1,46 @@ +import { Link, Outlet } from "react-router-dom" +import { AuthorizationContext } from "../lib/AuthorizationProvider" +import { use } from "react" + +function NavBarActions() { + const { auth, setAuth } = use(AuthorizationContext) + + if (!auth) { + return ( +
    +
  • + Login +
  • +
  • + Signup +
  • +
+ ) + } + + return ( + + ) +} + +export default function Layout() { + return ( + <> +
+
+ + Spring Security JWT + +
+
+ +
+
+
+ +
+ + ) +} diff --git a/spring-jwt/frontend/src/routes/LoginView.tsx b/spring-jwt/frontend/src/routes/LoginView.tsx new file mode 100644 index 0000000..4327255 --- /dev/null +++ b/spring-jwt/frontend/src/routes/LoginView.tsx @@ -0,0 +1,62 @@ +import { use, useState } from "react" +import { AuthorizationContext } from "../lib/AuthorizationProvider" +import { useNavigate } from "react-router-dom" +import { login } from "../lib/api" + +export default function LoginView() { + const navigate = useNavigate() + const { setAuth } = use(AuthorizationContext) + const [errorMessage, setErrorMessage] = useState("") + + const handleSubmit = async (formData: FormData) => { + const email = formData.get("email")!.toString() + const password = formData.get("password")!.toString() + + try { + const data = await login({ email, password }) + setAuth({ token: data.token }) + navigate("/") + } catch (error) { + setErrorMessage(JSON.stringify(error, null, 2)) + + const dialog = document.querySelector( + "#error-dialog" + ) as HTMLDialogElement + + dialog.showModal() + } + } + + return ( + <> + +
+

Error

+

{errorMessage}

+
+
+ +
+
+
+
+ +
+

Login

+ + + +
+ + ) +} diff --git a/spring-jwt/frontend/src/routes/NoticeView.tsx b/spring-jwt/frontend/src/routes/NoticeView.tsx new file mode 100644 index 0000000..85bb96e --- /dev/null +++ b/spring-jwt/frontend/src/routes/NoticeView.tsx @@ -0,0 +1,181 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query" +import Preloader from "../components/Preloader" +import { getNotice, getUser } from "../lib/api" +import useJWT from "../lib/useJWT" +import { useState } from "react" + +function UserCard() { + const token = useJWT() + + const { + isPending, + error, + data: user, + } = useQuery({ + queryKey: ["user", token], + queryFn: () => getUser(token!), + enabled: !!token, + }) + + if (isPending) { + return + } + + if (error) { + return ( +
+
+ {JSON.stringify(error, null, 2)} +
+
+ ) + } + + return ( +
+
+

+ Name: + {user.firstname} {user.lastname} +

+

+ Email: + {user.email} +

+

+ Role: + {user.role} +

+

+ Authorities + {user.authorities.join(", ")} +

+
+
+ ) +} + +function Notice({ notice, onEdit }: { notice: string; onEdit: () => void }) { + const token = useJWT() + const { data: user } = useQuery({ + queryKey: ["user", token], + queryFn: () => getUser(token!), + enabled: !!token, + }) + + const handleEditButtonClick = () => onEdit() + + return ( + <> +
+
{notice}
+ {user?.authorities?.includes("WRITE") && ( + + )} +
+ + ) +} + +function NoticeEditor({ + initialData, + onCompleted, +}: { + initialData: string + onCompleted: () => void +}) { + const token = useJWT() + const queryClient = useQueryClient() + const [notice, setNotice] = useState(initialData) + + const { mutate } = useMutation({ + mutationFn: async (data: string) => { + await fetch("http://localhost:8080/notice", { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + }, + body: data, + }) + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ["notice", token] }) + }, + }) + + const handleButtonClick = () => { + mutate(notice) + onCompleted() + } + + return ( +
+ setNotice(e.target.value)} + /> + +
+ ) +} + +export default function NoticeView() { + const token = useJWT() + const [isEditing, setIsEditing] = useState(false) + + const { + data: notice, + isPending, + error, + } = useQuery({ + queryKey: ["notice", token], + queryFn: () => getNotice(token!), + enabled: !!token, + }) + + if (!token) { + return ( +
+
+ Please Login First. +
+
+ ) + } + + if (isPending) { + return + } + + if (error) { + return ( +
+
+ {JSON.stringify(error, null, 2)} +
+
+ ) + } + + return ( + <> + +
+ {isEditing ? ( + setIsEditing(false)} + /> + ) : ( + setIsEditing(true)} /> + )} +
+ + ) +} diff --git a/spring-jwt/frontend/src/routes/SignupView.tsx b/spring-jwt/frontend/src/routes/SignupView.tsx new file mode 100644 index 0000000..5af6a8a --- /dev/null +++ b/spring-jwt/frontend/src/routes/SignupView.tsx @@ -0,0 +1,100 @@ +import { use, useState } from "react" +import { useNavigate } from "react-router-dom" +import { AuthorizationContext } from "../lib/AuthorizationProvider" +import { signup } from "../lib/api" +import { Role } from "../lib/types" + +export default function SignupView() { + const navigate = useNavigate() + const { setAuth } = use(AuthorizationContext) + const [errorMessage, setErrorMessage] = useState("") + + const showDialog = (message: string) => { + const dialog = document.querySelector("#error-dialog") as HTMLDialogElement + setErrorMessage(message) + dialog.showModal() + } + + const handleSubmit = async (formData: FormData) => { + try { + const firstname = formData.get("firstname")!.toString() + const lastname = formData.get("lastname")!.toString() + const email = formData.get("email")!.toString() + const password = formData.get("password")!.toString() + const role = formData.get("role")!.toString() + + const data = await signup({ + firstname, + lastname, + email, + password, + role: role as Role, + }) + setAuth({ token: data.token }) + navigate("/") + } catch (error) { + showDialog(JSON.stringify(error, null, 2)) + } + } + + return ( + <> + +
+

Error

+

{errorMessage}

+
+
+ +
+
+
+
+ +
+

Sign up

+
+ + +
+ + + + +
+ + ) +} diff --git a/spring-jwt/frontend/src/vite-env.d.ts b/spring-jwt/frontend/src/vite-env.d.ts new file mode 100644 index 0000000..11f02fe --- /dev/null +++ b/spring-jwt/frontend/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/spring-jwt/frontend/tailwind.config.js b/spring-jwt/frontend/tailwind.config.js new file mode 100644 index 0000000..aacd647 --- /dev/null +++ b/spring-jwt/frontend/tailwind.config.js @@ -0,0 +1,8 @@ +/** @type {import('tailwindcss').Config} */ +export default { + content: ["./index.html", "./src/**/*.{html,js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [require("daisyui")], +}; diff --git a/spring-jwt/frontend/tsconfig.app.json b/spring-jwt/frontend/tsconfig.app.json new file mode 100644 index 0000000..f867de0 --- /dev/null +++ b/spring-jwt/frontend/tsconfig.app.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "Bundler", + "allowImportingTsExtensions": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "react-jsx", + + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true + }, + "include": ["src"] +} diff --git a/spring-jwt/frontend/tsconfig.json b/spring-jwt/frontend/tsconfig.json new file mode 100644 index 0000000..1ffef60 --- /dev/null +++ b/spring-jwt/frontend/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" } + ] +} diff --git a/spring-jwt/frontend/tsconfig.node.json b/spring-jwt/frontend/tsconfig.node.json new file mode 100644 index 0000000..abcd7f0 --- /dev/null +++ b/spring-jwt/frontend/tsconfig.node.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "target": "ES2022", + "lib": ["ES2023"], + "module": "ESNext", + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "Bundler", + "allowImportingTsExtensions": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, + + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true + }, + "include": ["vite.config.ts"] +} diff --git a/spring-jwt/frontend/vite.config.ts b/spring-jwt/frontend/vite.config.ts new file mode 100644 index 0000000..d89c10c --- /dev/null +++ b/spring-jwt/frontend/vite.config.ts @@ -0,0 +1,21 @@ +import { defineConfig } from "vite" +import tailwindcss from "tailwindcss" +import react from "@vitejs/plugin-react" + +const ReactCompilerConfig = {} + +// https://vite.dev/config/ +export default defineConfig({ + plugins: [ + react({ + babel: { + plugins: [["babel-plugin-react-compiler", ReactCompilerConfig]], + }, + }), + ], + css: { + postcss: { + plugins: [tailwindcss()], + }, + }, +}) diff --git a/spring-jwt/gradle/wrapper/gradle-wrapper.jar b/spring-jwt/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/spring-jwt/gradle/wrapper/gradle-wrapper.jar differ diff --git a/spring-jwt/gradle/wrapper/gradle-wrapper.properties b/spring-jwt/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..df97d72 --- /dev/null +++ b/spring-jwt/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/spring-jwt/gradlew b/spring-jwt/gradlew new file mode 100644 index 0000000..f5feea6 --- /dev/null +++ b/spring-jwt/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/spring-jwt/gradlew.bat b/spring-jwt/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/spring-jwt/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/spring-jwt/settings.gradle.kts b/spring-jwt/settings.gradle.kts new file mode 100644 index 0000000..24dbae0 --- /dev/null +++ b/spring-jwt/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "spring-jwt" diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/ApiError.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/ApiError.java new file mode 100644 index 0000000..0545167 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/ApiError.java @@ -0,0 +1,36 @@ +package io.github.jlzhjp.springjwt; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.ServletResponse; +import lombok.*; + +import java.io.IOException; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class ApiError { + private long timestamp; + private String error; + private String message; + + public static ApiError fromException(Exception e) { + return ApiError.builder() + .timestamp(System.currentTimeMillis()) + .error(e.getClass().getName()) + .message(e.getMessage()) + .build(); + } + + public String toJson() throws JsonProcessingException { + return new ObjectMapper().writeValueAsString(this); + } + + public void writeToResponse(ServletResponse response) throws IOException { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + response.getWriter().write(toJson()); + } +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/SpringJwtApplication.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/SpringJwtApplication.java new file mode 100644 index 0000000..8e67a5c --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/SpringJwtApplication.java @@ -0,0 +1,13 @@ +package io.github.jlzhjp.springjwt; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringJwtApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringJwtApplication.class, args); + } + +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/AuthenticationController.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/AuthenticationController.java new file mode 100644 index 0000000..229fe9a --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/AuthenticationController.java @@ -0,0 +1,28 @@ +package io.github.jlzhjp.springjwt.auth; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/auth") +@RequiredArgsConstructor +public class AuthenticationController { + private final AuthenticationService authenticationService; + + @PostMapping("/signup") + public AuthenticationResponse register( + @RequestBody RegisterRequest request + ) { + return authenticationService.register(request); + } + + @PostMapping("/authenticate") + public AuthenticationResponse authenticate( + @RequestBody AuthenticationRequest request + ) { + return authenticationService.authenticate(request); + } +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/AuthenticationRequest.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/AuthenticationRequest.java new file mode 100644 index 0000000..5b963de --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/AuthenticationRequest.java @@ -0,0 +1,15 @@ +package io.github.jlzhjp.springjwt.auth; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class AuthenticationRequest { + private String email; + private String password; +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/AuthenticationResponse.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/AuthenticationResponse.java new file mode 100644 index 0000000..e7bafa9 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/AuthenticationResponse.java @@ -0,0 +1,11 @@ +package io.github.jlzhjp.springjwt.auth; + +import lombok.*; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class AuthenticationResponse { + private String token; +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/AuthenticationService.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/AuthenticationService.java new file mode 100644 index 0000000..cd78288 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/AuthenticationService.java @@ -0,0 +1,57 @@ +package io.github.jlzhjp.springjwt.auth; + +import io.github.jlzhjp.springjwt.config.JwtService; +import io.github.jlzhjp.springjwt.user.Role; +import io.github.jlzhjp.springjwt.user.RoleRepository; +import io.github.jlzhjp.springjwt.user.User; +import io.github.jlzhjp.springjwt.user.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class AuthenticationService { + private final UserRepository userRepository; + private final PasswordEncoder passwordEncoder; + private final JwtService jwtService; + private final AuthenticationManager authenticationManager; + private final RoleRepository roleRepository; + + public AuthenticationResponse register(RegisterRequest request) { + Role role = roleRepository.findByName(request.getRole()) + .orElseThrow(() -> new RoleNameNotFoundException("Role name " + request.getRole() + " not found")); + + var user = User.builder() + .firstname(request.getFirstname()) + .lastname(request.getLastname()) + .email(request.getEmail()) + .password(passwordEncoder.encode(request.getPassword())) + .role(role) + .build(); + userRepository.save(user); + + var jwtToken = jwtService.generateToken(user); + return AuthenticationResponse.builder() + .token(jwtToken) + .build(); + } + + public AuthenticationResponse authenticate(AuthenticationRequest request) { + authenticationManager.authenticate( + new UsernamePasswordAuthenticationToken( + request.getEmail(), + request.getPassword() + ) + ); + var user = userRepository.findByEmail(request.getEmail()) + .orElseThrow(); + + var jwtToken = jwtService.generateToken(user); + return AuthenticationResponse.builder() + .token(jwtToken) + .build(); + } +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/RegisterRequest.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/RegisterRequest.java new file mode 100644 index 0000000..772ae13 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/RegisterRequest.java @@ -0,0 +1,18 @@ +package io.github.jlzhjp.springjwt.auth; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class RegisterRequest { + private String firstname; + private String lastname; + private String email; + private String password; + private String role; +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/RoleNameNotFoundException.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/RoleNameNotFoundException.java new file mode 100644 index 0000000..4753f8e --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/auth/RoleNameNotFoundException.java @@ -0,0 +1,7 @@ +package io.github.jlzhjp.springjwt.auth; + +public class RoleNameNotFoundException extends RuntimeException { + public RoleNameNotFoundException(String message) { + super(message); + } +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/config/ApplicationConfiguration.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/config/ApplicationConfiguration.java new file mode 100644 index 0000000..d453906 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/config/ApplicationConfiguration.java @@ -0,0 +1,54 @@ +package io.github.jlzhjp.springjwt.config; + + +import io.github.jlzhjp.springjwt.user.*; +import lombok.RequiredArgsConstructor; +import org.springframework.boot.ApplicationRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.password.PasswordEncoder; + +import java.util.List; + +@RequiredArgsConstructor +@Configuration +public class ApplicationConfiguration { + private final AuthorityRepository authorityRepository; + private final RoleRepository roleRepository; + private final PasswordEncoder passwordEncoder; + + @Bean + public ApplicationRunner applicationRunner(UserRepository userRepository) { + return args -> { + Authority read = Authority.builder().name("READ").build(); + Authority write = Authority.builder().name("WRITE").build(); + + authorityRepository.saveAll(List.of(read, write)); + + Role admin = Role.builder().name("ADMIN").build(); + admin.getAuthorities().addAll(List.of(read, write)); + Role user = Role.builder().name("USER").build(); + user.getAuthorities().add(read); + + roleRepository.saveAll(List.of(admin, user)); + + User adminUser = User.builder() + .email("admin@admin.com") + .firstname("admin") + .lastname("admin") + .role(admin) + .password(passwordEncoder.encode("admin")) + .build(); + + User normalUser = User.builder() + .email("user@user.com") + .firstname("user") + .lastname("user") + .role(user) + .password(passwordEncoder.encode("user")) + .build(); + + userRepository.saveAll(List.of(adminUser, normalUser)); + }; + } +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/config/JwtAuthenticationFilter.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/config/JwtAuthenticationFilter.java new file mode 100644 index 0000000..109e50d --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/config/JwtAuthenticationFilter.java @@ -0,0 +1,56 @@ +package io.github.jlzhjp.springjwt.config; + +import jakarta.annotation.Nonnull; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@Component +@RequiredArgsConstructor +public class JwtAuthenticationFilter extends OncePerRequestFilter { + private final JwtService jwtService; + private final UserDetailsService userDetailsService; + + @Override + protected void doFilterInternal( + @Nonnull HttpServletRequest request, + @Nonnull HttpServletResponse response, + @Nonnull FilterChain filterChain) throws ServletException, IOException { + final String authorizationHeader = request.getHeader("Authorization"); + final String jwt; + final String userEmail; + if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) { + filterChain.doFilter(request, response); + return; + } + jwt = authorizationHeader.substring(7); + userEmail = jwtService.extractUsername(jwt); + if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) { + UserDetails userDetails = userDetailsService.loadUserByUsername(userEmail); + if (jwtService.isTokenValid(jwt, userDetails)){ + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( + userDetails, + null, + userDetails.getAuthorities() + ); + authenticationToken.setDetails( + new WebAuthenticationDetailsSource().buildDetails(request) + ); + SecurityContextHolder.getContext().setAuthentication(authenticationToken); + } + } + + filterChain.doFilter(request, response); + } +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/config/JwtService.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/config/JwtService.java new file mode 100644 index 0000000..f1c341a --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/config/JwtService.java @@ -0,0 +1,75 @@ +package io.github.jlzhjp.springjwt.config; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.security.Keys; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Service; + +import java.security.Key; +import java.util.Base64; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +@Service +public class JwtService { + private static final String SECRET_KEY = "2cd7a0a076513654c9ab9c8d2c34c83d9557e3817e790e36e6c698e8a0ef858f0d7a8d178fc53db8f00287a4185c2cf481db8660de47d8b0bd3e8e1571934d0af4007182ada739cf1860530817758b311e3657e3fa27c7f2b54fd59035a74d1c52fbf0a5617bd0446a1d104a42cd3f765758ff3abb424fabaae45ea52653cdd2c80cae411a4d3ab1d3578230ea67be1d699df1e90fff2cc3afe89a19e4a3dc048e8ecb7f6bb46f4270cca00a19e7bdbb5138f665dc54111f49449ce0e424069f37be645fad7642c23874d32e1d499a56158b2b4849c4a3b7ba0e9b9c0fe200db0e3a03c145f44c1f983429c85a73da45d7d79251fadcf5fb711a383a527dbac022c0bbfe30bc20b0501e7d8e99ae766ce9e676142ac1b022fe8a52285071de80beb5603af6e6e8120c1b970ca826a1be4289b0d40770996819e445e269b162a7f38d29400b914e688c68f6fd3677cbc5e44c9280465aed13c72ff0118020b968afbcdb68350bae89d667a4d1cbdc1f60377491cedd53c5a27a43dd577eb33232cdf13f7ef11a46bdf1df53a0a100607c7b95dbf87cdb88df76223a705f0e9deab073baf3414b19e5236c63dd59f216f551fb9fb623ec1a9849a135773fe26c1faba81b9dd5cbf272140b2b9e1e7462396233b538ebf78c4f24fdb44fd507a9e4e361fb7414770019e31643668b26f2c4ceb4309d576c88a849a4bc219ee96f86"; + + public Key getSigningKey() { + byte[] keyBytes = Base64.getDecoder().decode(SECRET_KEY); + return Keys.hmacShaKeyFor(keyBytes); + } + + public String extractUsername(String token) { + return extractClaim(token, Claims::getSubject); + } + + public T extractClaim(String token, Function claimsResolver) { + final Claims claims = extractAllClaims(token); + return claimsResolver.apply(claims); + } + + public String generateToken(UserDetails userDetails) { + return generateToken(new HashMap<>(), userDetails); + } + + public String generateToken( + Map extraClaims, + UserDetails userDetails + ) { + return Jwts + .builder() + .setClaims(extraClaims) + .setSubject(userDetails.getUsername()) + .setIssuedAt(new Date(System.currentTimeMillis())) + .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 24)) + .signWith(getSigningKey(), SignatureAlgorithm.HS256) + .compact(); + } + + public boolean isTokenValid(String token, UserDetails userDetails) { + final String username = extractUsername(token); + return (username.equals(userDetails.getUsername())) && + (!isTokenExpired(token)); + } + + private boolean isTokenExpired(String token) { + return extractTokenExpiration(token).before(new Date()); + } + + private Date extractTokenExpiration(String token) { + return extractClaim(token, Claims::getExpiration); + } + + private Claims extractAllClaims(String token) { + return Jwts + .parserBuilder() + .setSigningKey(getSigningKey()) + .build() + .parseClaimsJws(token) + .getBody(); + } +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/config/SecurityConfiguration.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/config/SecurityConfiguration.java new file mode 100644 index 0000000..44a0632 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/config/SecurityConfiguration.java @@ -0,0 +1,92 @@ +package io.github.jlzhjp.springjwt.config; + +import io.github.jlzhjp.springjwt.ApiError; +import io.github.jlzhjp.springjwt.user.UserRepository; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.Customizer; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +import static org.springframework.security.config.Customizer.withDefaults; + +@Configuration +@EnableWebSecurity +@EnableMethodSecurity +public class SecurityConfiguration { + + @Bean + public SecurityFilterChain securityFilterChain( + HttpSecurity http, + JwtAuthenticationFilter jwtAuthenticationFilter) throws Exception { + return http + .cors(withDefaults()) + .csrf(csrf -> csrf.disable()) + .authorizeHttpRequests(request -> request + .requestMatchers("/auth/**").permitAll() + .requestMatchers("/h2-console/**").permitAll() + .anyRequest().authenticated()) + .sessionManagement(session -> session + .sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) + .build(); + } + + @Bean + public UserDetailsService userDetailsService(UserRepository userRepository) { + return username -> userRepository + .findByEmail(username) + .orElseThrow(() -> new UsernameNotFoundException("User not found")); + } + + @Bean + public AuthenticationProvider daoAuthenticationProvider( + UserDetailsService userDetailsService, + PasswordEncoder passwordEncoder) { + DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); + provider.setUserDetailsService(userDetailsService); + provider.setPasswordEncoder(passwordEncoder); + return provider; + } + + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception { + return config.getAuthenticationManager(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public AccessDeniedHandler accessDeniedHandler() { + return (request, response, accessDeniedException) -> { + ApiError error = ApiError.fromException(accessDeniedException); + error.writeToResponse(response); + }; + } + + @Bean + public AuthenticationEntryPoint authenticationEntryPoint() { + return (request, response, authException) -> { + ApiError error = ApiError.fromException(authException); + error.writeToResponse(response); + }; + } +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/Authority.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/Authority.java new file mode 100644 index 0000000..f10b151 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/Authority.java @@ -0,0 +1,21 @@ +package io.github.jlzhjp.springjwt.user; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.RequiredArgsConstructor; + +@Entity +@Data +@Builder +@AllArgsConstructor +@RequiredArgsConstructor +public class Authority { + @Id + @GeneratedValue + private Long id; + private String name; +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/AuthorityRepository.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/AuthorityRepository.java new file mode 100644 index 0000000..9935860 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/AuthorityRepository.java @@ -0,0 +1,8 @@ +package io.github.jlzhjp.springjwt.user; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface AuthorityRepository extends JpaRepository { +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/Role.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/Role.java new file mode 100644 index 0000000..5577600 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/Role.java @@ -0,0 +1,29 @@ +package io.github.jlzhjp.springjwt.user; + +import jakarta.persistence.*; +import lombok.*; + +import java.util.HashSet; +import java.util.Set; + +@Entity +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class Role { + @Id + @GeneratedValue + private Long id; + + private String name; + + @Builder.Default + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable( + name = "role_authority", + joinColumns = @JoinColumn(name = "student_id"), + inverseJoinColumns = @JoinColumn(name = "authority_id") + ) + private Set authorities = new HashSet<>(); +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/RoleRepository.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/RoleRepository.java new file mode 100644 index 0000000..65a65b1 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/RoleRepository.java @@ -0,0 +1,11 @@ +package io.github.jlzhjp.springjwt.user; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface RoleRepository extends JpaRepository { + Optional findByName(String name); +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/User.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/User.java new file mode 100644 index 0000000..b3867d9 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/User.java @@ -0,0 +1,46 @@ +package io.github.jlzhjp.springjwt.user; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; +import java.util.stream.Stream; + +@Entity +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "_user") +public class User implements UserDetails { + @Id + @GeneratedValue + private Long id; + private String firstname; + private String lastname; + private String email; + private String password; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "role_id") + private Role role; + + @Override + public Collection getAuthorities() { + return Stream.concat( + Stream.of(new SimpleGrantedAuthority("ROLE_" + role.getName())), + role.getAuthorities().stream().map(authority -> new SimpleGrantedAuthority(authority.getName())) + ).toList(); + } + + @Override + public String getUsername() { + return email; + } +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/UserController.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/UserController.java new file mode 100644 index 0000000..095a7f5 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/UserController.java @@ -0,0 +1,24 @@ +package io.github.jlzhjp.springjwt.user; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UserController { + + @GetMapping("/user") + public UserInfoResponse getUserInfo(@AuthenticationPrincipal User user) { + return UserInfoResponse.builder() + .email(user.getEmail()) + .firstname(user.getFirstname()) + .lastname(user.getLastname()) + .role(user.getRole().getName()) + .authorities(user.getAuthorities().stream() + .map(GrantedAuthority::getAuthority) + .filter(auth -> !auth.startsWith("ROLE_")) + .toList()) + .build(); + } +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/UserInfoResponse.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/UserInfoResponse.java new file mode 100644 index 0000000..aaa2de1 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/UserInfoResponse.java @@ -0,0 +1,20 @@ +package io.github.jlzhjp.springjwt.user; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class UserInfoResponse { + private String firstname; + private String lastname; + private String email; + private String role; + private List authorities; +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/UserRepository.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/UserRepository.java new file mode 100644 index 0000000..7aa7f94 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/user/UserRepository.java @@ -0,0 +1,11 @@ +package io.github.jlzhjp.springjwt.user; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface UserRepository extends JpaRepository { + Optional findByEmail(String email); +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/web/GlobalExceptionHandler.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/web/GlobalExceptionHandler.java new file mode 100644 index 0000000..eb39ea1 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/web/GlobalExceptionHandler.java @@ -0,0 +1,23 @@ +package io.github.jlzhjp.springjwt.web; + +import com.fasterxml.jackson.core.JsonProcessingException; +import io.github.jlzhjp.springjwt.ApiError; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.io.IOException; + +@RestControllerAdvice +public class GlobalExceptionHandler { + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public void handleException(HttpServletResponse response, Exception ex) throws IOException { + var error = ApiError.fromException(ex); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + response.getWriter().write(error.toJson()); + } +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/web/NoticeController.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/web/NoticeController.java new file mode 100644 index 0000000..7ba0c26 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/web/NoticeController.java @@ -0,0 +1,26 @@ +package io.github.jlzhjp.springjwt.web; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.concurrent.atomic.AtomicReference; + +@RestController +public class NoticeController { + private final AtomicReference notice = new AtomicReference<>(""); + + @PreAuthorize("hasAuthority('READ')") + @GetMapping("/notice") + public String notice() { + return notice.get(); + } + + @PreAuthorize("hasAuthority('WRITE')") + @PostMapping("/notice") + public void updateNotice(@RequestBody String content) { + notice.set(content); + } +} diff --git a/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/web/WebMvcConfiguration.java b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/web/WebMvcConfiguration.java new file mode 100644 index 0000000..f12f753 --- /dev/null +++ b/spring-jwt/src/main/java/io/github/jlzhjp/springjwt/web/WebMvcConfiguration.java @@ -0,0 +1,26 @@ +package io.github.jlzhjp.springjwt.web; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; + +@Configuration +@EnableWebMvc +public class WebMvcConfiguration implements WebMvcConfigurer { + @Bean + CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(List.of("*")); + configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); + configuration.setAllowedHeaders(List.of("*")); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } +} diff --git a/spring-jwt/src/main/resources/application.properties b/spring-jwt/src/main/resources/application.properties new file mode 100644 index 0000000..a17be84 --- /dev/null +++ b/spring-jwt/src/main/resources/application.properties @@ -0,0 +1,7 @@ +spring.application.name=spring-jwt + +spring.datasource.url=jdbc:h2:mem:testdb + +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +spring.jpa.database=h2 diff --git a/spring-jwt/src/test/java/io/github/jlzhjp/springjwt/SpringJwtApplicationTests.java b/spring-jwt/src/test/java/io/github/jlzhjp/springjwt/SpringJwtApplicationTests.java new file mode 100644 index 0000000..0c4e2ab --- /dev/null +++ b/spring-jwt/src/test/java/io/github/jlzhjp/springjwt/SpringJwtApplicationTests.java @@ -0,0 +1,13 @@ +package io.github.jlzhjp.springjwt; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringJwtApplicationTests { + + @Test + void contextLoads() { + } + +}