diff --git a/README.md b/README.md new file mode 100644 index 0000000..3e340a8 --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# Description +This is a sample application, created in order to demonstrate how we can expire JWT manually without storing it. + +###### Token invalidation way: +Using random salt per user, so we can change that salt on logout and invalidate all tokens issued +with that salt. + + + +### Look here for start: + +* `com.jwtdemo.application.service.JwtService` - here api access token is issued and validated. +* `com.jwtdemo.application.auth.DemoAuthenticationProvider` - authorization with JWT token and check salt. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..060699a --- /dev/null +++ b/build.gradle @@ -0,0 +1,33 @@ +plugins { + id 'org.springframework.boot' version '2.1.4.RELEASE' + id 'java' +} + +apply plugin: 'io.spring.dependency-management' + +group = 'com.jwtdemo' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '11' + +repositories { + mavenCentral() + maven { url 'https://repo.spring.io/snapshot' } + maven { url 'https://repo.spring.io/milestone' } +} + +dependencies { + annotationProcessor 'org.projectlombok:lombok:1.18.6' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.projectlombok:lombok:1.18.6' + implementation 'com.nimbusds:nimbus-jose-jwt:7.0.1' + implementation 'org.apache.commons:commons-lang3:3.8.1' + implementation 'commons-codec:commons-codec:1.12' + runtimeOnly 'com.h2database:h2' + + testAnnotationProcessor 'org.projectlombok:lombok:1.18.6' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.security:spring-security-test' + testImplementation 'org.projectlombok:lombok:1.18.6' +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..87b738c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..88bdac0 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 07 16:43:45 JST 2019 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-all.zip diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..af6708f --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..0f8d593 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..b1ce28c --- /dev/null +++ b/settings.gradle @@ -0,0 +1,16 @@ +pluginManagement { + repositories { + maven { url 'https://repo.spring.io/snapshot' } + maven { url 'https://repo.spring.io/milestone' } + gradlePluginPortal() + } + resolutionStrategy { + eachPlugin { + if (requested.id.id == 'org.springframework.boot') { + useModule("org.springframework.boot:spring-boot-gradle-plugin:${requested.version}") + } + } + } +} + +rootProject.name = 'api demo' diff --git a/src/main/java/com/jwtdemo/JwtDemoApplication.java b/src/main/java/com/jwtdemo/JwtDemoApplication.java new file mode 100644 index 0000000..8663919 --- /dev/null +++ b/src/main/java/com/jwtdemo/JwtDemoApplication.java @@ -0,0 +1,13 @@ +package com.jwtdemo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class JwtDemoApplication { + + public static void main(String[] args) { + SpringApplication.run(JwtDemoApplication.class, args); + } + +} diff --git a/src/main/java/com/jwtdemo/application/auth/DemoAuthenticationFilter.java b/src/main/java/com/jwtdemo/application/auth/DemoAuthenticationFilter.java new file mode 100644 index 0000000..34bf3ab --- /dev/null +++ b/src/main/java/com/jwtdemo/application/auth/DemoAuthenticationFilter.java @@ -0,0 +1,25 @@ +package com.jwtdemo.application.auth; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; + +@RequiredArgsConstructor +public class DemoAuthenticationFilter extends AbstractPreAuthenticatedProcessingFilter { + + @Override + protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { + String authorization = request.getHeader("Authorization"); + if (StringUtils.isEmpty(authorization) || !authorization.startsWith("Bearer ")) { + return ""; + } + return authorization.substring(7); + } + + @Override + protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { + return "N/A"; + } +} diff --git a/src/main/java/com/jwtdemo/application/auth/DemoAuthenticationProvider.java b/src/main/java/com/jwtdemo/application/auth/DemoAuthenticationProvider.java new file mode 100644 index 0000000..9a5d3e5 --- /dev/null +++ b/src/main/java/com/jwtdemo/application/auth/DemoAuthenticationProvider.java @@ -0,0 +1,42 @@ +package com.jwtdemo.application.auth; + +import com.jwtdemo.application.model.TokenMetaData; +import com.jwtdemo.application.service.JwtService; +import com.jwtdemo.domain.user.User; +import com.jwtdemo.domain.user.UserService; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; + +@RequiredArgsConstructor +public class DemoAuthenticationProvider implements AuthenticationProvider { + + private final JwtService jwtService; + private final UserService userService; + + @Override + public Authentication authenticate(Authentication authentication) { + if (!(authentication.getPrincipal() instanceof String)) { + return null; + } + String token = (String) authentication.getPrincipal(); + if (token.isBlank()) { + return null; + } + TokenMetaData tokenMetaData = jwtService.retrieveMetaData(token); + User user = userService.getUser(tokenMetaData.getUserName()); + if (!user.getTokenSalt().equals(tokenMetaData.getSalt())) { + return null; + } + PreAuthenticatedAuthenticationToken authenticationToken = new PreAuthenticatedAuthenticationToken( + user, null); + authenticationToken.setAuthenticated(true); + return authenticationToken; + } + + @Override + public boolean supports(Class authentication) { + return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication); + } +} diff --git a/src/main/java/com/jwtdemo/application/config/ApplicationConfig.java b/src/main/java/com/jwtdemo/application/config/ApplicationConfig.java new file mode 100644 index 0000000..7b94f58 --- /dev/null +++ b/src/main/java/com/jwtdemo/application/config/ApplicationConfig.java @@ -0,0 +1,17 @@ +package com.jwtdemo.application.config; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.time.Clock; + +@RequiredArgsConstructor +@Configuration +public class ApplicationConfig { + + @Bean + public Clock clock() { + return Clock.systemDefaultZone(); + } +} diff --git a/src/main/java/com/jwtdemo/application/config/SecurityConfig.java b/src/main/java/com/jwtdemo/application/config/SecurityConfig.java new file mode 100644 index 0000000..a31772b --- /dev/null +++ b/src/main/java/com/jwtdemo/application/config/SecurityConfig.java @@ -0,0 +1,41 @@ +package com.jwtdemo.application.config; + +import com.jwtdemo.application.auth.DemoAuthenticationFilter; +import com.jwtdemo.application.auth.DemoAuthenticationProvider; +import com.jwtdemo.application.service.JwtService; +import com.jwtdemo.domain.user.UserService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; + +@Configuration +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable() + .authorizeRequests() + .antMatchers("/api/v1/auth/login").permitAll() + .antMatchers("/api/**").authenticated() + .anyRequest().denyAll() + .and() + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .enableSessionUrlRewriting(false) + .and() + .addFilterAfter(demoAuthenticationFilter(), BasicAuthenticationFilter.class); + } + + @Bean + public DemoAuthenticationProvider defaultAuthProvider(JwtService jwtService, UserService userService) { + return new DemoAuthenticationProvider(jwtService, userService); + } + + private DemoAuthenticationFilter demoAuthenticationFilter() throws Exception { + var filter = new DemoAuthenticationFilter(); + filter.setAuthenticationManager(authenticationManager()); + return filter; + } +} diff --git a/src/main/java/com/jwtdemo/application/controller/AuthController.java b/src/main/java/com/jwtdemo/application/controller/AuthController.java new file mode 100644 index 0000000..4966c3f --- /dev/null +++ b/src/main/java/com/jwtdemo/application/controller/AuthController.java @@ -0,0 +1,34 @@ +package com.jwtdemo.application.controller; + + +import com.jwtdemo.application.model.Credentials; +import com.jwtdemo.application.service.JwtService; +import com.jwtdemo.domain.user.User; +import com.jwtdemo.domain.user.UserService; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/v1/auth") +public class AuthController { + + private final UserService userService; + private final JwtService jwtService; + + @PostMapping("/login") + public String login(@RequestBody Credentials credentials) { + User user = userService.getUser(credentials.getUsername(), credentials.getSecret()); + return jwtService.issueAccessToken(user); + } + + @PostMapping("/logout") + public String logout(@AuthenticationPrincipal User user) { + userService.changeTokenSalt(user); + return "OK"; + } +} diff --git a/src/main/java/com/jwtdemo/application/exception/ServiceException.java b/src/main/java/com/jwtdemo/application/exception/ServiceException.java new file mode 100644 index 0000000..f2d1306 --- /dev/null +++ b/src/main/java/com/jwtdemo/application/exception/ServiceException.java @@ -0,0 +1,11 @@ +package com.jwtdemo.application.exception; + +public class ServiceException extends RuntimeException { + public ServiceException(String message) { + super(message); + } + + public ServiceException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/jwtdemo/application/exception/TokenNotValidException.java b/src/main/java/com/jwtdemo/application/exception/TokenNotValidException.java new file mode 100644 index 0000000..d8e71fb --- /dev/null +++ b/src/main/java/com/jwtdemo/application/exception/TokenNotValidException.java @@ -0,0 +1,11 @@ +package com.jwtdemo.application.exception; + +public class TokenNotValidException extends RuntimeException { + public TokenNotValidException(String message) { + super(message); + } + + public TokenNotValidException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/jwtdemo/application/model/Credentials.java b/src/main/java/com/jwtdemo/application/model/Credentials.java new file mode 100644 index 0000000..53dfb73 --- /dev/null +++ b/src/main/java/com/jwtdemo/application/model/Credentials.java @@ -0,0 +1,9 @@ +package com.jwtdemo.application.model; + +import lombok.Data; + +@Data +public class Credentials { + private String username; + private String secret; +} diff --git a/src/main/java/com/jwtdemo/application/model/TokenMetaData.java b/src/main/java/com/jwtdemo/application/model/TokenMetaData.java new file mode 100644 index 0000000..77ebfae --- /dev/null +++ b/src/main/java/com/jwtdemo/application/model/TokenMetaData.java @@ -0,0 +1,14 @@ +package com.jwtdemo.application.model; + +import lombok.Builder; +import lombok.Data; +import org.springframework.lang.NonNull; + +@Data +@Builder +public class TokenMetaData { + @NonNull + private String userName; + @NonNull + private String salt; +} diff --git a/src/main/java/com/jwtdemo/application/property/EcKeys.java b/src/main/java/com/jwtdemo/application/property/EcKeys.java new file mode 100644 index 0000000..4f104d5 --- /dev/null +++ b/src/main/java/com/jwtdemo/application/property/EcKeys.java @@ -0,0 +1,25 @@ +package com.jwtdemo.application.property; + +import com.nimbusds.jose.jwk.Curve; +import com.nimbusds.jose.jwk.ECKey; +import com.nimbusds.jose.jwk.KeyUse; +import com.nimbusds.jose.util.Base64URL; +import org.springframework.stereotype.Component; + +@Component +public class EcKeys { + + public ECKey getPrivateKey() { + return new ECKey.Builder(Curve.P_256, + new Base64URL("uqm4BesTXKfcdjOAYKL78MizNdVOjQEpQVwn5xrKJco"), + new Base64URL("FcO1U6DL8istqr1pLKfOyBAeDAcF88jdmYoK2nYz6O0")) + .keyUse(KeyUse.SIGNATURE) + .keyID("60f9f9e0-17f4-11ea-8d71-362b9e155667") + .d(new Base64URL("aX00h0ikq1gJZIfVLdltiDYx6y7ss-BiddHMKBlsr9E")) + .build(); + } + + public ECKey getPublicKey() { + return getPrivateKey().toPublicJWK(); + } +} diff --git a/src/main/java/com/jwtdemo/application/property/JwtProperties.java b/src/main/java/com/jwtdemo/application/property/JwtProperties.java new file mode 100644 index 0000000..eaf2ab7 --- /dev/null +++ b/src/main/java/com/jwtdemo/application/property/JwtProperties.java @@ -0,0 +1,15 @@ +package com.jwtdemo.application.property; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +import java.time.Duration; + +@Component +@ConfigurationProperties(prefix = "demo.jwt") +@Data +public class JwtProperties { + private String issuer; + private Duration tokenExpiration; +} diff --git a/src/main/java/com/jwtdemo/application/service/JwsService.java b/src/main/java/com/jwtdemo/application/service/JwsService.java new file mode 100644 index 0000000..4a9be56 --- /dev/null +++ b/src/main/java/com/jwtdemo/application/service/JwsService.java @@ -0,0 +1,59 @@ +package com.jwtdemo.application.service; + +import com.jwtdemo.application.exception.ServiceException; +import com.jwtdemo.application.exception.TokenNotValidException; +import com.nimbusds.jose.JOSEException; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.JWSHeader.Builder; +import com.nimbusds.jose.JWSVerifier; +import com.nimbusds.jose.crypto.ECDSASigner; +import com.nimbusds.jose.crypto.factories.DefaultJWSVerifierFactory; +import com.nimbusds.jose.jwk.ECKey; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import com.nimbusds.jwt.proc.BadJWTException; +import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier; +import org.springframework.lang.NonNull; +import org.springframework.stereotype.Service; + +import java.text.ParseException; + +@Service +class JwsService { + + @NonNull + SignedJWT parse(@NonNull String token) { + try { + return SignedJWT.parse(token); + } catch (ParseException e) { + throw new TokenNotValidException("Can't parse token!", e); + } + } + + @NonNull + boolean validate(@NonNull String token, @NonNull ECKey key) { + SignedJWT signedJWT = parse(token); + DefaultJWTClaimsVerifier claimsVerifier = new DefaultJWTClaimsVerifier(); + try { + JWSVerifier jwsVerifier = new DefaultJWSVerifierFactory().createJWSVerifier(signedJWT.getHeader(), key.toECPublicKey()); + claimsVerifier.verify(signedJWT.getJWTClaimsSet()); + return signedJWT.verify(jwsVerifier); + } catch (JOSEException | ParseException | BadJWTException e) { + return false; + } + } + + @NonNull + SignedJWT sign(JWTClaimsSet claimsSet, ECKey key) { + JWSHeader jwsHeader = new Builder(JWSAlgorithm.ES256).keyID( + key.getKeyID()).build(); + SignedJWT jwt = new SignedJWT(jwsHeader, claimsSet); + try { + jwt.sign(new ECDSASigner(key)); + } catch (JOSEException e) { + throw new ServiceException("Token signing failed!", e); + } + return jwt; + } +} diff --git a/src/main/java/com/jwtdemo/application/service/JwtService.java b/src/main/java/com/jwtdemo/application/service/JwtService.java new file mode 100644 index 0000000..f3f209b --- /dev/null +++ b/src/main/java/com/jwtdemo/application/service/JwtService.java @@ -0,0 +1,60 @@ +package com.jwtdemo.application.service; + +import com.jwtdemo.application.exception.TokenNotValidException; +import com.jwtdemo.application.model.TokenMetaData; +import com.jwtdemo.application.property.EcKeys; +import com.jwtdemo.application.property.JwtProperties; +import com.jwtdemo.domain.user.User; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.text.ParseException; +import java.time.Clock; +import java.time.Instant; +import java.util.Date; + +@RequiredArgsConstructor +@Service +public class JwtService { + + static final String SALT_CLAIM = "slt"; + + private final Clock clock; + private final JwsService jwsService; + private final JwtProperties jwtProperties; + private final EcKeys ecKeys; + + public String issueAccessToken(User user) { + Instant issuedAt = Instant.now(clock); + Instant expiringAt = issuedAt.plusSeconds(jwtProperties.getTokenExpiration().toSeconds()); + JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() + .issuer(jwtProperties.getIssuer()) + .subject(user.getName()) + .expirationTime(Date.from(expiringAt)) + .issueTime(Date.from(issuedAt)) + .claim(SALT_CLAIM, user.getTokenSalt()) + .build(); + + SignedJWT signedJWT = jwsService.sign(claimsSet, ecKeys.getPrivateKey()); + return signedJWT.serialize(); + } + + public TokenMetaData retrieveMetaData(String token) { + if (!jwsService.validate(token, ecKeys.getPublicKey())) { + throw new TokenNotValidException("Provided token is not valid!"); + } + SignedJWT signedJWT = jwsService.parse(token); + JWTClaimsSet jwtClaimsSet; + try { + jwtClaimsSet = signedJWT.getJWTClaimsSet(); + } catch (ParseException e) { + throw new TokenNotValidException("Can't obtain claim set!"); + } + return TokenMetaData.builder() + .userName(jwtClaimsSet.getSubject()) + .salt((String) jwtClaimsSet.getClaim(SALT_CLAIM)) + .build(); + } +} diff --git a/src/main/java/com/jwtdemo/domain/user/User.java b/src/main/java/com/jwtdemo/domain/user/User.java new file mode 100644 index 0000000..dca1278 --- /dev/null +++ b/src/main/java/com/jwtdemo/domain/user/User.java @@ -0,0 +1,33 @@ +package com.jwtdemo.domain.user; + +import lombok.AccessLevel; +import lombok.Data; +import lombok.Setter; +import org.apache.commons.lang3.RandomStringUtils; + +import javax.persistence.*; + +@Data +@Entity +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + @Column(unique = true) + private String name; + private String secret; + @Setter(AccessLevel.PRIVATE) + private String tokenSalt; + + public User() { + this.tokenSalt = generateTokenSalt(); + } + + public void changeTokenSalt() { + this.setTokenSalt(generateTokenSalt()); + } + + private String generateTokenSalt() { + return RandomStringUtils.random(8, true, true); + } +} diff --git a/src/main/java/com/jwtdemo/domain/user/UserController.java b/src/main/java/com/jwtdemo/domain/user/UserController.java new file mode 100644 index 0000000..090235a --- /dev/null +++ b/src/main/java/com/jwtdemo/domain/user/UserController.java @@ -0,0 +1,18 @@ +package com.jwtdemo.domain.user; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/v1/user") +public class UserController { + + @GetMapping("/status") + public String status(@AuthenticationPrincipal User user) { + return "User: " + user; + } +} diff --git a/src/main/java/com/jwtdemo/domain/user/UserFactory.java b/src/main/java/com/jwtdemo/domain/user/UserFactory.java new file mode 100644 index 0000000..395a308 --- /dev/null +++ b/src/main/java/com/jwtdemo/domain/user/UserFactory.java @@ -0,0 +1,16 @@ +package com.jwtdemo.domain.user; + +import org.apache.commons.lang3.RandomStringUtils; +import org.springframework.stereotype.Component; + +@Component +public class UserFactory { + + public User createUser(String name) { + User user = new User(); + user.setName(name); + user.setSecret(RandomStringUtils.random(12, true, true)); + user.changeTokenSalt(); + return user; + } +} diff --git a/src/main/java/com/jwtdemo/domain/user/UserRepository.java b/src/main/java/com/jwtdemo/domain/user/UserRepository.java new file mode 100644 index 0000000..1e17619 --- /dev/null +++ b/src/main/java/com/jwtdemo/domain/user/UserRepository.java @@ -0,0 +1,12 @@ +package com.jwtdemo.domain.user; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.lang.NonNull; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface UserRepository extends CrudRepository { + Optional findByName(@NonNull String name); +} diff --git a/src/main/java/com/jwtdemo/domain/user/UserService.java b/src/main/java/com/jwtdemo/domain/user/UserService.java new file mode 100644 index 0000000..92e5b94 --- /dev/null +++ b/src/main/java/com/jwtdemo/domain/user/UserService.java @@ -0,0 +1,33 @@ +package com.jwtdemo.domain.user; + +import com.jwtdemo.domain.user.exception.DataNotFoundException; +import lombok.RequiredArgsConstructor; +import org.springframework.lang.NonNull; +import org.springframework.stereotype.Service; + +@RequiredArgsConstructor +@Service +public class UserService { + + private final UserRepository userRepository; + + @NonNull + public User getUser(@NonNull String name, @NonNull String secret) { + User user = getUser(name); + if (user.getSecret().equals(secret)) { + return user; + } else { + throw new DataNotFoundException("No user matching username/password exists!"); + } + } + + public User getUser(String name) { + return userRepository.findByName(name) + .orElseThrow(() -> new DataNotFoundException("User not found!")); + } + + public void changeTokenSalt(@NonNull User user) { + user.changeTokenSalt(); + userRepository.save(user); + } +} diff --git a/src/main/java/com/jwtdemo/domain/user/exception/DataNotFoundException.java b/src/main/java/com/jwtdemo/domain/user/exception/DataNotFoundException.java new file mode 100644 index 0000000..11e1bc5 --- /dev/null +++ b/src/main/java/com/jwtdemo/domain/user/exception/DataNotFoundException.java @@ -0,0 +1,11 @@ +package com.jwtdemo.domain.user.exception; + +public class DataNotFoundException extends RuntimeException { + public DataNotFoundException(String message) { + super(message); + } + + public DataNotFoundException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..efa120e --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,21 @@ +server: + port: 8090 + servlet: + session: + persistent: false + cookie: + path: /auth/line + max-age: 0 + domain: + +demo: + jwt: + issuer: "mydomain.com" + token-expiration: 1d + +spring: + thymeleaf: + cache: false + mode: HTML + jpa: + show-sql: true diff --git a/src/main/resources/data.sql b/src/main/resources/data.sql new file mode 100644 index 0000000..bd30fca --- /dev/null +++ b/src/main/resources/data.sql @@ -0,0 +1,2 @@ +INSERT INTO `user` (`name`, `secret`, `token_salt`) VALUES +('user', 'secret', 'salt'); diff --git a/src/test/java/com/jwtdemo/JwtDemoApplicationTest.java b/src/test/java/com/jwtdemo/JwtDemoApplicationTest.java new file mode 100644 index 0000000..4c2168b --- /dev/null +++ b/src/test/java/com/jwtdemo/JwtDemoApplicationTest.java @@ -0,0 +1,15 @@ +package com.jwtdemo; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class JwtDemoApplicationTest { + + @Test + public void contextLoads() { + } +} diff --git a/src/test/java/com/jwtdemo/application/auth/DemoAuthenticationProviderTest.java b/src/test/java/com/jwtdemo/application/auth/DemoAuthenticationProviderTest.java new file mode 100644 index 0000000..5c04f58 --- /dev/null +++ b/src/test/java/com/jwtdemo/application/auth/DemoAuthenticationProviderTest.java @@ -0,0 +1,89 @@ +package com.jwtdemo.application.auth; + +import com.jwtdemo.application.model.TokenMetaData; +import com.jwtdemo.application.service.JwtService; + +import com.jwtdemo.domain.user.User; +import com.jwtdemo.domain.user.UserService; +import com.nimbusds.jose.jwk.Curve; +import com.nimbusds.jose.jwk.gen.ECKeyGenerator; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.security.authentication.TestingAuthenticationToken; +import org.springframework.security.core.Authentication; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; + +@RunWith(MockitoJUnitRunner.class) +public class DemoAuthenticationProviderTest { + + @Mock + private JwtService jwtService; + @Mock + private UserService userService; + + @InjectMocks + private DemoAuthenticationProvider authenticationProvider; + + @Test + public void testAuthenticate() { + String userName = "User Name"; + User user = new User(); + user.setName(userName); + String testToken = "test token"; + String salt = user.getTokenSalt(); + TestingAuthenticationToken token = new TestingAuthenticationToken(testToken, null); + TokenMetaData tokenMetaData = TokenMetaData.builder() + .userName(userName) + .salt(salt) + .build(); + given(jwtService.retrieveMetaData(testToken)).willReturn(tokenMetaData); + given(userService.getUser(userName)).willReturn(user); + Authentication authentication = authenticationProvider.authenticate(token); + + assertThat(authentication).isNotNull(); + assertThat(authentication.getPrincipal()).isEqualTo(user); + assertThat(authentication.getCredentials()).isNull(); + } + + @Test + public void testSaltChanged() { + String userName = "User Name"; + User user = new User(); + user.setName(userName); + String testToken = "test token"; + String salt = user.getTokenSalt(); + TestingAuthenticationToken token = new TestingAuthenticationToken(testToken, null); + TokenMetaData tokenMetaData = TokenMetaData.builder() + .userName(userName) + .salt(salt) + .build(); + user.changeTokenSalt(); + given(jwtService.retrieveMetaData(testToken)).willReturn(tokenMetaData); + given(userService.getUser(userName)).willReturn(user); + Authentication authentication = authenticationProvider.authenticate(token); + + assertThat(authentication).isNull(); + } + + @Test + public void testBlankToken() { + String testToken = " "; + TestingAuthenticationToken token = new TestingAuthenticationToken(testToken, null); + Authentication authentication = authenticationProvider.authenticate(token); + assertThat(authentication).isNull(); + } + + @Test + public void testWrongToken() { + TestingAuthenticationToken token = new TestingAuthenticationToken(new User(), null); + Authentication authentication = authenticationProvider.authenticate(token); + assertThat(authentication).isNull(); + } +} diff --git a/src/test/java/com/jwtdemo/application/service/JwsServiceTest.java b/src/test/java/com/jwtdemo/application/service/JwsServiceTest.java new file mode 100644 index 0000000..348776a --- /dev/null +++ b/src/test/java/com/jwtdemo/application/service/JwsServiceTest.java @@ -0,0 +1,86 @@ +package com.jwtdemo.application.service; + +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.JWSVerifier; +import com.nimbusds.jose.crypto.ECDSASigner; +import com.nimbusds.jose.crypto.factories.DefaultJWSVerifierFactory; +import com.nimbusds.jose.jwk.Curve; +import com.nimbusds.jose.jwk.ECKey; +import com.nimbusds.jose.jwk.gen.ECKeyGenerator; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import org.junit.Before; +import org.junit.Test; + +import java.time.Instant; +import java.util.Date; + +import static org.assertj.core.api.Assertions.assertThat; + +public class JwsServiceTest { + + private JwsService jwsService; + + @Before + public void setUp() { + jwsService = new JwsService(); + } + + @Test + public void testParse() throws Exception { + ECKey ecKey = generateKey(); + SignedJWT jwt = getSignedToken(ecKey, getClimeSet()); + SignedJWT actualJwt = jwsService.parse(jwt.serialize()); + + assertThat(jwt.getJWTClaimsSet().getClaims()) + .isEqualTo(actualJwt.getJWTClaimsSet().getClaims()); + } + + @Test + public void testValidate() throws Exception { + ECKey ecKey = generateKey(); + SignedJWT jwt = getSignedToken(ecKey, getClimeSet()); + boolean isValid = jwsService.validate(jwt.serialize(), ecKey); + + assertThat(isValid).isTrue(); + } + + @Test + public void testValidateFails() throws Exception { + ECKey ecKey = generateKey(); + JWTClaimsSet climeSet = new JWTClaimsSet.Builder() + .expirationTime(new Date(Instant.now().minusSeconds(60).toEpochMilli())) + .build(); + SignedJWT jwt = getSignedToken(ecKey, climeSet); + boolean isValid = jwsService.validate(jwt.serialize(), ecKey); + + assertThat(isValid).isFalse(); + } + + @Test + public void testSign() throws Exception { + ECKey ecKey = generateKey(); + SignedJWT jwt = jwsService.sign(getClimeSet(), ecKey); + JWSVerifier jwsVerifier = new DefaultJWSVerifierFactory().createJWSVerifier(jwt.getHeader(), ecKey.toECPublicKey()); + + assertThat(jwt.verify(jwsVerifier)).isTrue(); + } + + private ECKey generateKey() throws Exception { + return (new ECKeyGenerator(Curve.P_256)).generate(); + } + + private SignedJWT getSignedToken(ECKey ecKey, JWTClaimsSet claimsSet) throws Exception { + JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.ES256).keyID(ecKey.getKeyID()).build(); + SignedJWT jwt = new SignedJWT(jwsHeader, claimsSet); + jwt.sign(new ECDSASigner(ecKey)); + return jwt; + } + + private JWTClaimsSet getClimeSet() { + return new JWTClaimsSet.Builder() + .claim("claim1", "claim value") + .build(); + } +} diff --git a/src/test/java/com/jwtdemo/application/service/JwtServiceTest.java b/src/test/java/com/jwtdemo/application/service/JwtServiceTest.java new file mode 100644 index 0000000..9815b80 --- /dev/null +++ b/src/test/java/com/jwtdemo/application/service/JwtServiceTest.java @@ -0,0 +1,67 @@ +package com.jwtdemo.application.service; + +import com.jwtdemo.application.property.EcKeys; +import com.jwtdemo.application.property.JwtProperties; +import com.jwtdemo.domain.user.User; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; + +import java.text.ParseException; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Date; + +import static com.jwtdemo.application.service.JwtService.SALT_CLAIM; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { + ConfigurationPropertiesAutoConfiguration.class, + EcKeys.class, + JwtProperties.class, + JwsService.class, + JwtService.class +}) +public class JwtServiceTest { + + @MockBean + private Clock clock; + @Autowired + private JwtProperties jwtProperties; + @Autowired + private JwtService jwtService; + + @Before + public void setUp() { + given(clock.instant()).willReturn(Instant.parse("2019-01-11T12:00:00Z")); + given(clock.getZone()).willReturn(ZoneId.systemDefault()); + } + + @Test + public void testIssueAccessToken() throws ParseException { + User user = new User(); + user.setName("user"); + String accessToken = jwtService.issueAccessToken(user); + + SignedJWT signedJWT = SignedJWT.parse(accessToken); + JWTClaimsSet jwtClaimsSet = signedJWT.getJWTClaimsSet(); + Date expectedExpiration = Date.from(clock.instant().plusSeconds( + jwtProperties.getTokenExpiration().toSeconds())); + + assertThat(jwtClaimsSet.getSubject()).isEqualTo(user.getName()); + assertThat(jwtClaimsSet.getIssuer()).isEqualTo(jwtProperties.getIssuer()); + assertThat(jwtClaimsSet.getExpirationTime()).isEqualTo(expectedExpiration); + assertThat(jwtClaimsSet.getIssueTime()).isEqualTo(Date.from(clock.instant())); + assertThat(jwtClaimsSet.getClaim(SALT_CLAIM)).isEqualTo(user.getTokenSalt()); + } +} diff --git a/src/test/java/com/jwtdemo/domain/user/UserControllerTest.java b/src/test/java/com/jwtdemo/domain/user/UserControllerTest.java new file mode 100644 index 0000000..fd37e0d --- /dev/null +++ b/src/test/java/com/jwtdemo/domain/user/UserControllerTest.java @@ -0,0 +1,49 @@ +package com.jwtdemo.domain.user; + +import com.jwtdemo.application.service.JwtService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.web.context.HttpSessionSecurityContextRepository; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import java.awt.desktop.UserSessionEvent; + +import static org.junit.Assert.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@WebMvcTest(controllers = UserController.class) +public class UserControllerTest { + + @Autowired + private MockMvc mvc; + + @MockBean + private JwtService jwtService; + @MockBean + private UserService userServices; + + @WithMockUser(username = "name") + @Test + public void testStatus() throws Exception { + mvc.perform(get("/api/v1/user/status")) + .andDo(print()) + .andExpect(status().isOk()); + } + + @Test + public void testNotAuthenticated() throws Exception { + mvc.perform(get("/api/v1/user/status")) + .andDo(print()) + .andExpect(status().isForbidden()); + } +} diff --git a/src/test/java/com/jwtdemo/domain/user/UserFactoryTest.java b/src/test/java/com/jwtdemo/domain/user/UserFactoryTest.java new file mode 100644 index 0000000..8bcabc3 --- /dev/null +++ b/src/test/java/com/jwtdemo/domain/user/UserFactoryTest.java @@ -0,0 +1,22 @@ +package com.jwtdemo.domain.user; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class UserFactoryTest { + + @Test + public void testCreateUser() { + String name = "user"; + UserFactory userFactory = new UserFactory(); + + User user = userFactory.createUser(name); + + assertThat(user.getName()).isNotBlank() + .isEqualTo(name); + assertThat(user.getTokenSalt()).isNotBlank(); + assertThat(user.getSecret()).isNotBlank() + .hasSize(12); + } +} diff --git a/src/test/java/com/jwtdemo/domain/user/UserServiceTest.java b/src/test/java/com/jwtdemo/domain/user/UserServiceTest.java new file mode 100644 index 0000000..a4c9142 --- /dev/null +++ b/src/test/java/com/jwtdemo/domain/user/UserServiceTest.java @@ -0,0 +1,69 @@ +package com.jwtdemo.domain.user; + +import com.jwtdemo.domain.user.exception.DataNotFoundException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.times; + +@RunWith(MockitoJUnitRunner.class) +public class UserServiceTest { + + @Mock + private UserRepository userRepository; + + @InjectMocks + private UserService userService; + private UserFactory userFactory = new UserFactory(); + private String userName = "user"; + + @Test + public void testGetUserByName() { + User expectedUser = userFactory.createUser(userName); + given(userRepository.findByName(eq(userName))).willReturn(Optional.of(expectedUser)); + User actualUser = userService.getUser(userName); + + assertThat(actualUser).isEqualTo(expectedUser); + } + + @Test(expected = DataNotFoundException.class) + public void testGetUserByNameFailed() { + given(userRepository.findByName(eq(userName))).willReturn(Optional.empty()); + userService.getUser(userName); + } + + @Test + public void testGetUserByCredentials() { + User expectedUser = userFactory.createUser(userName); + given(userRepository.findByName(eq(userName))).willReturn(Optional.of(expectedUser)); + User actualUser = userService.getUser(userName, expectedUser.getSecret()); + + assertThat(actualUser).isEqualTo(expectedUser); + } + + @Test(expected = DataNotFoundException.class) + public void testGetUserByCredentialsFailed() { + User expectedUser = userFactory.createUser(userName); + given(userRepository.findByName(eq(userName))).willReturn(Optional.of(expectedUser)); + userService.getUser(userName, expectedUser.getSecret() + "some wrong data"); + } + + @Test + public void changeTokenSalt() { + User user = userFactory.createUser(userName); + String oldSalt = user.getTokenSalt(); + userService.changeTokenSalt(user); + + then(userRepository).should(times(1)).save(eq(user)); + assertThat(user.getTokenSalt()).isNotEqualTo(oldSalt); + } +} diff --git a/src/test/java/com/jwtdemo/domain/user/UserTest.java b/src/test/java/com/jwtdemo/domain/user/UserTest.java new file mode 100644 index 0000000..7dbbefc --- /dev/null +++ b/src/test/java/com/jwtdemo/domain/user/UserTest.java @@ -0,0 +1,21 @@ +package com.jwtdemo.domain.user; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class UserTest { + + @Test + public void testChangeTokenSalt() { + User user = new User(); + user.changeTokenSalt(); + String tokenSalt1 = user.getTokenSalt(); + user.changeTokenSalt(); + String tokenSalt2 = user.getTokenSalt(); + + assertThat(tokenSalt2).isNotEqualTo(tokenSalt1) + .hasSize(8); + } +}