├── .gitignore
├── .mvn
└── wrapper
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── LICENSE
├── README.md
├── compose.yaml
├── mvnw
├── mvnw.cmd
├── pom.xml
├── react-frontend
├── .eslintrc.cjs
├── .gitignore
├── README.md
├── index.html
├── package-lock.json
├── package.json
├── public
│ └── vite.svg
├── src
│ ├── App.css
│ ├── App.jsx
│ ├── Home.jsx
│ ├── SignIn.jsx
│ ├── SignUp.jsx
│ ├── assets
│ │ └── react.svg
│ ├── index.css
│ ├── main.jsx
│ ├── network.js
│ ├── store.jsx
│ └── tokenSlice.jsx
└── vite.config.js
└── src
├── main
├── java
│ └── com
│ │ └── example
│ │ └── springboot3jwtauthentication
│ │ ├── SpringBoot3JwtAuthenticationApplication.java
│ │ ├── config
│ │ ├── PasswordConfig.java
│ │ ├── SecurityConfig.java
│ │ └── SeedDataConfig.java
│ │ ├── controllers
│ │ ├── AuthenticationController.java
│ │ └── TestController.java
│ │ ├── dto
│ │ ├── JwtAuthenticationResponse.java
│ │ ├── SignInRequest.java
│ │ └── SignUpRequest.java
│ │ ├── filters
│ │ └── JwtAuthenticationFilter.java
│ │ ├── models
│ │ ├── Role.java
│ │ └── User.java
│ │ ├── repositories
│ │ └── UserRepository.java
│ │ └── services
│ │ ├── AuthenticationService.java
│ │ ├── JwtService.java
│ │ └── UserService.java
└── resources
│ ├── META-INF
│ └── additional-spring-configuration-metadata.json
│ └── application.properties
└── test
└── java
└── com
└── example
└── springboot3jwtauthentication
└── SpringBoot3JwtAuthenticationApplicationTests.java
/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 | .env
35 |
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wazooinc/spring-boot-3-jwt-authentication/69d740dc1f0a0e3f2e6097dc5acfb341339d6762/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.3/apache-maven-3.9.3-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar
3 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2023 Wazoo Web Bytes
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”),
4 | to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
5 | and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6 |
7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 |
9 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
10 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
11 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
12 | IN THE SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Spring Boot 3 JWT Authentication
2 |
3 | This project is part of a video series on YouTube about providing JSON Web Token
4 | support for Spring Boot projects.
5 |
6 | ## YouTube Links
7 |
8 | 1. Implementing JWT Authentication in Spring Boot 3: https://youtu.be/7fAB4WS29oM
9 |
10 | ## Developer Notes
11 |
12 | The project makes use of MySQL and PHPMyAdmin Docker images for database support,
13 | so make sure you have the Docker Desktop running on your machine.
14 |
15 | - `git clone git@github.com:wazooinc/spring-boot-3-jwt-authentication.git`
16 | - `cd spring-boot-3-jwt-authentication`
17 | - Open in your favorite editor supporting Java
18 |
19 | Note that if you are using this project to start your own, then make sure to generate your own JWT
20 | secret key that's used in the `application.properties`. Instructions are provided in that file
21 | for an easy one-liner to do this.
22 |
23 | Also, the `TestController` contains some "dummy" endpoints for just helping to verify role
24 | authorization. You shouldn't need this in any of your projects. It might be handy to just
25 | use as a reference for the `@PreAuthorize` stuff.
26 |
27 | ## Running the Project
28 |
29 | - **Make sure Docker Desktop is running**
30 | - `mvnw spring-boot:run`
31 |
32 | ## References
33 |
34 | Lots of great work by the Spring Boot (and other server) communities around the interwebs. Here's a few I came across
35 | during the research phase of this video.
36 |
37 | - https://medium.com/@truongbui95/jwt-authentication-and-authorization-with-spring-boot-3-and-spring-security-6-2f90f9337421
38 | - https://github.com/osopromadze/Spring-Boot-Blog-REST-API
39 | - https://www.codejava.net/frameworks/spring-boot/spring-security-jwt-role-based-authorization
40 | - https://medium.com/spring-boot/spring-security-role-based-implementation-with-spring-boot-3-0-2d59fa5a851b
41 |
42 |
43 | ## LICENSE
44 |
45 | Copyright 2023 Wazoo Web Bytes
46 |
47 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”),
48 | to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
49 | and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
50 |
51 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
52 |
53 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
54 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
55 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
56 | IN THE SOFTWARE.
57 |
--------------------------------------------------------------------------------
/compose.yaml:
--------------------------------------------------------------------------------
1 | version: '3.8'
2 |
3 | services:
4 | database:
5 | image: mysql:latest
6 | restart: unless-stopped
7 | env_file: .env
8 | environment:
9 | MYSQL_DATABASE: '${MYSQL_DATABASE}'
10 | MYSQL_PASSWORD: '${MYSQL_PASSWORD}'
11 | MYSQL_ROOT_PASSWORD: '${MYSQL_ROOT_PASSWORD}'
12 | MYSQL_USER: '${MYSQL_USER}'
13 | ports:
14 | - "3306:3306"
15 | volumes:
16 | - db-data:/var/lib/db
17 | networks:
18 | - spring-network
19 |
20 | phpmyadmin:
21 | depends_on:
22 | - database
23 | image: phpmyadmin/phpmyadmin
24 | restart: unless-stopped
25 | ports:
26 | - "8081:80"
27 | env_file: .env
28 | environment:
29 | PMA_HOST: database
30 | MYSQL_ROOT_PASSWORD: '${MYSQL_ROOT_PASSWORD}'
31 | networks:
32 | - spring-network
33 |
34 | volumes:
35 | db-data:
36 |
37 | networks:
38 | spring-network:
39 | driver: bridge
40 |
--------------------------------------------------------------------------------
/mvnw:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # ----------------------------------------------------------------------------
3 | # Licensed to the Apache Software Foundation (ASF) under one
4 | # or more contributor license agreements. See the NOTICE file
5 | # distributed with this work for additional information
6 | # regarding copyright ownership. The ASF licenses this file
7 | # to you under the Apache License, Version 2.0 (the
8 | # "License"); you may not use this file except in compliance
9 | # with the License. You may obtain a copy of the License at
10 | #
11 | # https://www.apache.org/licenses/LICENSE-2.0
12 | #
13 | # Unless required by applicable law or agreed to in writing,
14 | # software distributed under the License is distributed on an
15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 | # KIND, either express or implied. See the License for the
17 | # specific language governing permissions and limitations
18 | # under the License.
19 | # ----------------------------------------------------------------------------
20 |
21 | # ----------------------------------------------------------------------------
22 | # Apache Maven Wrapper startup batch script, version 3.2.0
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | # e.g. to debug Maven itself, use
32 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | # ----------------------------------------------------------------------------
35 |
36 | if [ -z "$MAVEN_SKIP_RC" ] ; then
37 |
38 | if [ -f /usr/local/etc/mavenrc ] ; then
39 | . /usr/local/etc/mavenrc
40 | fi
41 |
42 | if [ -f /etc/mavenrc ] ; then
43 | . /etc/mavenrc
44 | fi
45 |
46 | if [ -f "$HOME/.mavenrc" ] ; then
47 | . "$HOME/.mavenrc"
48 | fi
49 |
50 | fi
51 |
52 | # OS specific support. $var _must_ be set to either true or false.
53 | cygwin=false;
54 | darwin=false;
55 | mingw=false
56 | case "$(uname)" in
57 | CYGWIN*) cygwin=true ;;
58 | MINGW*) mingw=true;;
59 | Darwin*) darwin=true
60 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
61 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
62 | if [ -z "$JAVA_HOME" ]; then
63 | if [ -x "/usr/libexec/java_home" ]; then
64 | JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME
65 | else
66 | JAVA_HOME="/Library/Java/Home"; export JAVA_HOME
67 | fi
68 | fi
69 | ;;
70 | esac
71 |
72 | if [ -z "$JAVA_HOME" ] ; then
73 | if [ -r /etc/gentoo-release ] ; then
74 | JAVA_HOME=$(java-config --jre-home)
75 | fi
76 | fi
77 |
78 | # For Cygwin, ensure paths are in UNIX format before anything is touched
79 | if $cygwin ; then
80 | [ -n "$JAVA_HOME" ] &&
81 | JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
82 | [ -n "$CLASSPATH" ] &&
83 | CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
84 | fi
85 |
86 | # For Mingw, ensure paths are in UNIX format before anything is touched
87 | if $mingw ; then
88 | [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] &&
89 | JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)"
90 | fi
91 |
92 | if [ -z "$JAVA_HOME" ]; then
93 | javaExecutable="$(which javac)"
94 | if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then
95 | # readlink(1) is not available as standard on Solaris 10.
96 | readLink=$(which readlink)
97 | if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then
98 | if $darwin ; then
99 | javaHome="$(dirname "\"$javaExecutable\"")"
100 | javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac"
101 | else
102 | javaExecutable="$(readlink -f "\"$javaExecutable\"")"
103 | fi
104 | javaHome="$(dirname "\"$javaExecutable\"")"
105 | javaHome=$(expr "$javaHome" : '\(.*\)/bin')
106 | JAVA_HOME="$javaHome"
107 | export JAVA_HOME
108 | fi
109 | fi
110 | fi
111 |
112 | if [ -z "$JAVACMD" ] ; then
113 | if [ -n "$JAVA_HOME" ] ; then
114 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
115 | # IBM's JDK on AIX uses strange locations for the executables
116 | JAVACMD="$JAVA_HOME/jre/sh/java"
117 | else
118 | JAVACMD="$JAVA_HOME/bin/java"
119 | fi
120 | else
121 | JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)"
122 | fi
123 | fi
124 |
125 | if [ ! -x "$JAVACMD" ] ; then
126 | echo "Error: JAVA_HOME is not defined correctly." >&2
127 | echo " We cannot execute $JAVACMD" >&2
128 | exit 1
129 | fi
130 |
131 | if [ -z "$JAVA_HOME" ] ; then
132 | echo "Warning: JAVA_HOME environment variable is not set."
133 | fi
134 |
135 | # traverses directory structure from process work directory to filesystem root
136 | # first directory with .mvn subdirectory is considered project base directory
137 | find_maven_basedir() {
138 | if [ -z "$1" ]
139 | then
140 | echo "Path not specified to find_maven_basedir"
141 | return 1
142 | fi
143 |
144 | basedir="$1"
145 | wdir="$1"
146 | while [ "$wdir" != '/' ] ; do
147 | if [ -d "$wdir"/.mvn ] ; then
148 | basedir=$wdir
149 | break
150 | fi
151 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
152 | if [ -d "${wdir}" ]; then
153 | wdir=$(cd "$wdir/.." || exit 1; pwd)
154 | fi
155 | # end of workaround
156 | done
157 | printf '%s' "$(cd "$basedir" || exit 1; pwd)"
158 | }
159 |
160 | # concatenates all lines of a file
161 | concat_lines() {
162 | if [ -f "$1" ]; then
163 | # Remove \r in case we run on Windows within Git Bash
164 | # and check out the repository with auto CRLF management
165 | # enabled. Otherwise, we may read lines that are delimited with
166 | # \r\n and produce $'-Xarg\r' rather than -Xarg due to word
167 | # splitting rules.
168 | tr -s '\r\n' ' ' < "$1"
169 | fi
170 | }
171 |
172 | log() {
173 | if [ "$MVNW_VERBOSE" = true ]; then
174 | printf '%s\n' "$1"
175 | fi
176 | }
177 |
178 | BASE_DIR=$(find_maven_basedir "$(dirname "$0")")
179 | if [ -z "$BASE_DIR" ]; then
180 | exit 1;
181 | fi
182 |
183 | MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR
184 | log "$MAVEN_PROJECTBASEDIR"
185 |
186 | ##########################################################################################
187 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
188 | # This allows using the maven wrapper in projects that prohibit checking in binary data.
189 | ##########################################################################################
190 | wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar"
191 | if [ -r "$wrapperJarPath" ]; then
192 | log "Found $wrapperJarPath"
193 | else
194 | log "Couldn't find $wrapperJarPath, downloading it ..."
195 |
196 | if [ -n "$MVNW_REPOURL" ]; then
197 | wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
198 | else
199 | wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
200 | fi
201 | while IFS="=" read -r key value; do
202 | # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' )
203 | safeValue=$(echo "$value" | tr -d '\r')
204 | case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;;
205 | esac
206 | done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
207 | log "Downloading from: $wrapperUrl"
208 |
209 | if $cygwin; then
210 | wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
211 | fi
212 |
213 | if command -v wget > /dev/null; then
214 | log "Found wget ... using wget"
215 | [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet"
216 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
217 | wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
218 | else
219 | wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
220 | fi
221 | elif command -v curl > /dev/null; then
222 | log "Found curl ... using curl"
223 | [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent"
224 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
225 | curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
226 | else
227 | curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
228 | fi
229 | else
230 | log "Falling back to using Java to download"
231 | javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java"
232 | javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class"
233 | # For Cygwin, switch paths to Windows format before running javac
234 | if $cygwin; then
235 | javaSource=$(cygpath --path --windows "$javaSource")
236 | javaClass=$(cygpath --path --windows "$javaClass")
237 | fi
238 | if [ -e "$javaSource" ]; then
239 | if [ ! -e "$javaClass" ]; then
240 | log " - Compiling MavenWrapperDownloader.java ..."
241 | ("$JAVA_HOME/bin/javac" "$javaSource")
242 | fi
243 | if [ -e "$javaClass" ]; then
244 | log " - Running MavenWrapperDownloader.java ..."
245 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath"
246 | fi
247 | fi
248 | fi
249 | fi
250 | ##########################################################################################
251 | # End of extension
252 | ##########################################################################################
253 |
254 | # If specified, validate the SHA-256 sum of the Maven wrapper jar file
255 | wrapperSha256Sum=""
256 | while IFS="=" read -r key value; do
257 | case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;;
258 | esac
259 | done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
260 | if [ -n "$wrapperSha256Sum" ]; then
261 | wrapperSha256Result=false
262 | if command -v sha256sum > /dev/null; then
263 | if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then
264 | wrapperSha256Result=true
265 | fi
266 | elif command -v shasum > /dev/null; then
267 | if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then
268 | wrapperSha256Result=true
269 | fi
270 | else
271 | echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available."
272 | echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties."
273 | exit 1
274 | fi
275 | if [ $wrapperSha256Result = false ]; then
276 | echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2
277 | echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2
278 | echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2
279 | exit 1
280 | fi
281 | fi
282 |
283 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
284 |
285 | # For Cygwin, switch paths to Windows format before running java
286 | if $cygwin; then
287 | [ -n "$JAVA_HOME" ] &&
288 | JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
289 | [ -n "$CLASSPATH" ] &&
290 | CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
291 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
292 | MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
293 | fi
294 |
295 | # Provide a "standardized" way to retrieve the CLI args that will
296 | # work with both Windows and non-Windows executions.
297 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*"
298 | export MAVEN_CMD_LINE_ARGS
299 |
300 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
301 |
302 | # shellcheck disable=SC2086 # safe args
303 | exec "$JAVACMD" \
304 | $MAVEN_OPTS \
305 | $MAVEN_DEBUG_OPTS \
306 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
307 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
308 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
309 |
--------------------------------------------------------------------------------
/mvnw.cmd:
--------------------------------------------------------------------------------
1 | @REM ----------------------------------------------------------------------------
2 | @REM Licensed to the Apache Software Foundation (ASF) under one
3 | @REM or more contributor license agreements. See the NOTICE file
4 | @REM distributed with this work for additional information
5 | @REM regarding copyright ownership. The ASF licenses this file
6 | @REM to you under the Apache License, Version 2.0 (the
7 | @REM "License"); you may not use this file except in compliance
8 | @REM with the License. You may obtain a copy of the License at
9 | @REM
10 | @REM https://www.apache.org/licenses/LICENSE-2.0
11 | @REM
12 | @REM Unless required by applicable law or agreed to in writing,
13 | @REM software distributed under the License is distributed on an
14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | @REM KIND, either express or implied. See the License for the
16 | @REM specific language governing permissions and limitations
17 | @REM under the License.
18 | @REM ----------------------------------------------------------------------------
19 |
20 | @REM ----------------------------------------------------------------------------
21 | @REM Apache Maven Wrapper startup batch script, version 3.2.0
22 | @REM
23 | @REM Required ENV vars:
24 | @REM JAVA_HOME - location of a JDK home dir
25 | @REM
26 | @REM Optional ENV vars
27 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
28 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
29 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
30 | @REM e.g. to debug Maven itself, use
31 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
32 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
33 | @REM ----------------------------------------------------------------------------
34 |
35 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
36 | @echo off
37 | @REM set title of command window
38 | title %0
39 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
40 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
41 |
42 | @REM set %HOME% to equivalent of $HOME
43 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
44 |
45 | @REM Execute a user defined script before this one
46 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
47 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
48 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
49 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
50 | :skipRcPre
51 |
52 | @setlocal
53 |
54 | set ERROR_CODE=0
55 |
56 | @REM To isolate internal variables from possible post scripts, we use another setlocal
57 | @setlocal
58 |
59 | @REM ==== START VALIDATION ====
60 | if not "%JAVA_HOME%" == "" goto OkJHome
61 |
62 | echo.
63 | echo Error: JAVA_HOME not found in your environment. >&2
64 | echo Please set the JAVA_HOME variable in your environment to match the >&2
65 | echo location of your Java installation. >&2
66 | echo.
67 | goto error
68 |
69 | :OkJHome
70 | if exist "%JAVA_HOME%\bin\java.exe" goto init
71 |
72 | echo.
73 | echo Error: JAVA_HOME is set to an invalid directory. >&2
74 | echo JAVA_HOME = "%JAVA_HOME%" >&2
75 | echo Please set the JAVA_HOME variable in your environment to match the >&2
76 | echo location of your Java installation. >&2
77 | echo.
78 | goto error
79 |
80 | @REM ==== END VALIDATION ====
81 |
82 | :init
83 |
84 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
85 | @REM Fallback to current working directory if not found.
86 |
87 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
88 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
89 |
90 | set EXEC_DIR=%CD%
91 | set WDIR=%EXEC_DIR%
92 | :findBaseDir
93 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
94 | cd ..
95 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
96 | set WDIR=%CD%
97 | goto findBaseDir
98 |
99 | :baseDirFound
100 | set MAVEN_PROJECTBASEDIR=%WDIR%
101 | cd "%EXEC_DIR%"
102 | goto endDetectBaseDir
103 |
104 | :baseDirNotFound
105 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
106 | cd "%EXEC_DIR%"
107 |
108 | :endDetectBaseDir
109 |
110 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
111 |
112 | @setlocal EnableExtensions EnableDelayedExpansion
113 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
114 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
115 |
116 | :endReadAdditionalConfig
117 |
118 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
121 |
122 | set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
123 |
124 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
125 | IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B
126 | )
127 |
128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data.
130 | if exist %WRAPPER_JAR% (
131 | if "%MVNW_VERBOSE%" == "true" (
132 | echo Found %WRAPPER_JAR%
133 | )
134 | ) else (
135 | if not "%MVNW_REPOURL%" == "" (
136 | SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
137 | )
138 | if "%MVNW_VERBOSE%" == "true" (
139 | echo Couldn't find %WRAPPER_JAR%, downloading it ...
140 | echo Downloading from: %WRAPPER_URL%
141 | )
142 |
143 | powershell -Command "&{"^
144 | "$webclient = new-object System.Net.WebClient;"^
145 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
146 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
147 | "}"^
148 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
149 | "}"
150 | if "%MVNW_VERBOSE%" == "true" (
151 | echo Finished downloading %WRAPPER_JAR%
152 | )
153 | )
154 | @REM End of extension
155 |
156 | @REM If specified, validate the SHA-256 sum of the Maven wrapper jar file
157 | SET WRAPPER_SHA_256_SUM=""
158 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
159 | IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B
160 | )
161 | IF NOT %WRAPPER_SHA_256_SUM%=="" (
162 | powershell -Command "&{"^
163 | "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^
164 | "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^
165 | " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^
166 | " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^
167 | " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^
168 | " exit 1;"^
169 | "}"^
170 | "}"
171 | if ERRORLEVEL 1 goto error
172 | )
173 |
174 | @REM Provide a "standardized" way to retrieve the CLI args that will
175 | @REM work with both Windows and non-Windows executions.
176 | set MAVEN_CMD_LINE_ARGS=%*
177 |
178 | %MAVEN_JAVA_EXE% ^
179 | %JVM_CONFIG_MAVEN_PROPS% ^
180 | %MAVEN_OPTS% ^
181 | %MAVEN_DEBUG_OPTS% ^
182 | -classpath %WRAPPER_JAR% ^
183 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
184 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
185 | if ERRORLEVEL 1 goto error
186 | goto end
187 |
188 | :error
189 | set ERROR_CODE=1
190 |
191 | :end
192 | @endlocal & set ERROR_CODE=%ERROR_CODE%
193 |
194 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
195 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
196 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
197 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
198 | :skipRcPost
199 |
200 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
201 | if "%MAVEN_BATCH_PAUSE%"=="on" pause
202 |
203 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
204 |
205 | cmd /C exit /B %ERROR_CODE%
206 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 3.1.2
9 |
10 |
11 | com.example
12 | spring-boot-3-jwt-authentication
13 | 0.0.1-SNAPSHOT
14 | spring-boot-3-jwt-authentication
15 | Demo project for Spring Boot
16 |
17 | 17
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-data-jpa
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-security
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-web
31 |
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-devtools
36 | runtime
37 | true
38 |
39 |
40 | org.springframework.boot
41 | spring-boot-docker-compose
42 | runtime
43 | true
44 |
45 |
46 | com.mysql
47 | mysql-connector-j
48 | runtime
49 |
50 |
51 | org.projectlombok
52 | lombok
53 | true
54 |
55 |
56 | io.jsonwebtoken
57 | jjwt-api
58 | 0.11.5
59 |
60 |
61 | io.jsonwebtoken
62 | jjwt-impl
63 | 0.11.5
64 |
65 |
66 | io.jsonwebtoken
67 | jjwt-jackson
68 | 0.11.5
69 |
70 |
71 | org.apache.commons
72 | commons-lang3
73 |
74 |
75 | org.springframework.boot
76 | spring-boot-starter-test
77 | test
78 |
79 |
80 | org.springframework.security
81 | spring-security-test
82 | test
83 |
84 |
85 |
86 |
87 |
88 |
89 | org.springframework.boot
90 | spring-boot-maven-plugin
91 |
92 |
93 |
94 | org.projectlombok
95 | lombok
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
--------------------------------------------------------------------------------
/react-frontend/.eslintrc.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | env: { browser: true, es2020: true },
4 | extends: [
5 | 'eslint:recommended',
6 | 'plugin:react/recommended',
7 | 'plugin:react/jsx-runtime',
8 | 'plugin:react-hooks/recommended',
9 | ],
10 | ignorePatterns: ['dist', '.eslintrc.cjs'],
11 | parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
12 | settings: { react: { version: '18.2' } },
13 | plugins: ['react-refresh'],
14 | rules: {
15 | 'react-refresh/only-export-components': [
16 | 'warn',
17 | { allowConstantExport: true },
18 | ],
19 | },
20 | }
21 |
--------------------------------------------------------------------------------
/react-frontend/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | pnpm-debug.log*
8 | lerna-debug.log*
9 |
10 | node_modules
11 | dist
12 | dist-ssr
13 | *.local
14 |
15 | # Editor directories and files
16 | .vscode/*
17 | !.vscode/extensions.json
18 | .idea
19 | .DS_Store
20 | *.suo
21 | *.ntvs*
22 | *.njsproj
23 | *.sln
24 | *.sw?
25 |
--------------------------------------------------------------------------------
/react-frontend/README.md:
--------------------------------------------------------------------------------
1 | # React + Vite
2 |
3 | This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
4 |
5 | Currently, two official plugins are available:
6 |
7 | - [@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
8 | - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
9 |
--------------------------------------------------------------------------------
/react-frontend/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Vite + React
8 |
9 |
10 |
11 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/react-frontend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "frontend-react",
3 | "private": true,
4 | "version": "0.0.0",
5 | "type": "module",
6 | "scripts": {
7 | "dev": "vite",
8 | "build": "vite build",
9 | "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
10 | "preview": "vite preview"
11 | },
12 | "dependencies": {
13 | "@reduxjs/toolkit": "^1.9.5",
14 | "react": "^18.2.0",
15 | "react-dom": "^18.2.0",
16 | "react-redux": "^8.1.2",
17 | "react-router-dom": "^6.15.0"
18 | },
19 | "devDependencies": {
20 | "@types/react": "^18.2.15",
21 | "@types/react-dom": "^18.2.7",
22 | "@vitejs/plugin-react": "^4.0.3",
23 | "eslint": "^8.45.0",
24 | "eslint-plugin-react": "^7.32.2",
25 | "eslint-plugin-react-hooks": "^4.6.0",
26 | "eslint-plugin-react-refresh": "^0.4.3",
27 | "vite": "^4.4.5"
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/react-frontend/public/vite.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/react-frontend/src/App.css:
--------------------------------------------------------------------------------
1 | #root {
2 | max-width: 1280px;
3 | margin: 0 auto;
4 | padding: 2rem;
5 | text-align: center;
6 | }
7 |
8 | .logo {
9 | height: 6em;
10 | padding: 1.5em;
11 | will-change: filter;
12 | transition: filter 300ms;
13 | }
14 | .logo:hover {
15 | filter: drop-shadow(0 0 2em #646cffaa);
16 | }
17 | .logo.react:hover {
18 | filter: drop-shadow(0 0 2em #61dafbaa);
19 | }
20 |
21 | @keyframes logo-spin {
22 | from {
23 | transform: rotate(0deg);
24 | }
25 | to {
26 | transform: rotate(360deg);
27 | }
28 | }
29 |
30 | @media (prefers-reduced-motion: no-preference) {
31 | a:nth-of-type(2) .logo {
32 | animation: logo-spin infinite 20s linear;
33 | }
34 | }
35 |
36 | .card {
37 | padding: 2em;
38 | }
39 |
40 | .read-the-docs {
41 | color: #888;
42 | }
43 |
--------------------------------------------------------------------------------
/react-frontend/src/App.jsx:
--------------------------------------------------------------------------------
1 | import { useState } from 'react'
2 | import reactLogo from './assets/react.svg'
3 | import viteLogo from '/vite.svg'
4 | import './App.css'
5 |
6 | function App() {
7 | const [count, setCount] = useState(0)
8 |
9 | return (
10 | <>
11 |
19 | Vite + React
20 |
21 |
24 |
25 | Edit src/App.jsx
and save to test HMR
26 |
27 |
28 |
29 | Click on the Vite and React logos to learn more
30 |
31 | >
32 | )
33 | }
34 |
35 | export default App
36 |
--------------------------------------------------------------------------------
/react-frontend/src/Home.jsx:
--------------------------------------------------------------------------------
1 | import { useState } from 'react'
2 | import { Link } from 'react-router-dom'
3 | import { useSelector } from 'react-redux'
4 | import { getFetch } from './network'
5 |
6 | const Home = () => {
7 | const token = useSelector((state) => state.token.value)
8 | const [testType, setTestType] = useState('anon')
9 | const [result, setResult] = useState('')
10 |
11 | const handleSubmit = async (e) => {
12 | e.preventDefault()
13 | //const baseURL = '/api/v1/test'
14 | //console.log('form submit')
15 | //console.log(testType)
16 |
17 | getFetch(`/test/${testType}`, token)
18 | .then(res => {
19 | console.log('res', res)
20 | setResult(res)
21 | })
22 | .catch(err => {
23 | console.error(err)
24 | if (err.message) {
25 | setResult(err.message)
26 | }
27 | })
28 |
29 |
30 |
31 | /*
32 |
33 | const headers = {
34 | 'Content-type': 'application/json',
35 | Authorization: `Bearer ${token}`
36 | }
37 |
38 | fetch(`${baseURL}/${testType}`, {
39 | method: 'GET',
40 | headers: headers
41 | })
42 | .then(response => response.text())
43 | .then(text => {
44 | console.log(text)
45 | setTestResult(text)
46 | })
47 | .catch(err => {
48 | if (err.message) {
49 | setTestResult(err.message)
50 | }
51 | })*/
52 |
53 | }
54 |
55 |
56 | return (
57 |
58 |
React JWT Authentication Tester
59 |
60 |
61 | -
62 | Sign In
63 |
64 | -
65 | Sign Up
66 |
67 |
68 |
69 |
70 |
JWT Token
71 |
72 | Token: {token}
73 |
74 |
75 |
76 |
Testing Links
77 |
85 |
86 |
87 |
Testing Result
88 |
89 |
90 | {result}
91 |
92 |
93 |
94 |
95 | )
96 | }
97 |
98 | export default Home
--------------------------------------------------------------------------------
/react-frontend/src/SignIn.jsx:
--------------------------------------------------------------------------------
1 | import { useState } from 'react'
2 | import { Link } from 'react-router-dom'
3 | import { useSelector, useDispatch } from 'react-redux'
4 | import { setter } from './tokenSlice'
5 | import { postFetch } from './network'
6 |
7 | const SignIn = () => {
8 | const token = useSelector((state) => state.token.value)
9 | const dispatch = useDispatch()
10 |
11 | const [email, setEmail] = useState('')
12 | const [password, setPassword] = useState('')
13 | const [result, setResult] = useState('')
14 |
15 | const handleSubmit = async (e) => {
16 | e.preventDefault()
17 | //const baseURL = '/api/v1'
18 |
19 | const payload = {
20 | email: email,
21 | password: password
22 | }
23 |
24 | const res = await postFetch('/signin', payload)
25 | .catch(err => {
26 | console.log(err)
27 | if (err.message) {
28 | setResult(err.message)
29 | }
30 | })
31 |
32 | if (res?.token) {
33 | dispatch(setter(res.token))
34 | setResult(`token: ${res.token}`)
35 | }
36 |
37 | /*
38 | fetch(`${baseURL}/signin`, {
39 | method: 'POST',
40 | body: JSON.stringify(payload),
41 | headers: {'Content-type': 'application/json'}
42 | })
43 | .then(response => response.json())
44 | .then(json => {
45 | console.log(json)
46 | if (json?.data?.token) {
47 | dispatch(setter(json.data.token))
48 | setResult(`token: ${json.data.token}`)
49 | }
50 |
51 | })
52 | .catch(err => {
53 | console.log(err)
54 | if (err.message) {
55 | setResult(err.message)
56 | }
57 | })*/
58 |
59 | }
60 |
61 | return (
62 |
63 |
Sign In
64 |
70 |
Result
71 |
{result}
72 |
73 |
Token
74 |
75 |
Home
76 |
77 | )
78 | }
79 |
80 | export default SignIn
--------------------------------------------------------------------------------
/react-frontend/src/SignUp.jsx:
--------------------------------------------------------------------------------
1 | import { useState } from 'react'
2 | import { Link } from 'react-router-dom'
3 | import { useSelector, useDispatch } from 'react-redux'
4 | import { setter } from './tokenSlice'
5 |
6 | const SignUp = () => {
7 | const token = useSelector((state) => state.token.value)
8 | const dispatch = useDispatch()
9 | const [firstName, setFirstName] = useState('')
10 | const [lastName, setLastName] = useState('')
11 | const [email, setEmail] = useState('')
12 | const [password, setPassword] = useState('')
13 | const [result, setResult] = useState('')
14 |
15 | const handleSubmit = async (e) => {
16 | e.preventDefault()
17 | //const baseURL = '/api/v1'
18 |
19 | const payload = {
20 | firstName: firstName,
21 | lastName: lastName,
22 | email: email,
23 | password: password
24 | }
25 |
26 | const res = await postFetch('/signup', payload)
27 | .catch(err => {
28 | console.log(err)
29 | if (err.message) {
30 | setResult(err.message)
31 | }
32 | })
33 | console.log('res', res)
34 |
35 |
36 | /*
37 | fetch(`${baseURL}/signup`, {
38 | method: 'POST',
39 | body: JSON.stringify(payload),
40 | headers: {'Content-type': 'application/json'}
41 | })
42 | .then(response => response.json())
43 | .then(json => {
44 | console.log(json)
45 | if (json?.data?.token) {
46 | dispatch(setter(json.data.token))
47 | setResult(`token: ${json.data.token}`)
48 | }
49 | })
50 | .catch(err => {
51 | console.log(err)
52 | if (err.message) {
53 | setResult(err.message)
54 | }
55 | })*/
56 |
57 | }
58 |
59 | return (
60 |
61 |
Sign Up!
62 |
70 |
Result
71 |
{result}
72 |
73 |
Token
74 |
75 |
Home
76 |
77 | )
78 | }
79 |
80 | export default SignUp
--------------------------------------------------------------------------------
/react-frontend/src/assets/react.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/react-frontend/src/index.css:
--------------------------------------------------------------------------------
1 |
2 | div.spacer {
3 | margin-top: 20px;
4 | margin-bottom: 20px;
5 | }
6 |
7 | /*
8 |
9 | :root {
10 | font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
11 | line-height: 1.5;
12 | font-weight: 400;
13 |
14 | color-scheme: light dark;
15 | color: rgba(255, 255, 255, 0.87);
16 | background-color: #242424;
17 |
18 | font-synthesis: none;
19 | text-rendering: optimizeLegibility;
20 | -webkit-font-smoothing: antialiased;
21 | -moz-osx-font-smoothing: grayscale;
22 | -webkit-text-size-adjust: 100%;
23 | }
24 |
25 | a {
26 | font-weight: 500;
27 | color: #646cff;
28 | text-decoration: inherit;
29 | }
30 | a:hover {
31 | color: #535bf2;
32 | }
33 |
34 | body {
35 | margin: 0;
36 | display: flex;
37 | place-items: center;
38 | min-width: 320px;
39 | min-height: 100vh;
40 | }
41 |
42 | h1 {
43 | font-size: 3.2em;
44 | line-height: 1.1;
45 | }
46 |
47 | button {
48 | border-radius: 8px;
49 | border: 1px solid transparent;
50 | padding: 0.6em 1.2em;
51 | font-size: 1em;
52 | font-weight: 500;
53 | font-family: inherit;
54 | background-color: #1a1a1a;
55 | cursor: pointer;
56 | transition: border-color 0.25s;
57 | }
58 | button:hover {
59 | border-color: #646cff;
60 | }
61 | button:focus,
62 | button:focus-visible {
63 | outline: 4px auto -webkit-focus-ring-color;
64 | }
65 |
66 | @media (prefers-color-scheme: light) {
67 | :root {
68 | color: #213547;
69 | background-color: #ffffff;
70 | }
71 | a:hover {
72 | color: #747bff;
73 | }
74 | button {
75 | background-color: #f9f9f9;
76 | }
77 | }
78 | */
--------------------------------------------------------------------------------
/react-frontend/src/main.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom/client'
3 | import './index.css'
4 | import {
5 | BrowserRouter, Routes, Route
6 | } from 'react-router-dom'
7 | import SignIn from './SignIn'
8 | import SignUp from './SignUp'
9 | import Home from './Home'
10 |
11 | import {Provider} from 'react-redux'
12 | import store from './store'
13 |
14 | ReactDOM.createRoot(document.getElementById('root')).render(
15 |
16 |
17 |
18 |
19 | } />
20 | } />
21 | } />
22 |
23 |
24 |
25 | ,
26 | )
27 |
--------------------------------------------------------------------------------
/react-frontend/src/network.js:
--------------------------------------------------------------------------------
1 |
2 | const baseURL = '/api/v1'
3 |
4 | export const getFetch = async (url, token = '') => {
5 | let headers = {}
6 | console.log(url)
7 | console.log(`${baseURL}${url}`)
8 |
9 | if (token !== '') {
10 | headers.Authorization = `Bearer ${token}`
11 | }
12 |
13 | return fetch(`${baseURL}${url}`, {
14 | method: 'GET',
15 | headers: headers
16 | })
17 | .then(response => {
18 | if (response.ok) {
19 | return response.text()
20 | } else {
21 | if (response.status === 403) {
22 | return Promise.reject(new Error('invalid credentials and/or access level'))
23 | }
24 |
25 | }
26 | })
27 | }
28 |
29 | export const postFetch = async (url, payload = {}, token = '') => {
30 |
31 | const headers = {
32 | 'Content-type': 'application/json'
33 | }
34 |
35 | if (token !== '') {
36 | headers.Authorization = `Bearer ${token}`
37 | }
38 |
39 | return fetch(`${baseURL}/${url}`, {
40 | method: 'POST',
41 | body: JSON.stringify(payload),
42 | headers: headers
43 | })
44 | .then(response => {
45 | if (response.ok) {
46 | return response.json()
47 | } else {
48 | if (response.status === 403) {
49 | return Promise.reject(new Error('invalid credentials and/or access level'))
50 | }
51 | }
52 | })
53 | //.catch(err => {
54 | // return Promise.reject(new Error(err))
55 | // })
56 |
57 | /*
58 | .then(response => response.json())
59 | .then(json => {
60 | if (json?.data?.token) {
61 | dispatch(setter(json.data.token))
62 | //setResult(`token: ${json.data.token}`)
63 | }
64 | //return json
65 | })
66 | return res*/
67 | }
--------------------------------------------------------------------------------
/react-frontend/src/store.jsx:
--------------------------------------------------------------------------------
1 | import { configureStore } from '@reduxjs/toolkit'
2 | import tokenReducer from './tokenSlice'
3 |
4 | export default configureStore({
5 | reducer: {
6 | token: tokenReducer,
7 | },
8 |
9 | })
--------------------------------------------------------------------------------
/react-frontend/src/tokenSlice.jsx:
--------------------------------------------------------------------------------
1 | import { createSlice } from '@reduxjs/toolkit'
2 |
3 | export const tokenSlice = createSlice({
4 | name: 'token',
5 | initialState: {
6 | value: '',
7 | },
8 | reducers: {
9 | setter: (state, action) => {
10 | // Redux Toolkit allows us to write "mutating" logic in reducers. It
11 | // doesn't actually mutate the state because it uses the Immer library,
12 | // which detects changes to a "draft state" and produces a brand new
13 | // immutable state based off those changes.
14 | // Also, no return statement is required from these functions.
15 | state.value = action.payload
16 | }
17 | },
18 | })
19 |
20 | // Action creators are generated for each case reducer function
21 | export const { setter } = tokenSlice.actions
22 |
23 | export default tokenSlice.reducer
--------------------------------------------------------------------------------
/react-frontend/vite.config.js:
--------------------------------------------------------------------------------
1 | import { defineConfig } from 'vite'
2 | import react from '@vitejs/plugin-react'
3 |
4 | // https://vitejs.dev/config/
5 | export default defineConfig({
6 | plugins: [react()],
7 | server: {
8 | proxy: {
9 | '/api': {
10 | target: 'http://localhost:8080',
11 | changeOrigin: true
12 | }
13 | }
14 | }
15 | })
16 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/SpringBoot3JwtAuthenticationApplication.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringBoot3JwtAuthenticationApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringBoot3JwtAuthenticationApplication.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/config/PasswordConfig.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
6 | import org.springframework.security.crypto.password.PasswordEncoder;
7 |
8 | @Configuration
9 | public class PasswordConfig {
10 |
11 | @Bean
12 | public PasswordEncoder passwordEncoder() {
13 | return new BCryptPasswordEncoder();
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/config/SecurityConfig.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.http.HttpMethod;
6 | import org.springframework.security.authentication.AuthenticationManager;
7 | import org.springframework.security.authentication.AuthenticationProvider;
8 | import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
9 | import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
10 | import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
11 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
12 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
13 | import org.springframework.security.config.http.SessionCreationPolicy;
14 | import org.springframework.security.crypto.password.PasswordEncoder;
15 | import org.springframework.security.web.SecurityFilterChain;
16 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
17 |
18 | import com.example.springboot3jwtauthentication.filters.JwtAuthenticationFilter;
19 | import com.example.springboot3jwtauthentication.services.UserService;
20 |
21 | import lombok.RequiredArgsConstructor;
22 |
23 | @Configuration
24 | @EnableWebSecurity
25 | @EnableMethodSecurity
26 | @RequiredArgsConstructor
27 | public class SecurityConfig {
28 |
29 | private final JwtAuthenticationFilter jwtAuthenticationFilter;
30 | private final UserService userService;
31 | private final PasswordEncoder passwordEncoder;
32 |
33 | @Bean
34 | public AuthenticationProvider authenticationProvider() {
35 | DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
36 | authProvider.setUserDetailsService(userService.userDetailsService());
37 | authProvider.setPasswordEncoder(passwordEncoder);
38 | return authProvider;
39 | }
40 |
41 | @Bean
42 | public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
43 | return config.getAuthenticationManager();
44 | }
45 |
46 | @Bean
47 | public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
48 | http
49 | .csrf(csrf -> csrf
50 | .disable()
51 | )
52 | .sessionManagement(session -> session
53 | .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
54 | )
55 | .authorizeHttpRequests(authorize -> authorize
56 | .requestMatchers(HttpMethod.POST, "/api/v1/signup", "/api/v1/signin").permitAll()
57 | .requestMatchers(HttpMethod.GET, "/api/v1/test/**").permitAll()
58 | .anyRequest().authenticated()
59 | )
60 | .authenticationProvider(authenticationProvider()).addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
61 |
62 | return http.build();
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/config/SeedDataConfig.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.config;
2 |
3 | import org.springframework.boot.CommandLineRunner;
4 | import org.springframework.security.crypto.password.PasswordEncoder;
5 | import org.springframework.stereotype.Component;
6 |
7 | import com.example.springboot3jwtauthentication.models.Role;
8 | import com.example.springboot3jwtauthentication.models.User;
9 | import com.example.springboot3jwtauthentication.repositories.UserRepository;
10 | import com.example.springboot3jwtauthentication.services.UserService;
11 |
12 | import lombok.RequiredArgsConstructor;
13 | import lombok.extern.slf4j.Slf4j;
14 |
15 | @Component
16 | @RequiredArgsConstructor
17 | @Slf4j
18 | public class SeedDataConfig implements CommandLineRunner {
19 |
20 | private final UserRepository userRepository;
21 | private final PasswordEncoder passwordEncoder;
22 | private final UserService userService;
23 |
24 | @Override
25 | public void run(String... args) throws Exception {
26 |
27 | if (userRepository.count() == 0) {
28 |
29 | User admin = User
30 | .builder()
31 | .firstName("admin")
32 | .lastName("admin")
33 | .email("admin@admin.com")
34 | .password(passwordEncoder.encode("password"))
35 | .role(Role.ROLE_ADMIN)
36 | .build();
37 |
38 | userService.save(admin);
39 | log.debug("created ADMIN user - {}", admin);
40 | }
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/controllers/AuthenticationController.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.controllers;
2 |
3 | import org.springframework.web.bind.annotation.PostMapping;
4 | import org.springframework.web.bind.annotation.RequestBody;
5 | import org.springframework.web.bind.annotation.RequestMapping;
6 | import org.springframework.web.bind.annotation.RestController;
7 |
8 | import com.example.springboot3jwtauthentication.dto.JwtAuthenticationResponse;
9 | import com.example.springboot3jwtauthentication.dto.SignInRequest;
10 | import com.example.springboot3jwtauthentication.dto.SignUpRequest;
11 | import com.example.springboot3jwtauthentication.services.AuthenticationService;
12 |
13 | import lombok.RequiredArgsConstructor;
14 |
15 | @RestController
16 | @RequestMapping("/api/v1")
17 | @RequiredArgsConstructor
18 | public class AuthenticationController {
19 |
20 | private final AuthenticationService authenticationService;
21 |
22 | @PostMapping("/signup")
23 | public JwtAuthenticationResponse signup(@RequestBody SignUpRequest request) {
24 | return authenticationService.signup(request);
25 | }
26 |
27 | @PostMapping("/signin")
28 | public JwtAuthenticationResponse signin(@RequestBody SignInRequest request) {
29 | return authenticationService.signin(request);
30 | }
31 | }
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/controllers/TestController.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.controllers;
2 |
3 | import org.springframework.security.access.prepost.PreAuthorize;
4 | import org.springframework.web.bind.annotation.GetMapping;
5 | import org.springframework.web.bind.annotation.RequestMapping;
6 | import org.springframework.web.bind.annotation.RestController;
7 |
8 |
9 | @RestController
10 | @RequestMapping("/api/v1/test")
11 | public class TestController {
12 |
13 | @GetMapping("/anon")
14 | public String anonEndPoint() {
15 | return "everyone can see this";
16 | }
17 |
18 | @GetMapping("/users")
19 | @PreAuthorize("hasRole('USER')")
20 | public String usersEndPoint() {
21 | return "ONLY users can see this";
22 | }
23 |
24 | @GetMapping("/admins")
25 | @PreAuthorize("hasRole('ADMIN')")
26 | public String adminsEndPoint() {
27 | return "ONLY admins can see this";
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/dto/JwtAuthenticationResponse.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Builder;
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 |
8 | @Data
9 | @Builder
10 | @NoArgsConstructor
11 | @AllArgsConstructor
12 | public class JwtAuthenticationResponse {
13 | String token;
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/dto/SignInRequest.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Builder;
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 |
8 | @Data
9 | @Builder
10 | @NoArgsConstructor
11 | @AllArgsConstructor
12 | public class SignInRequest {
13 | String email;
14 | String password;
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/dto/SignUpRequest.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Builder;
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 |
8 | @Data
9 | @Builder
10 | @NoArgsConstructor
11 | @AllArgsConstructor
12 | public class SignUpRequest {
13 | String firstName;
14 | String lastName;
15 | String email;
16 | String password;
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/filters/JwtAuthenticationFilter.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.filters;
2 |
3 | import java.io.IOException;
4 |
5 | import org.apache.commons.lang3.StringUtils;
6 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
7 | import org.springframework.security.core.context.SecurityContext;
8 | import org.springframework.security.core.context.SecurityContextHolder;
9 | import org.springframework.security.core.userdetails.UserDetails;
10 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
11 | import org.springframework.stereotype.Component;
12 | import org.springframework.web.filter.OncePerRequestFilter;
13 |
14 | import com.example.springboot3jwtauthentication.services.JwtService;
15 | import com.example.springboot3jwtauthentication.services.UserService;
16 |
17 | import jakarta.servlet.FilterChain;
18 | import jakarta.servlet.ServletException;
19 | import jakarta.servlet.http.HttpServletRequest;
20 | import jakarta.servlet.http.HttpServletResponse;
21 | import lombok.RequiredArgsConstructor;
22 | import lombok.extern.slf4j.Slf4j;
23 |
24 | @Component
25 | @RequiredArgsConstructor
26 | @Slf4j
27 | public class JwtAuthenticationFilter extends OncePerRequestFilter {
28 |
29 | private final JwtService jwtService;
30 | private final UserService userService;
31 |
32 | @Override
33 | protected void doFilterInternal(HttpServletRequest request,
34 | HttpServletResponse response,
35 | FilterChain filterChain)
36 | throws ServletException, IOException {
37 | final String authHeader = request.getHeader("Authorization");
38 | final String jwt;
39 | final String userEmail;
40 | if (StringUtils.isEmpty(authHeader) || !StringUtils.startsWith(authHeader, "Bearer ")) {
41 | filterChain.doFilter(request, response);
42 | return;
43 | }
44 | jwt = authHeader.substring(7);
45 | log.debug("JWT - {}", jwt.toString());
46 | userEmail = jwtService.extractUserName(jwt);
47 | if (StringUtils.isNotEmpty(userEmail) && SecurityContextHolder.getContext().getAuthentication() == null) {
48 | UserDetails userDetails = userService.userDetailsService().loadUserByUsername(userEmail);
49 | if (jwtService.isTokenValid(jwt, userDetails)) {
50 | log.debug("User - {}", userDetails);
51 | SecurityContext context = SecurityContextHolder.createEmptyContext();
52 | UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
53 | userDetails, null, userDetails.getAuthorities());
54 | authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
55 | context.setAuthentication(authToken);
56 | SecurityContextHolder.setContext(context);
57 | }
58 | }
59 | filterChain.doFilter(request, response);
60 | }
61 | }
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/models/Role.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.models;
2 |
3 | public enum Role {
4 | ROLE_ADMIN,
5 | ROLE_USER
6 | }
7 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/models/User.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.models;
2 |
3 | import java.time.LocalDateTime;
4 | import java.util.Collection;
5 | import java.util.List;
6 |
7 | import org.springframework.security.core.GrantedAuthority;
8 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
9 | import org.springframework.security.core.userdetails.UserDetails;
10 |
11 | import jakarta.persistence.Column;
12 | import jakarta.persistence.Entity;
13 | import jakarta.persistence.EnumType;
14 | import jakarta.persistence.Enumerated;
15 | import jakarta.persistence.GeneratedValue;
16 | import jakarta.persistence.GenerationType;
17 | import jakarta.persistence.Id;
18 | import jakarta.persistence.Table;
19 | import lombok.AllArgsConstructor;
20 | import lombok.Builder;
21 | import lombok.Data;
22 | import lombok.NoArgsConstructor;
23 | import lombok.ToString;
24 |
25 | @Data
26 | @Builder
27 | @NoArgsConstructor
28 | @AllArgsConstructor
29 | @Entity
30 | @ToString
31 | @Table(name = "users")
32 | public class User implements UserDetails {
33 |
34 | @Id
35 | @GeneratedValue(strategy = GenerationType.IDENTITY)
36 | Long id;
37 |
38 | String firstName;
39 |
40 | String lastName;
41 |
42 | @Column(unique = true)
43 | String email;
44 |
45 | String password;
46 |
47 | @Enumerated(EnumType.STRING)
48 | Role role;
49 |
50 | LocalDateTime createdAt;
51 |
52 | LocalDateTime updatedAt;
53 |
54 | @Override
55 | public Collection extends GrantedAuthority> getAuthorities() {
56 | return List.of(new SimpleGrantedAuthority(role.name()));
57 | }
58 |
59 | @Override
60 | public String getUsername() {
61 | // our "username" for security is the email field
62 | return email;
63 | }
64 |
65 | @Override
66 | public boolean isAccountNonExpired() {
67 | return true;
68 | }
69 |
70 | @Override
71 | public boolean isAccountNonLocked() {
72 | return true;
73 | }
74 |
75 | @Override
76 | public boolean isCredentialsNonExpired() {
77 | return true;
78 | }
79 |
80 | @Override
81 | public boolean isEnabled() {
82 | return true;
83 | }
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/repositories/UserRepository.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.repositories;
2 |
3 | import java.util.Optional;
4 | import org.springframework.data.jpa.repository.JpaRepository;
5 | import com.example.springboot3jwtauthentication.models.User;
6 |
7 | public interface UserRepository extends JpaRepository {
8 |
9 | Optional findByEmail(String email);
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/services/AuthenticationService.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.services;
2 |
3 | import org.springframework.security.authentication.AuthenticationManager;
4 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
5 | import org.springframework.security.crypto.password.PasswordEncoder;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.example.springboot3jwtauthentication.dto.JwtAuthenticationResponse;
9 | import com.example.springboot3jwtauthentication.dto.SignInRequest;
10 | import com.example.springboot3jwtauthentication.dto.SignUpRequest;
11 | import com.example.springboot3jwtauthentication.models.Role;
12 | import com.example.springboot3jwtauthentication.models.User;
13 | import com.example.springboot3jwtauthentication.repositories.UserRepository;
14 |
15 | import lombok.RequiredArgsConstructor;
16 |
17 | @Service
18 | @RequiredArgsConstructor
19 | public class AuthenticationService {
20 |
21 | private final UserRepository userRepository;
22 | private final UserService userService;
23 | private final PasswordEncoder passwordEncoder;
24 | private final JwtService jwtService;
25 | private final AuthenticationManager authenticationManager;
26 |
27 | public JwtAuthenticationResponse signup(SignUpRequest request) {
28 | var user = User
29 | .builder()
30 | .firstName(request.getFirstName())
31 | .lastName(request.getLastName())
32 | .email(request.getEmail())
33 | .password(passwordEncoder.encode(request.getPassword()))
34 | .role(Role.ROLE_USER)
35 | .build();
36 |
37 | user = userService.save(user);
38 | var jwt = jwtService.generateToken(user);
39 | return JwtAuthenticationResponse.builder().token(jwt).build();
40 | }
41 |
42 |
43 | public JwtAuthenticationResponse signin(SignInRequest request) {
44 | authenticationManager.authenticate(
45 | new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
46 | var user = userRepository.findByEmail(request.getEmail())
47 | .orElseThrow(() -> new IllegalArgumentException("Invalid email or password."));
48 | var jwt = jwtService.generateToken(user);
49 | return JwtAuthenticationResponse.builder().token(jwt).build();
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/services/JwtService.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.services;
2 |
3 | import java.security.Key;
4 | import java.util.Date;
5 | import java.util.HashMap;
6 | import java.util.Map;
7 | import java.util.function.Function;
8 |
9 | import org.springframework.beans.factory.annotation.Value;
10 | import org.springframework.security.core.userdetails.UserDetails;
11 | import org.springframework.stereotype.Service;
12 |
13 | import io.jsonwebtoken.Claims;
14 | import io.jsonwebtoken.Jwts;
15 | import io.jsonwebtoken.SignatureAlgorithm;
16 | import io.jsonwebtoken.io.Decoders;
17 | import io.jsonwebtoken.security.Keys;
18 |
19 | @Service
20 | public class JwtService {
21 |
22 | @Value("${token.secret.key}")
23 | String jwtSecretKey;
24 |
25 | @Value("${token.expirationms}")
26 | Long jwtExpirationMs;
27 |
28 | public String extractUserName(String token) {
29 | return extractClaim(token, Claims::getSubject);
30 | }
31 |
32 | public String generateToken(UserDetails userDetails) {
33 | return generateToken(new HashMap<>(), userDetails);
34 | }
35 |
36 | public boolean isTokenValid(String token, UserDetails userDetails) {
37 | final String userName = extractUserName(token);
38 | return (userName.equals(userDetails.getUsername())) && !isTokenExpired(token);
39 | }
40 |
41 | private T extractClaim(String token, Function claimsResolvers) {
42 | final Claims claims = extractAllClaims(token);
43 | return claimsResolvers.apply(claims);
44 | }
45 |
46 | private String generateToken(Map extraClaims, UserDetails userDetails) {
47 | return Jwts
48 | .builder()
49 | .setClaims(extraClaims)
50 | .setSubject(userDetails.getUsername())
51 | .setIssuedAt(new Date(System.currentTimeMillis()))
52 | .setExpiration(new Date(System.currentTimeMillis() + jwtExpirationMs))
53 | .signWith(getSigningKey(), SignatureAlgorithm.HS256)
54 | .compact();
55 | }
56 |
57 | private boolean isTokenExpired(String token) {
58 | return extractExpiration(token).before(new Date());
59 | }
60 |
61 | private Date extractExpiration(String token) {
62 | return extractClaim(token, Claims::getExpiration);
63 | }
64 |
65 | private Claims extractAllClaims(String token) {
66 | return Jwts
67 | .parserBuilder()
68 | .setSigningKey(getSigningKey())
69 | .build()
70 | .parseClaimsJws(token)
71 | .getBody();
72 | }
73 |
74 | private Key getSigningKey() {
75 | byte[] keyBytes = Decoders.BASE64.decode(jwtSecretKey);
76 | return Keys.hmacShaKeyFor(keyBytes);
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/java/com/example/springboot3jwtauthentication/services/UserService.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication.services;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import org.springframework.security.core.userdetails.UserDetails;
6 | import org.springframework.security.core.userdetails.UserDetailsService;
7 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
8 | import org.springframework.stereotype.Service;
9 |
10 | import com.example.springboot3jwtauthentication.models.User;
11 | import com.example.springboot3jwtauthentication.repositories.UserRepository;
12 |
13 | import lombok.RequiredArgsConstructor;
14 |
15 | @Service
16 | @RequiredArgsConstructor
17 | public class UserService {
18 |
19 | private final UserRepository userRepository;
20 |
21 | public UserDetailsService userDetailsService() {
22 | return new UserDetailsService() {
23 | @Override
24 | public UserDetails loadUserByUsername(String username) {
25 | return userRepository.findByEmail(username)
26 | .orElseThrow(() -> new UsernameNotFoundException("User not found"));
27 | }
28 | };
29 | }
30 |
31 | public User save(User newUser) {
32 | if (newUser.getId() == null) {
33 | newUser.setCreatedAt(LocalDateTime.now());
34 | }
35 |
36 | newUser.setUpdatedAt(LocalDateTime.now());
37 | return userRepository.save(newUser);
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/resources/META-INF/additional-spring-configuration-metadata.json:
--------------------------------------------------------------------------------
1 | {"properties": [
2 | {
3 | "name": "token.secret.key",
4 | "type": "java.lang.String",
5 | "description": "A description for 'token.secret.key'"
6 | },
7 | {
8 | "name": "token.expirationms",
9 | "type": "java.lang.String",
10 | "description": "A description for 'token.expirationms'"
11 | }
12 | ]}
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 |
2 | # define our server port
3 | server.port=8080
4 |
5 | logging.level.root=WARN
6 | logging.level.web=INFO
7 | logging.level.com.example=DEBUG
8 |
9 | # generate the hibernate entities
10 | spring.jpa.generate-ddl=true
11 |
12 | # JWT secret key
13 | # node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
14 | token.secret.key=48a868a4042f634ac04a117f00a87202131dd7c46c4b32c4acb3edc5e15f4511
15 |
16 | # JWT expiration is 1 hour
17 | token.expirationms=3600000
--------------------------------------------------------------------------------
/src/test/java/com/example/springboot3jwtauthentication/SpringBoot3JwtAuthenticationApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.example.springboot3jwtauthentication;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class SpringBoot3JwtAuthenticationApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------