├── .classpath
├── .gitignore
├── .project
├── .settings
├── org.eclipse.core.resources.prefs
├── org.eclipse.jdt.core.prefs
├── org.eclipse.m2e.core.prefs
└── org.eclipse.wst.common.project.facet.core.xml
├── .springBeans
├── LICENSE
├── README.md
├── mvnw
├── mvnw.cmd
├── pom.xml
├── src
├── main
│ ├── java
│ │ └── com
│ │ │ └── thomasvitale
│ │ │ ├── Application.java
│ │ │ ├── config
│ │ │ └── WebSecurityConfig.java
│ │ │ ├── controller
│ │ │ ├── HelloController.java
│ │ │ └── QuoteController.java
│ │ │ ├── model
│ │ │ ├── Account.java
│ │ │ └── Quote.java
│ │ │ ├── repository
│ │ │ ├── QuoteRepository.java
│ │ │ └── QuoteRepositoryImpl.java
│ │ │ ├── security
│ │ │ ├── JWTAuthenticationEntryPoint.java
│ │ │ ├── JWTAuthenticationFilter.java
│ │ │ ├── JWTLoginFilter.java
│ │ │ ├── TokenHandler.java
│ │ │ ├── repository
│ │ │ │ ├── AccountRepository.java
│ │ │ │ └── AccountRepositoryImpl.java
│ │ │ └── service
│ │ │ │ ├── AccountService.java
│ │ │ │ ├── TokenAuthenticationService.java
│ │ │ │ └── TokenAuthenticationServiceImpl.java
│ │ │ └── service
│ │ │ ├── QuoteService.java
│ │ │ └── QuoteServiceImpl.java
│ └── resources
│ │ └── application.properties
└── test
│ └── java
│ └── com
│ └── thomasvitale
│ └── DemoApplicationTests.java
└── target
├── classes
├── META-INF
│ ├── MANIFEST.MF
│ └── maven
│ │ └── com.thomasvitale
│ │ └── spring-security-jwt-rest-demo
│ │ ├── pom.properties
│ │ └── pom.xml
├── application.properties
└── com
│ └── thomasvitale
│ ├── Application.class
│ ├── config
│ └── WebSecurityConfig.class
│ ├── controller
│ ├── HelloController.class
│ └── QuoteController.class
│ ├── model
│ ├── Account.class
│ └── Quote.class
│ ├── repository
│ ├── QuoteRepository.class
│ └── QuoteRepositoryImpl.class
│ ├── security
│ ├── JWTAuthenticationEntryPoint.class
│ ├── JWTAuthenticationFilter.class
│ ├── JWTLoginFilter.class
│ ├── TokenHandler.class
│ ├── repository
│ │ ├── AccountRepository.class
│ │ └── AccountRepositoryImpl.class
│ └── service
│ │ ├── AccountService.class
│ │ ├── TokenAuthenticationService.class
│ │ └── TokenAuthenticationServiceImpl.class
│ └── service
│ ├── QuoteService.class
│ └── QuoteServiceImpl.class
└── test-classes
└── com
└── thomasvitale
└── DemoApplicationTests.class
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /build/
2 | .DS_STORE
3 | .DS_Store
4 | .idea/
5 | lib/
6 | Tomcat.xml
7 | /Tomcat.xml
8 | /bin/
9 | /target/
10 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | spring-security-jwt-rest
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.wst.common.project.facet.core.builder
10 |
11 |
12 |
13 |
14 | org.eclipse.jdt.core.javabuilder
15 |
16 |
17 |
18 |
19 | org.eclipse.m2e.core.maven2Builder
20 |
21 |
22 |
23 |
24 | org.springframework.ide.eclipse.core.springbuilder
25 |
26 |
27 |
28 |
29 |
30 | org.springframework.ide.eclipse.core.springnature
31 | org.eclipse.jdt.core.javanature
32 | org.eclipse.m2e.core.maven2Nature
33 | org.eclipse.wst.common.project.facet.core.nature
34 |
35 |
36 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding//src/main/java=UTF-8
3 | encoding//src/main/resources=UTF-8
4 | encoding//src/test/java=UTF-8
5 | encoding/=UTF-8
6 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
3 | org.eclipse.jdt.core.compiler.compliance=1.8
4 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
5 | org.eclipse.jdt.core.compiler.source=1.8
6 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | activeProfiles=
2 | eclipse.preferences.version=1
3 | resolveWorkspaceProjects=true
4 | version=1
5 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.wst.common.project.facet.core.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.springBeans:
--------------------------------------------------------------------------------
1 |
2 |
3 | 1
4 |
5 |
6 |
7 |
8 |
9 |
10 | java:com.thomasvitale.Application
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Thomas Vitale
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Spring Boot REST Application + Spring Security with JWT
2 |
3 | A demo to test Spring Security and JWT for a RESTful application
4 |
5 | ## Usage
6 |
7 | To login, add the following code to the body of a GET request at '/login':
8 | `{"username":"user","password":"password"}`
9 |
10 | To access the protected resource '/quotes', add to the Authentication header of the request the token obtained by logging in:
11 |
12 | `Authentication: Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX `
13 |
14 | ## Implementation
15 |
16 | Spring Security is configured in `com.thomasvitale.config` package:
17 | * `WebSecurityConfig` defines the policy to access resources, filters for login and authentication, a fake user in memory.
18 |
19 | Authentication, Login and JWT are handled in `com.thomasvitale.security` package:
20 | * `JWTAuthenticationEntryPoint` returns a 401 status code if token authentication fails (whatever the reason)
21 | * `JWTLoginFilter` is used to log in users and generate a token.
22 | * `JWTAuthenticationFilter` is used to authenticate (token verification) users when trying to access protected resources.
23 | * `TokenAuthenticationService` provides methods to generate tokens, to verify their validity.
24 | * `TokenHandler` is a utility class implementing methods to build and parse tokens.
25 |
26 | ### Resources
27 |
28 | This demo has been inspired by the following guides and tutorials:
29 |
30 | * [Spring Security Architecture](https://spring.io/guides/topicals/spring-security-architecture/)
31 | * [Securing Spring Boot with JWTs](https://auth0.com/blog/securing-spring-boot-with-jwts/)
32 | * [Stateless Authentication with Spring Security and JWT](http://technicalrex.com/2015/02/20/stateless-authentication-with-spring-security-and-jwt)
33 | * [Securing REST APIs With Spring Boot](http://ryanjbaxter.com/2015/01/06/securing-rest-apis-with-spring-boot/)
34 | * [SpringSecurity : Authenticate User with Custom UserDetailsService] (http://www.ekiras.com/2016/04/authenticate-user-with-custom-user-details-service-in-spring-security.html)
35 | * [REST Security with JWT using Java and Spring Security](https://www.toptal.com/java/rest-security-with-jwt-spring-security-and-java)
36 |
37 | ### Useful Readings
38 |
39 | * [JSON Web Tokens](http://niels.nu/blog/2015/json-web-tokens.html)
--------------------------------------------------------------------------------
/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 | # http://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 | # Maven2 Start Up Batch script
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # M2_HOME - location of maven2's installed home dir
31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
32 | # e.g. to debug Maven itself, use
33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35 | # ----------------------------------------------------------------------------
36 |
37 | if [ -z "$MAVEN_SKIP_RC" ] ; then
38 |
39 | if [ -f /etc/mavenrc ] ; then
40 | . /etc/mavenrc
41 | fi
42 |
43 | if [ -f "$HOME/.mavenrc" ] ; then
44 | . "$HOME/.mavenrc"
45 | fi
46 |
47 | fi
48 |
49 | # OS specific support. $var _must_ be set to either true or false.
50 | cygwin=false;
51 | darwin=false;
52 | mingw=false
53 | case "`uname`" in
54 | CYGWIN*) cygwin=true ;;
55 | MINGW*) mingw=true;;
56 | Darwin*) darwin=true
57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
59 | if [ -z "$JAVA_HOME" ]; then
60 | if [ -x "/usr/libexec/java_home" ]; then
61 | export JAVA_HOME="`/usr/libexec/java_home`"
62 | else
63 | export JAVA_HOME="/Library/Java/Home"
64 | fi
65 | fi
66 | ;;
67 | esac
68 |
69 | if [ -z "$JAVA_HOME" ] ; then
70 | if [ -r /etc/gentoo-release ] ; then
71 | JAVA_HOME=`java-config --jre-home`
72 | fi
73 | fi
74 |
75 | if [ -z "$M2_HOME" ] ; then
76 | ## resolve links - $0 may be a link to maven's home
77 | PRG="$0"
78 |
79 | # need this for relative symlinks
80 | while [ -h "$PRG" ] ; do
81 | ls=`ls -ld "$PRG"`
82 | link=`expr "$ls" : '.*-> \(.*\)$'`
83 | if expr "$link" : '/.*' > /dev/null; then
84 | PRG="$link"
85 | else
86 | PRG="`dirname "$PRG"`/$link"
87 | fi
88 | done
89 |
90 | saveddir=`pwd`
91 |
92 | M2_HOME=`dirname "$PRG"`/..
93 |
94 | # make it fully qualified
95 | M2_HOME=`cd "$M2_HOME" && pwd`
96 |
97 | cd "$saveddir"
98 | # echo Using m2 at $M2_HOME
99 | fi
100 |
101 | # For Cygwin, ensure paths are in UNIX format before anything is touched
102 | if $cygwin ; then
103 | [ -n "$M2_HOME" ] &&
104 | M2_HOME=`cygpath --unix "$M2_HOME"`
105 | [ -n "$JAVA_HOME" ] &&
106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
107 | [ -n "$CLASSPATH" ] &&
108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
109 | fi
110 |
111 | # For Migwn, ensure paths are in UNIX format before anything is touched
112 | if $mingw ; then
113 | [ -n "$M2_HOME" ] &&
114 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
115 | [ -n "$JAVA_HOME" ] &&
116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
117 | # TODO classpath?
118 | fi
119 |
120 | if [ -z "$JAVA_HOME" ]; then
121 | javaExecutable="`which javac`"
122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
123 | # readlink(1) is not available as standard on Solaris 10.
124 | readLink=`which readlink`
125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
126 | if $darwin ; then
127 | javaHome="`dirname \"$javaExecutable\"`"
128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
129 | else
130 | javaExecutable="`readlink -f \"$javaExecutable\"`"
131 | fi
132 | javaHome="`dirname \"$javaExecutable\"`"
133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
134 | JAVA_HOME="$javaHome"
135 | export JAVA_HOME
136 | fi
137 | fi
138 | fi
139 |
140 | if [ -z "$JAVACMD" ] ; then
141 | if [ -n "$JAVA_HOME" ] ; then
142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
143 | # IBM's JDK on AIX uses strange locations for the executables
144 | JAVACMD="$JAVA_HOME/jre/sh/java"
145 | else
146 | JAVACMD="$JAVA_HOME/bin/java"
147 | fi
148 | else
149 | JAVACMD="`which java`"
150 | fi
151 | fi
152 |
153 | if [ ! -x "$JAVACMD" ] ; then
154 | echo "Error: JAVA_HOME is not defined correctly." >&2
155 | echo " We cannot execute $JAVACMD" >&2
156 | exit 1
157 | fi
158 |
159 | if [ -z "$JAVA_HOME" ] ; then
160 | echo "Warning: JAVA_HOME environment variable is not set."
161 | fi
162 |
163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
164 |
165 | # traverses directory structure from process work directory to filesystem root
166 | # first directory with .mvn subdirectory is considered project base directory
167 | find_maven_basedir() {
168 |
169 | if [ -z "$1" ]
170 | then
171 | echo "Path not specified to find_maven_basedir"
172 | return 1
173 | fi
174 |
175 | basedir="$1"
176 | wdir="$1"
177 | while [ "$wdir" != '/' ] ; do
178 | if [ -d "$wdir"/.mvn ] ; then
179 | basedir=$wdir
180 | break
181 | fi
182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
183 | if [ -d "${wdir}" ]; then
184 | wdir=`cd "$wdir/.."; pwd`
185 | fi
186 | # end of workaround
187 | done
188 | echo "${basedir}"
189 | }
190 |
191 | # concatenates all lines of a file
192 | concat_lines() {
193 | if [ -f "$1" ]; then
194 | echo "$(tr -s '\n' ' ' < "$1")"
195 | fi
196 | }
197 |
198 | BASE_DIR=`find_maven_basedir "$(pwd)"`
199 | if [ -z "$BASE_DIR" ]; then
200 | exit 1;
201 | fi
202 |
203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
204 | echo $MAVEN_PROJECTBASEDIR
205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
206 |
207 | # For Cygwin, switch paths to Windows format before running java
208 | if $cygwin; then
209 | [ -n "$M2_HOME" ] &&
210 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
211 | [ -n "$JAVA_HOME" ] &&
212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
213 | [ -n "$CLASSPATH" ] &&
214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
215 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
217 | fi
218 |
219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
220 |
221 | exec "$JAVACMD" \
222 | $MAVEN_OPTS \
223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
226 |
--------------------------------------------------------------------------------
/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 http://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 Maven2 Start Up Batch script
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 M2_HOME - location of maven2's installed home dir
28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | @REM e.g. to debug Maven itself, use
32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | @REM ----------------------------------------------------------------------------
35 |
36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37 | @echo off
38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
40 |
41 | @REM set %HOME% to equivalent of $HOME
42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
43 |
44 | @REM Execute a user defined script before this one
45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
49 | :skipRcPre
50 |
51 | @setlocal
52 |
53 | set ERROR_CODE=0
54 |
55 | @REM To isolate internal variables from possible post scripts, we use another setlocal
56 | @setlocal
57 |
58 | @REM ==== START VALIDATION ====
59 | if not "%JAVA_HOME%" == "" goto OkJHome
60 |
61 | echo.
62 | echo Error: JAVA_HOME not found in your environment. >&2
63 | echo Please set the JAVA_HOME variable in your environment to match the >&2
64 | echo location of your Java installation. >&2
65 | echo.
66 | goto error
67 |
68 | :OkJHome
69 | if exist "%JAVA_HOME%\bin\java.exe" goto init
70 |
71 | echo.
72 | echo Error: JAVA_HOME is set to an invalid directory. >&2
73 | echo JAVA_HOME = "%JAVA_HOME%" >&2
74 | echo Please set the JAVA_HOME variable in your environment to match the >&2
75 | echo location of your Java installation. >&2
76 | echo.
77 | goto error
78 |
79 | @REM ==== END VALIDATION ====
80 |
81 | :init
82 |
83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
84 | @REM Fallback to current working directory if not found.
85 |
86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
88 |
89 | set EXEC_DIR=%CD%
90 | set WDIR=%EXEC_DIR%
91 | :findBaseDir
92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
93 | cd ..
94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
95 | set WDIR=%CD%
96 | goto findBaseDir
97 |
98 | :baseDirFound
99 | set MAVEN_PROJECTBASEDIR=%WDIR%
100 | cd "%EXEC_DIR%"
101 | goto endDetectBaseDir
102 |
103 | :baseDirNotFound
104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
105 | cd "%EXEC_DIR%"
106 |
107 | :endDetectBaseDir
108 |
109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
110 |
111 | @setlocal EnableExtensions EnableDelayedExpansion
112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
114 |
115 | :endReadAdditionalConfig
116 |
117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
118 |
119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
121 |
122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
123 | if ERRORLEVEL 1 goto error
124 | goto end
125 |
126 | :error
127 | set ERROR_CODE=1
128 |
129 | :end
130 | @endlocal & set ERROR_CODE=%ERROR_CODE%
131 |
132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
136 | :skipRcPost
137 |
138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause
140 |
141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
142 |
143 | exit /B %ERROR_CODE%
144 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | com.thomasvitale
7 | spring-security-jwt-rest-demo
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | spring-security-jwt-rest-demo
12 | Spring Security JWT Rest Demo
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 1.5.4.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 |
30 | org.springframework.boot
31 | spring-boot-starter-security
32 |
33 |
34 |
35 | org.springframework.boot
36 | spring-boot-starter-web
37 |
38 |
39 |
40 | io.jsonwebtoken
41 | jjwt
42 | 0.6.0
43 |
44 |
45 |
46 | org.springframework.boot
47 | spring-boot-starter-test
48 | test
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | org.springframework.boot
57 | spring-boot-maven-plugin
58 |
59 |
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/Application.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class Application {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(Application.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/config/WebSecurityConfig.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.config;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.http.HttpMethod;
6 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
7 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
9 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
10 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
11 | import org.springframework.security.config.http.SessionCreationPolicy;
12 | import org.springframework.security.core.userdetails.UserDetailsService;
13 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
14 |
15 | import com.thomasvitale.security.JWTAuthenticationEntryPoint;
16 | import com.thomasvitale.security.JWTAuthenticationFilter;
17 | import com.thomasvitale.security.JWTLoginFilter;
18 | import com.thomasvitale.security.repository.AccountRepository;
19 | import com.thomasvitale.security.service.AccountService;
20 |
21 | @Configuration
22 | @EnableWebSecurity
23 | @EnableGlobalMethodSecurity(prePostEnabled = true)
24 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
25 |
26 | @Autowired
27 | private JWTAuthenticationEntryPoint unauthorizedHandler;
28 |
29 | @Autowired
30 | private AccountRepository accountRepository;
31 |
32 | @Override
33 | protected void configure(HttpSecurity http) throws Exception {
34 | http
35 | // Disable CSRF protection since tokens are immune to it
36 | .csrf().disable()
37 | // If the user is not authenticated, returns 401
38 | .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
39 | // This is a stateless application, disable sessions
40 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
41 | // Security policy
42 | .authorizeRequests()
43 | // Allow anonymous access to "/" path
44 | .antMatchers("/").permitAll()
45 | // Allow anonymous access to "/login" (only POST requests)
46 | .antMatchers(HttpMethod.POST, "/login").permitAll()
47 | // Any other request must be authenticated
48 | .anyRequest().authenticated().and()
49 | // Custom filter for logging in users at "/login"
50 | .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
51 | // Custom filter for authenticating users using tokens
52 | .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
53 | // Disable resource caching
54 | .headers().cacheControl();
55 | }
56 |
57 | @Override
58 | protected void configure(AuthenticationManagerBuilder auth) throws Exception {
59 |
60 | auth.userDetailsService(userDetailsServiceBean());
61 |
62 | //auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
63 | }
64 |
65 | @Override
66 | public UserDetailsService userDetailsServiceBean() throws Exception {
67 | return new AccountService(accountRepository);
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/controller/HelloController.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.controller;
2 |
3 | import org.springframework.web.bind.annotation.RequestMapping;
4 | import org.springframework.web.bind.annotation.RequestMethod;
5 | import org.springframework.web.bind.annotation.RestController;
6 |
7 | @RestController
8 | @RequestMapping("/")
9 | public class HelloController {
10 |
11 | @RequestMapping(method = RequestMethod.GET)
12 | public String hello() {
13 | return "Hello World";
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/controller/QuoteController.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.controller;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.web.bind.annotation.RequestMapping;
7 | import org.springframework.web.bind.annotation.RequestMethod;
8 | import org.springframework.web.bind.annotation.RestController;
9 |
10 | import com.thomasvitale.model.Quote;
11 | import com.thomasvitale.service.QuoteService;
12 |
13 | @RestController
14 | @RequestMapping("/quotes")
15 | public class QuoteController {
16 |
17 | @Autowired
18 | private QuoteService quoteService;
19 |
20 | @RequestMapping(method = RequestMethod.GET)
21 | public List getQuotes() {
22 | return quoteService.findAllQuotes();
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/model/Account.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.model;
2 |
3 | public class Account {
4 |
5 | private String id;
6 | private String username;
7 | private String password;
8 | private boolean enabled;
9 |
10 | public Account() {
11 | }
12 |
13 | public Account(String username, String password) {
14 | this.username = username;
15 | this.password = password;
16 | this.enabled = true;
17 | }
18 |
19 | public String getId() {
20 | return id;
21 | }
22 |
23 | public void setId(String id) {
24 | this.id = id;
25 | }
26 |
27 | public String getUsername() {
28 | return username;
29 | }
30 |
31 | public void setUsername(String username) {
32 | this.username = username;
33 | }
34 |
35 | public String getPassword() {
36 | return password;
37 | }
38 |
39 | public void setPassword(String password) {
40 | this.password = password;
41 | }
42 |
43 | public boolean isEnabled() {
44 | return enabled;
45 | }
46 |
47 | public void setEnabled(boolean enabled) {
48 | this.enabled = enabled;
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/model/Quote.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.model;
2 |
3 | public class Quote {
4 |
5 | private String author;
6 | private String sentence;
7 |
8 | public Quote() {
9 | }
10 |
11 | public Quote(String author, String sentence) {
12 | this.author = author;
13 | this.sentence = sentence;
14 | }
15 |
16 | public String getAuthor() {
17 | return author;
18 | }
19 |
20 | public void setAuthor(String author) {
21 | this.author = author;
22 | }
23 |
24 | public String getSentence() {
25 | return sentence;
26 | }
27 |
28 | public void setSentence(String sentence) {
29 | this.sentence = sentence;
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/repository/QuoteRepository.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.repository;
2 |
3 | import java.util.Collection;
4 |
5 | import com.thomasvitale.model.Quote;
6 |
7 | public interface QuoteRepository {
8 |
9 | Collection findAllQuotes();
10 |
11 | }
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/repository/QuoteRepositoryImpl.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.repository;
2 |
3 | import java.util.Collection;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | import org.springframework.stereotype.Repository;
8 |
9 | import com.thomasvitale.model.Quote;
10 |
11 | @Repository("quoteRepository")
12 | public class QuoteRepositoryImpl implements QuoteRepository {
13 |
14 | private Map quotesMap = new HashMap<>();
15 |
16 | public QuoteRepositoryImpl() {
17 | Quote q1 = new Quote("Hermione Granger", "It's leviosa, not leviosar!");
18 | quotesMap.put("Hermione Granger", q1);
19 | Quote q2 = new Quote("Sheldon Cooper", "Bazinga!");
20 | quotesMap.put("Sheldon Cooper", q2);
21 | Quote q3 = new Quote("Gandalf The Grey", "You shall not pass!");
22 | quotesMap.put("Gandalf The Grey", q3);
23 | }
24 |
25 | @Override
26 | public Collection findAllQuotes() {
27 | return quotesMap.values();
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/security/JWTAuthenticationEntryPoint.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.security;
2 |
3 | import org.springframework.security.core.AuthenticationException;
4 | import org.springframework.security.web.AuthenticationEntryPoint;
5 | import org.springframework.stereotype.Component;
6 |
7 | import javax.servlet.http.HttpServletRequest;
8 | import javax.servlet.http.HttpServletResponse;
9 | import java.io.IOException;
10 | import java.io.Serializable;
11 |
12 | @Component
13 | public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
14 |
15 | private static final long serialVersionUID = 5907023648091540313L;
16 |
17 | @Override
18 | public void commence(HttpServletRequest request,
19 | HttpServletResponse response,
20 | AuthenticationException authException) throws IOException {
21 | // This is invoked when user tries to access a secured REST resource without supplying any credentials
22 | // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to
23 | response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
24 | }
25 | }
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/security/JWTAuthenticationFilter.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.security;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.servlet.FilterChain;
6 | import javax.servlet.ServletException;
7 | import javax.servlet.ServletRequest;
8 | import javax.servlet.ServletResponse;
9 | import javax.servlet.http.HttpServletRequest;
10 |
11 | import org.springframework.security.core.Authentication;
12 | import org.springframework.security.core.context.SecurityContextHolder;
13 | import org.springframework.web.filter.GenericFilterBean;
14 |
15 | import com.thomasvitale.security.service.TokenAuthenticationService;
16 | import com.thomasvitale.security.service.TokenAuthenticationServiceImpl;
17 |
18 | public class JWTAuthenticationFilter extends GenericFilterBean {
19 |
20 | private TokenAuthenticationService tokenAuthenticationService = new TokenAuthenticationServiceImpl();
21 |
22 | @Override
23 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
24 |
25 | // Delegates authentication to the TokenAuthenticationService
26 | Authentication authentication = tokenAuthenticationService.getAuthentication((HttpServletRequest)request);
27 |
28 | // Apply the authentication to the SecurityContextHolder
29 | SecurityContextHolder.getContext().setAuthentication(authentication);
30 |
31 | // Go on processing the request
32 | filterChain.doFilter(request,response);
33 |
34 | // Clears the context from authentication
35 | SecurityContextHolder.getContext().setAuthentication(null);
36 |
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/security/JWTLoginFilter.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.security;
2 |
3 | import java.io.IOException;
4 | import java.util.Collections;
5 |
6 | import javax.servlet.FilterChain;
7 | import javax.servlet.ServletException;
8 | import javax.servlet.http.HttpServletRequest;
9 | import javax.servlet.http.HttpServletResponse;
10 |
11 | import org.springframework.security.authentication.AuthenticationManager;
12 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
13 | import org.springframework.security.core.Authentication;
14 | import org.springframework.security.core.AuthenticationException;
15 | import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
16 | import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
17 |
18 | import com.fasterxml.jackson.databind.ObjectMapper;
19 | import com.thomasvitale.model.Account;
20 | import com.thomasvitale.security.service.TokenAuthenticationService;
21 | import com.thomasvitale.security.service.TokenAuthenticationServiceImpl;
22 |
23 | public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
24 |
25 | private TokenAuthenticationService tokenAuthenticationService = new TokenAuthenticationServiceImpl();
26 |
27 | public JWTLoginFilter(String url, AuthenticationManager authManager) {
28 | super(new AntPathRequestMatcher(url));
29 | setAuthenticationManager(authManager);
30 | }
31 |
32 | @Override
33 | public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException {
34 |
35 | // Retrieve username and password from the http request and save them in an Account object.
36 | Account account = new ObjectMapper().readValue(req.getInputStream(), Account.class);
37 |
38 | // Verify if the correctness of login details.
39 | // If correct, the successfulAuthentication() method is executed.
40 | return getAuthenticationManager().authenticate(
41 | new UsernamePasswordAuthenticationToken(
42 | account.getUsername(),
43 | account.getPassword(),
44 | Collections.emptyList()
45 | )
46 | );
47 | }
48 |
49 | @Override
50 | protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) throws IOException, ServletException {
51 |
52 | // Pass authenticated user data to the tokenAuthenticationService in order to add a JWT to the http response.
53 | tokenAuthenticationService.addAuthentication(res, auth);
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/security/TokenHandler.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.security;
2 |
3 | import java.util.Date;
4 | import java.util.UUID;
5 |
6 | import org.springframework.security.core.userdetails.UserDetailsService;
7 |
8 | import com.thomasvitale.security.repository.AccountRepositoryImpl;
9 | import com.thomasvitale.security.service.AccountService;
10 |
11 | import io.jsonwebtoken.Jwts;
12 | import io.jsonwebtoken.SignatureAlgorithm;
13 |
14 | public class TokenHandler {
15 |
16 | final long EXPIRATIONTIME = 15*60*1000; // 15 minutes
17 | final String SECRET = "ThisIsASecret"; // private key, better read it from an external file
18 |
19 | final public String TOKEN_PREFIX = "Bearer"; // the prefix of the token in the http header
20 | final public String HEADER_STRING = "Authorization"; // the http header containing the prexif + the token
21 |
22 | private UserDetailsService userDetailsService = new AccountService(new AccountRepositoryImpl());
23 |
24 | /**
25 | * Generate a token from the username.
26 | *
27 | * @param username The subject from which generate the token.
28 | *
29 | * @return The generated token.
30 | */
31 | public String build(String username) {
32 |
33 | Date now = new Date();
34 |
35 | String JWT = Jwts.builder()
36 | .setId(UUID.randomUUID().toString())
37 | .setSubject(username)
38 | .setIssuedAt(now)
39 | .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
40 | //.compressWith(CompressionCodecs.DEFLATE) // uncomment to enable token compression
41 | .signWith(SignatureAlgorithm.HS512, SECRET)
42 | .compact();
43 |
44 | return JWT;
45 |
46 | }
47 |
48 | /**
49 | * Parse a token and extract the subject (username).
50 | *
51 | * @param token A token to parse.
52 | *
53 | * @return The subject (username) of the token.
54 | */
55 | public String parse(String token) {
56 |
57 | String username = Jwts.parser()
58 | .setSigningKey(SECRET)
59 | .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
60 | .getBody()
61 | .getSubject();
62 |
63 | return userDetailsService.loadUserByUsername(username).getUsername();
64 |
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/security/repository/AccountRepository.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.security.repository;
2 |
3 | import com.thomasvitale.model.Account;
4 |
5 | public interface AccountRepository {
6 |
7 | Account findByUsername(String username);
8 |
9 | }
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/security/repository/AccountRepositoryImpl.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.security.repository;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | import org.springframework.stereotype.Repository;
7 |
8 | import com.thomasvitale.model.Account;
9 |
10 | @Repository("accountRepository")
11 | public class AccountRepositoryImpl implements AccountRepository {
12 |
13 | private Map accountsMap = new HashMap<>();
14 |
15 | public AccountRepositoryImpl() {
16 | Account account = new Account("user", "password");
17 | accountsMap.put(account.getUsername(), account);
18 | }
19 |
20 | @Override
21 | public Account findByUsername(String username) {
22 | return accountsMap.get(username);
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/security/service/AccountService.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.security.service;
2 |
3 | import static java.util.Collections.emptyList;
4 |
5 | import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
6 | import org.springframework.security.core.userdetails.User;
7 | import org.springframework.security.core.userdetails.UserDetails;
8 | import org.springframework.security.core.userdetails.UserDetailsService;
9 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
10 | import org.springframework.stereotype.Service;
11 |
12 | import com.thomasvitale.model.Account;
13 | import com.thomasvitale.security.repository.AccountRepository;
14 |
15 | @Service("userDetailsService")
16 | public class AccountService implements UserDetailsService {
17 |
18 | private AccountRepository accountRepository;
19 | private final AccountStatusUserDetailsChecker detailsChecker = new AccountStatusUserDetailsChecker();
20 |
21 | public AccountService(AccountRepository accountRepository) {
22 | this.accountRepository = accountRepository;
23 | }
24 |
25 | @Override
26 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
27 |
28 | // Fetch the account corresponding to the given username
29 | Account account = accountRepository.findByUsername(username);
30 |
31 | // If the account doesn't exist
32 | if (account == null) {
33 | throw new UsernameNotFoundException("User " + username + " not found");
34 | }
35 |
36 | // User(username, password, enabled, accountNonExpired, credentialsNotExpired, accountNonLocked, authorities)
37 | User user = new User(account.getUsername(), account.getPassword(), account.isEnabled(), true, true, true, emptyList());
38 |
39 | detailsChecker.check(user);
40 |
41 | return user;
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/security/service/TokenAuthenticationService.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.security.service;
2 |
3 | import javax.servlet.http.HttpServletRequest;
4 | import javax.servlet.http.HttpServletResponse;
5 |
6 | import org.springframework.security.core.Authentication;
7 |
8 | public interface TokenAuthenticationService {
9 |
10 | /**
11 | * When a user successfully logs into the application, create a token for that user.
12 | *
13 | * @param res An http response that will be filled with an 'Authentication' header containing the token.
14 | * @param username The username mapped to the user.
15 | */
16 | void addAuthentication(HttpServletResponse res, Authentication authentication);
17 |
18 | /**
19 | * The JWTAuthenticationFilter calls this method to verify the user authentication.
20 | * If the token is not valid, the authentication fails and the request will be refused.
21 | *
22 | * @param request An http request that will be check for authentication token to verify.
23 | * @return
24 | */
25 | Authentication getAuthentication(HttpServletRequest request);
26 |
27 | }
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/security/service/TokenAuthenticationServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.security.service;
2 |
3 | import static java.util.Collections.emptyList;
4 |
5 | import javax.servlet.http.HttpServletRequest;
6 | import javax.servlet.http.HttpServletResponse;
7 |
8 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
9 | import org.springframework.security.core.Authentication;
10 | import org.springframework.stereotype.Service;
11 |
12 | import com.thomasvitale.security.TokenHandler;
13 |
14 | import io.jsonwebtoken.ExpiredJwtException;
15 | import io.jsonwebtoken.MalformedJwtException;
16 | import io.jsonwebtoken.SignatureException;
17 | import io.jsonwebtoken.UnsupportedJwtException;
18 |
19 | @Service
20 | public class TokenAuthenticationServiceImpl implements TokenAuthenticationService {
21 |
22 | private TokenHandler tokenHandler = new TokenHandler();
23 |
24 | /**
25 | * When a user successfully logs into the application, create a token for that user.
26 | *
27 | * @param res An http response that will be filled with an 'Authentication' header containing the token.
28 | * @param username The username mapped to the user.
29 | */
30 | @Override
31 | public void addAuthentication(HttpServletResponse res, Authentication authentication) {
32 |
33 | String user = authentication.getName();
34 |
35 | String JWT = tokenHandler.build(user);
36 |
37 | res.addHeader(tokenHandler.HEADER_STRING, tokenHandler.TOKEN_PREFIX + " " + JWT);
38 | }
39 |
40 | /**
41 | * The JWTAuthenticationFilter calls this method to verify the user authentication.
42 | * If the token is not valid, the authentication fails and the request will be refused.
43 | *
44 | * @param request An http request that will be check for authentication token to verify.
45 | * @return
46 | */
47 | @Override
48 | public Authentication getAuthentication(HttpServletRequest request) {
49 |
50 | String token = request.getHeader(tokenHandler.HEADER_STRING);
51 |
52 | if (token != null && token.startsWith(tokenHandler.TOKEN_PREFIX)) {
53 | // Parse the token.
54 | String user = null;
55 |
56 | try {
57 | user = tokenHandler.parse(token);
58 | } catch (ExpiredJwtException e) {
59 | e.printStackTrace();
60 | } catch (UnsupportedJwtException e) {
61 | e.printStackTrace();
62 | } catch (MalformedJwtException e) {
63 | e.printStackTrace();
64 | } catch (SignatureException e) {
65 | e.printStackTrace();
66 | } catch (IllegalArgumentException e) {
67 | e.printStackTrace();
68 | }
69 |
70 | if (user != null) {
71 | return new UsernamePasswordAuthenticationToken(user, null, emptyList());
72 | } else {
73 | return null;
74 | }
75 |
76 | }
77 |
78 | return null;
79 |
80 | }
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/service/QuoteService.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.service;
2 |
3 | import java.util.List;
4 |
5 | import com.thomasvitale.model.Quote;
6 |
7 | public interface QuoteService {
8 |
9 | List findAllQuotes();
10 |
11 | }
--------------------------------------------------------------------------------
/src/main/java/com/thomasvitale/service/QuoteServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale.service;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Service;
8 |
9 | import com.thomasvitale.model.Quote;
10 | import com.thomasvitale.repository.QuoteRepository;
11 |
12 | @Service("quoteService")
13 | public class QuoteServiceImpl implements QuoteService {
14 |
15 | @Autowired
16 | private QuoteRepository quoteRepository;
17 |
18 | @Override
19 | public List findAllQuotes() {
20 | List quotes = new ArrayList<>(quoteRepository.findAllQuotes());
21 | return quotes;
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/src/main/resources/application.properties
--------------------------------------------------------------------------------
/src/test/java/com/thomasvitale/DemoApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.thomasvitale;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class DemoApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/target/classes/META-INF/MANIFEST.MF:
--------------------------------------------------------------------------------
1 | Manifest-Version: 1.0
2 | Implementation-Title: spring-security-jwt-rest-demo
3 | Implementation-Version: 0.0.1-SNAPSHOT
4 | Built-By: thomasvitale
5 | Implementation-Vendor-Id: com.thomasvitale
6 | Build-Jdk: 1.8.0_72
7 | Implementation-URL: http://projects.spring.io/spring-boot/spring-secur
8 | ity-jwt-rest-demo/
9 | Created-By: Maven Integration for Eclipse
10 | Implementation-Vendor: Pivotal Software, Inc.
11 |
12 |
--------------------------------------------------------------------------------
/target/classes/META-INF/maven/com.thomasvitale/spring-security-jwt-rest-demo/pom.properties:
--------------------------------------------------------------------------------
1 | #Generated by Maven Integration for Eclipse
2 | #Sat Jun 24 18:46:46 CEST 2017
3 | version=0.0.1-SNAPSHOT
4 | groupId=com.thomasvitale
5 | m2e.projectName=spring-security-jwt-rest
6 | m2e.projectLocation=/Users/thomasvitale/Desktop/Polito/Applicazioni Internet/Experiments/spring-security-jwt-rest-demo
7 | artifactId=spring-security-jwt-rest-demo
8 |
--------------------------------------------------------------------------------
/target/classes/META-INF/maven/com.thomasvitale/spring-security-jwt-rest-demo/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | com.thomasvitale
7 | spring-security-jwt-rest-demo
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | spring-security-jwt-rest-demo
12 | Spring Security JWT Rest Demo
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 1.5.4.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 |
30 | org.springframework.boot
31 | spring-boot-starter-security
32 |
33 |
34 |
35 | org.springframework.boot
36 | spring-boot-starter-web
37 |
38 |
39 |
40 | io.jsonwebtoken
41 | jjwt
42 | 0.6.0
43 |
44 |
45 |
46 | org.springframework.boot
47 | spring-boot-starter-test
48 | test
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | org.springframework.boot
57 | spring-boot-maven-plugin
58 |
59 |
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/target/classes/application.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/application.properties
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/Application.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/Application.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/config/WebSecurityConfig.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/config/WebSecurityConfig.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/controller/HelloController.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/controller/HelloController.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/controller/QuoteController.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/controller/QuoteController.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/model/Account.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/model/Account.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/model/Quote.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/model/Quote.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/repository/QuoteRepository.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/repository/QuoteRepository.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/repository/QuoteRepositoryImpl.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/repository/QuoteRepositoryImpl.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/security/JWTAuthenticationEntryPoint.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/security/JWTAuthenticationEntryPoint.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/security/JWTAuthenticationFilter.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/security/JWTAuthenticationFilter.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/security/JWTLoginFilter.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/security/JWTLoginFilter.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/security/TokenHandler.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/security/TokenHandler.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/security/repository/AccountRepository.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/security/repository/AccountRepository.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/security/repository/AccountRepositoryImpl.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/security/repository/AccountRepositoryImpl.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/security/service/AccountService.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/security/service/AccountService.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/security/service/TokenAuthenticationService.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/security/service/TokenAuthenticationService.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/security/service/TokenAuthenticationServiceImpl.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/security/service/TokenAuthenticationServiceImpl.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/service/QuoteService.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/service/QuoteService.class
--------------------------------------------------------------------------------
/target/classes/com/thomasvitale/service/QuoteServiceImpl.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/classes/com/thomasvitale/service/QuoteServiceImpl.class
--------------------------------------------------------------------------------
/target/test-classes/com/thomasvitale/DemoApplicationTests.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ThomasVitale/spring-security-jwt-rest-demo/4298cef187fdeed1fe3f7ee7a80863a9d86fabb6/target/test-classes/com/thomasvitale/DemoApplicationTests.class
--------------------------------------------------------------------------------