├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── asia │ │ └── embla │ │ ├── SpringBootJwtApplication.java │ │ ├── config │ │ ├── AuthorizationServerConfig.java │ │ ├── DatasourceConfig.java │ │ ├── ResourceServerConfig.java │ │ └── SecurityConfig.java │ │ ├── controller │ │ └── CountryCodeController.java │ │ ├── dto │ │ └── CountryCodeDTO.java │ │ ├── entity │ │ ├── CountryCode.java │ │ ├── Role.java │ │ └── User.java │ │ ├── repository │ │ ├── CountryCodeRepository.java │ │ └── UserRepository.java │ │ └── service │ │ ├── CountryCodeService.java │ │ ├── CountryCodeServiceImpl.java │ │ └── UserDetailsServiceImpl.java └── resources │ ├── application.properties │ └── sql │ ├── data.sql │ └── schema.sql └── test └── java └── asia └── embla └── SpringBootJwtApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tharsans/spring-boot-security-with-jwt/09b21d7ac68798f941249f22283371eddfff763d/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spring-boot-security-with-jwt -------------------------------------------------------------------------------- /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 | asia.embla 7 | spring-boot-jwt 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-boot-jwt 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.10.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.7 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-data-jpa 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-test 43 | test 44 | 45 | 46 | com.h2database 47 | h2 48 | runtime 49 | 50 | 51 | org.springframework.security 52 | spring-security-crypto 53 | 54 | 55 | org.springframework.security 56 | spring-security-jwt 57 | 58 | 59 | org.springframework.security.oauth 60 | spring-security-oauth2 61 | 62 | 63 | com.google.guava 64 | guava 65 | r05 66 | 67 | 68 | 69 | 70 | 71 | 72 | org.springframework.boot 73 | spring-boot-maven-plugin 74 | 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/SpringBootJwtApplication.java: -------------------------------------------------------------------------------- 1 | package asia.embla; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.ComponentScan; 6 | 7 | @SpringBootApplication 8 | public class SpringBootJwtApplication { 9 | 10 | public static void main(String[] args) { 11 | SpringApplication.run(SpringBootJwtApplication.class, args); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/config/AuthorizationServerConfig.java: -------------------------------------------------------------------------------- 1 | package asia.embla.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.security.authentication.AuthenticationManager; 7 | import org.springframework.security.core.userdetails.UserDetailsService; 8 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 9 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 10 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 11 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 12 | import org.springframework.security.oauth2.provider.token.AccessTokenConverter; 13 | import org.springframework.security.oauth2.provider.token.DefaultTokenServices; 14 | 15 | /** 16 | * Created by tharsan on 4/24/18. 17 | */ 18 | @Configuration 19 | @EnableAuthorizationServer 20 | public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { 21 | @Value("${security.jwt.client-id}") 22 | private String clientId; 23 | 24 | @Value("${security.jwt.client-secret}") 25 | private String clientSecret; 26 | 27 | @Value("${security.jwt.grant-type}") 28 | private String grantType; 29 | 30 | @Value("${security.jwt.scope-read}") 31 | private String scopeRead; 32 | 33 | @Value("${security.jwt.scope-write}") 34 | private String scopeWrite = "write"; 35 | 36 | @Value("${security.jwt.resource-ids}") 37 | private String resourceIds; 38 | 39 | @Autowired 40 | private AuthenticationManager authenticationManager; 41 | 42 | @Autowired 43 | private UserDetailsService userDetailsService; 44 | 45 | @Autowired 46 | private DefaultTokenServices defaultTokenServices; 47 | 48 | @Autowired 49 | private AccessTokenConverter accessTokenConverter; 50 | 51 | @Override 52 | public void configure(ClientDetailsServiceConfigurer configurer) throws Exception { 53 | configurer 54 | .inMemory() 55 | .withClient(clientId) 56 | .secret(clientSecret) 57 | .authorizedGrantTypes(grantType) 58 | .scopes(scopeRead, scopeWrite) 59 | .resourceIds(resourceIds); 60 | } 61 | 62 | @Override 63 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 64 | endpoints.tokenServices(defaultTokenServices).authenticationManager(authenticationManager) 65 | .accessTokenConverter(accessTokenConverter).userDetailsService(userDetailsService); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/config/DatasourceConfig.java: -------------------------------------------------------------------------------- 1 | package asia.embla.config; 2 | 3 | import org.springframework.beans.factory.annotation.Qualifier; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 7 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; 8 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; 9 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; 10 | import org.springframework.orm.jpa.JpaTransactionManager; 11 | import org.springframework.orm.jpa.JpaVendorAdapter; 12 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 13 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; 14 | import org.springframework.transaction.PlatformTransactionManager; 15 | import org.springframework.transaction.annotation.EnableTransactionManagement; 16 | 17 | import javax.persistence.EntityManagerFactory; 18 | import javax.sql.DataSource; 19 | import java.beans.PropertyVetoException; 20 | 21 | /** 22 | * Created by tharsan on 4/24/18. 23 | */ 24 | @Configuration 25 | public class DatasourceConfig { 26 | @Bean 27 | public DataSource datasource() throws PropertyVetoException { 28 | EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); 29 | EmbeddedDatabase dataSource = builder 30 | .setType(EmbeddedDatabaseType.H2) 31 | .addScript("sql/schema.sql") 32 | .addScript("sql/data.sql") 33 | .build(); 34 | 35 | return dataSource; 36 | } 37 | 38 | @Bean 39 | public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier("datasource") DataSource ds) throws PropertyVetoException{ 40 | LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean(); 41 | entityManagerFactory.setDataSource(ds); 42 | entityManagerFactory.setPackagesToScan(new String[]{"asia.embla.entity"}); 43 | JpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); 44 | entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter); 45 | return entityManagerFactory; 46 | } 47 | 48 | @Bean 49 | public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory){ 50 | JpaTransactionManager transactionManager = new JpaTransactionManager(); 51 | transactionManager.setEntityManagerFactory(entityManagerFactory); 52 | return transactionManager; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/config/ResourceServerConfig.java: -------------------------------------------------------------------------------- 1 | package asia.embla.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 7 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 8 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 9 | import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; 10 | import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; 11 | 12 | /** 13 | * Created by tharsan on 4/24/18. 14 | */ 15 | @Configuration 16 | @EnableResourceServer 17 | public class ResourceServerConfig extends ResourceServerConfigurerAdapter { 18 | @Autowired 19 | private ResourceServerTokenServices tokenServices; 20 | 21 | @Value("${security.jwt.resource-ids}") 22 | private String resourceIds; 23 | 24 | @Override 25 | public void configure(ResourceServerSecurityConfigurer resources) throws Exception { 26 | resources.resourceId(resourceIds).tokenServices(tokenServices); 27 | } 28 | 29 | @Override 30 | public void configure(HttpSecurity http) throws Exception { 31 | http.requestMatchers() 32 | .and() 33 | .authorizeRequests() 34 | .antMatchers("/countries/**" ).authenticated(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package asia.embla.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.security.authentication.AuthenticationManager; 8 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 9 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 10 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 12 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 13 | import org.springframework.security.config.http.SessionCreationPolicy; 14 | import org.springframework.security.core.userdetails.UserDetailsService; 15 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 16 | import org.springframework.security.crypto.password.PasswordEncoder; 17 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 18 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 19 | import org.springframework.security.oauth2.provider.token.DefaultTokenServices; 20 | import org.springframework.security.oauth2.provider.token.TokenEnhancer; 21 | import org.springframework.security.oauth2.provider.token.TokenEnhancerChain; 22 | import org.springframework.security.oauth2.provider.token.TokenStore; 23 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 24 | import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; 25 | 26 | import com.google.common.collect.Lists; 27 | /** 28 | * Created by tharsan on 4/24/18. 29 | */ 30 | @Configuration 31 | @EnableWebSecurity 32 | @EnableGlobalMethodSecurity(prePostEnabled = true) 33 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 34 | @Value("${security.signing-key}") 35 | private String signingKey; 36 | 37 | @Value("${security.encoding-strength}") 38 | private Integer encodingStrength; 39 | 40 | @Value("${security.security-realm}") 41 | private String securityRealm; 42 | 43 | @Autowired 44 | private PasswordEncoder bCryptPasswordEncoder; 45 | 46 | @Autowired 47 | private UserDetailsService userDetailsService; 48 | 49 | @Bean 50 | @Override 51 | protected AuthenticationManager authenticationManager() throws Exception { 52 | return super.authenticationManager(); 53 | } 54 | 55 | @Override 56 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 57 | auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder); 58 | } 59 | 60 | @Override 61 | protected void configure(HttpSecurity http) throws Exception { 62 | http 63 | .sessionManagement() 64 | .sessionCreationPolicy(SessionCreationPolicy.STATELESS) 65 | .and() 66 | .httpBasic() 67 | .realmName(securityRealm) 68 | .and() 69 | .csrf() 70 | .disable(); 71 | 72 | } 73 | 74 | @Bean 75 | public JwtAccessTokenConverter accessTokenConverter() { 76 | JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); 77 | converter.setSigningKey(signingKey); 78 | return converter; 79 | } 80 | 81 | @Bean 82 | public TokenStore tokenStore() { 83 | return new JwtTokenStore(accessTokenConverter()); 84 | } 85 | 86 | @Bean 87 | public TokenEnhancerChain tokenEnhancerChain() { 88 | final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); 89 | tokenEnhancerChain.setTokenEnhancers(Lists.newArrayList(new MyTokenEnhancer(), accessTokenConverter())); 90 | return tokenEnhancerChain; 91 | } 92 | 93 | @Bean 94 | public DefaultTokenServices defaultTokenServices() { 95 | final DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); 96 | defaultTokenServices.setTokenStore(tokenStore()); 97 | // defaultTokenServices.setClientDetailsService(clientDetailsService); 98 | defaultTokenServices.setTokenEnhancer(tokenEnhancerChain()); 99 | defaultTokenServices.setSupportRefreshToken(true); 100 | return defaultTokenServices; 101 | } 102 | 103 | private static class MyTokenEnhancer implements TokenEnhancer { 104 | @Override 105 | public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { 106 | // TODO Auto-generated method stub 107 | return accessToken; 108 | } 109 | } 110 | 111 | @Bean 112 | public PasswordEncoder passwordEncoder() { 113 | return new BCryptPasswordEncoder(); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/controller/CountryCodeController.java: -------------------------------------------------------------------------------- 1 | package asia.embla.controller; 2 | 3 | import asia.embla.dto.CountryCodeDTO; 4 | import asia.embla.service.CountryCodeService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.access.prepost.PreAuthorize; 7 | import org.springframework.web.bind.annotation.*; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * Created by tharsan on 4/24/18. 13 | */ 14 | @RestController 15 | @RequestMapping("/countrycodes") 16 | public class CountryCodeController { 17 | @Autowired 18 | private CountryCodeService countryCodeService; 19 | 20 | @RequestMapping(value = "/", method = RequestMethod.GET) 21 | public List getCountries(){ 22 | return countryCodeService.getCountryCodes(); 23 | } 24 | 25 | @PreAuthorize("hasAuthority('SUPER_ADMIN') OR hasAuthority('ADMIN')") 26 | @RequestMapping(value = "/", method = RequestMethod.POST) 27 | public String createCountry(@RequestBody CountryCodeDTO countryDTO){ 28 | return countryCodeService.createCountryCode(countryDTO); 29 | } 30 | 31 | @PreAuthorize("hasAuthority('SUPER_ADMIN')") 32 | @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) 33 | public String deleteCountry(@RequestParam("id") int id){ 34 | return countryCodeService.deleteCountryCode(id); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/dto/CountryCodeDTO.java: -------------------------------------------------------------------------------- 1 | package asia.embla.dto; 2 | 3 | /** 4 | * Created by tharsan on 4/24/18. 5 | */ 6 | public class CountryCodeDTO { 7 | private int id; 8 | private String name; 9 | private String code; 10 | private String isoCode; 11 | 12 | public int getId() { 13 | return id; 14 | } 15 | 16 | public void setId(int id) { 17 | this.id = id; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public void setName(String name) { 25 | this.name = name; 26 | } 27 | 28 | public String getCode() { 29 | return code; 30 | } 31 | 32 | public void setCode(String code) { 33 | this.code = code; 34 | } 35 | 36 | public String getIsoCode() { 37 | return isoCode; 38 | } 39 | 40 | public void setIsoCode(String isoCode) { 41 | this.isoCode = isoCode; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/entity/CountryCode.java: -------------------------------------------------------------------------------- 1 | package asia.embla.entity; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.Id; 6 | import javax.persistence.Table; 7 | 8 | /** 9 | * Created by tharsan on 2/22/18. 10 | */ 11 | @Entity 12 | @Table(name = "country_code") 13 | public class CountryCode { 14 | @Id 15 | @Column(name = "id") 16 | private int id; 17 | 18 | @Column(name = "name") 19 | private String name; 20 | 21 | @Column(name = "code") 22 | private String code; 23 | 24 | @Column(name = "iso_code") 25 | private String isoCode; 26 | 27 | public int getId() { 28 | return id; 29 | } 30 | 31 | public void setId(int id) { 32 | this.id = id; 33 | } 34 | 35 | public String getName() { 36 | return name; 37 | } 38 | 39 | public void setName(String name) { 40 | this.name = name; 41 | } 42 | 43 | public String getCode() { 44 | return code; 45 | } 46 | 47 | public void setCode(String code) { 48 | this.code = code; 49 | } 50 | 51 | public String getIsoCode() { 52 | return isoCode; 53 | } 54 | 55 | public void setIsoCode(String isoCode) { 56 | this.isoCode = isoCode; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/entity/Role.java: -------------------------------------------------------------------------------- 1 | package asia.embla.entity; 2 | 3 | import javax.persistence.*; 4 | 5 | /** 6 | * Created by tharsan on 4/24/18. 7 | */ 8 | @Entity 9 | @Table(name = "role") 10 | public class Role { 11 | @Id 12 | @GeneratedValue(strategy = GenerationType.IDENTITY) 13 | private Long id; 14 | 15 | @Column(name="name") 16 | private String name; 17 | 18 | @Column(name="description") 19 | private String description; 20 | 21 | public Long getId() { 22 | return id; 23 | } 24 | 25 | public void setId(Long id) { 26 | this.id = id; 27 | } 28 | 29 | public String getName() { 30 | return name; 31 | } 32 | 33 | public void setName(String name) { 34 | this.name = name; 35 | } 36 | 37 | public String getDescription() { 38 | return description; 39 | } 40 | 41 | public void setDescription(String description) { 42 | this.description = description; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/entity/User.java: -------------------------------------------------------------------------------- 1 | package asia.embla.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | 5 | import javax.persistence.*; 6 | import java.util.List; 7 | 8 | /** 9 | * Created by tharsan on 4/24/18. 10 | */ 11 | @Entity 12 | @Table(name = "user") 13 | public class User { 14 | @Id 15 | @GeneratedValue(strategy = GenerationType.IDENTITY) 16 | @Column(name = "id") 17 | private Long id; 18 | 19 | @Column(name = "username") 20 | private String username; 21 | 22 | @Column(name = "password") 23 | @JsonIgnore 24 | private String password; 25 | 26 | @ManyToMany(fetch = FetchType.EAGER) 27 | @JoinTable(name = "user_role", joinColumns 28 | = @JoinColumn(name = "user_id", 29 | referencedColumnName = "id"), 30 | inverseJoinColumns = @JoinColumn(name = "role_id", 31 | referencedColumnName = "id")) 32 | private List roles; 33 | 34 | public Long getId() { 35 | return id; 36 | } 37 | 38 | public void setId(Long id) { 39 | this.id = id; 40 | } 41 | 42 | public String getUsername() { 43 | return username; 44 | } 45 | 46 | public void setUsername(String username) { 47 | this.username = username; 48 | } 49 | 50 | public String getPassword() { 51 | return password; 52 | } 53 | 54 | public void setPassword(String password) { 55 | this.password = password; 56 | } 57 | 58 | public List getRoles() { 59 | return roles; 60 | } 61 | 62 | public void setRoles(List roles) { 63 | this.roles = roles; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/repository/CountryCodeRepository.java: -------------------------------------------------------------------------------- 1 | package asia.embla.repository; 2 | 3 | import asia.embla.entity.CountryCode; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | /** 8 | * Created by tharsan on 2/22/18. 9 | */ 10 | @Repository 11 | public interface CountryCodeRepository extends JpaRepository { 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package asia.embla.repository; 2 | 3 | import asia.embla.entity.User; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | /** 9 | * Created by tharsan on 4/24/18. 10 | */ 11 | @Repository 12 | public interface UserRepository extends JpaRepository { 13 | User findByUsername(String username); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/service/CountryCodeService.java: -------------------------------------------------------------------------------- 1 | package asia.embla.service; 2 | 3 | import asia.embla.dto.CountryCodeDTO; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Created by tharsan on 2/22/18. 9 | */ 10 | public interface CountryCodeService { 11 | List getCountryCodes(); 12 | String createCountryCode(CountryCodeDTO countryDTO); 13 | String deleteCountryCode(int id); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/service/CountryCodeServiceImpl.java: -------------------------------------------------------------------------------- 1 | package asia.embla.service; 2 | 3 | import asia.embla.dto.CountryCodeDTO; 4 | import asia.embla.entity.CountryCode; 5 | import asia.embla.repository.CountryCodeRepository; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | /** 13 | * Created by tharsan on 4/24/18. 14 | */ 15 | @Service 16 | public class CountryCodeServiceImpl implements CountryCodeService { 17 | @Autowired 18 | private CountryCodeRepository repository; 19 | 20 | private final static String CREATED = "CountryCode has been created successfully"; 21 | private final static String DELETED = "CountryCode has been deleted successfully"; 22 | 23 | @Override 24 | public List getCountryCodes() { 25 | List countryCodeDTOs = new ArrayList<>(); 26 | CountryCodeDTO countryCodeDTO = null; 27 | List countryCodes = repository.findAll(); 28 | for(CountryCode countryCode : countryCodes){ 29 | countryCodeDTO = new CountryCodeDTO(); 30 | countryCodeDTO.setId(countryCode.getId()); 31 | countryCodeDTO.setName(countryCode.getName()); 32 | countryCodeDTO.setCode(countryCode.getCode()); 33 | countryCodeDTO.setIsoCode(countryCode.getIsoCode()); 34 | countryCodeDTOs.add(countryCodeDTO); 35 | } 36 | return countryCodeDTOs; 37 | } 38 | 39 | @Override 40 | public String createCountryCode(CountryCodeDTO countryCodeDTO) { 41 | CountryCode countryCode = new CountryCode(); 42 | countryCode.setId(countryCodeDTO.getId()); 43 | countryCode.setName(countryCodeDTO.getName()); 44 | countryCode.setCode(countryCodeDTO.getCode()); 45 | countryCode.setIsoCode(countryCodeDTO.getIsoCode()); 46 | repository.save(countryCode); 47 | return CREATED; 48 | } 49 | 50 | @Override 51 | public String deleteCountryCode(int id) { 52 | repository.delete(id); 53 | return DELETED; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/asia/embla/service/UserDetailsServiceImpl.java: -------------------------------------------------------------------------------- 1 | package asia.embla.service; 2 | 3 | import asia.embla.entity.Role; 4 | import asia.embla.entity.User; 5 | import asia.embla.repository.UserRepository; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.security.core.GrantedAuthority; 8 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | import org.springframework.security.core.userdetails.UserDetailsService; 11 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 12 | import org.springframework.stereotype.Service; 13 | 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | /** 18 | * Created by tharsan on 4/24/18. 19 | */ 20 | @Service 21 | public class UserDetailsServiceImpl implements UserDetailsService { 22 | @Autowired 23 | private UserRepository userRepository; 24 | 25 | @Override 26 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 27 | User user = userRepository.findByUsername(username); 28 | 29 | if(user == null) { 30 | throw new UsernameNotFoundException(String.format("The username %s doesn't exist", username)); 31 | } 32 | 33 | List authorities = new ArrayList<>(); 34 | List roles = user.getRoles(); 35 | for(Role role : roles){ 36 | authorities.add(new SimpleGrantedAuthority(role.getName())); 37 | } 38 | 39 | UserDetails userDetails = new org.springframework.security.core.userdetails. 40 | User(user.getUsername(), user.getPassword(), authorities); 41 | 42 | return userDetails; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | ### security ######## 2 | security.oauth2.resource.filter-order=3 3 | security.signing-key=MaYzkSjmkzPC57L 4 | security.encoding-strength=256 5 | security.security-realm=EmblaMagazineRealm 6 | 7 | security.jwt.client-id=EmblaMagazineClient 8 | security.jwt.client-secret=f2a1ed52710d4533bde25be6da03b6e3 9 | security.jwt.grant-type=password 10 | security.jwt.scope-read=read 11 | security.jwt.scope-write=write 12 | security.jwt.resource-ids=EmblaMagazineRestAPI 13 | 14 | -------------------------------------------------------------------------------- /src/main/resources/sql/data.sql: -------------------------------------------------------------------------------- 1 | DELETE FROM country_code; 2 | DELETE FROM user_role; 3 | DELETE FROM role; 4 | DELETE FROM user; 5 | 6 | INSERT INTO role (id, name, description) VALUES (1, 'USER', 'User - has authority to view list of country codes'); 7 | INSERT INTO role (id, name, description) VALUES (2, 'ADMIN', 'Admin - has authority to view and create list of country codes'); 8 | INSERT INTO role (id, name, description) VALUES (3, 'SUPER_ADMIN', 'Super Admin - has authority to view, create and delete country codes'); 9 | 10 | INSERT INTO user (id, username, password) VALUES (1, 'user', '$2a$10$.vqKeONK..aJ1Dy1P6z5peftRXek8S0dBC4hJmiIUe8lezmO4t9nu'); 11 | INSERT INTO user (id, username, password) VALUES (2, 'admin', '$2a$10$.vqKeONK..aJ1Dy1P6z5peftRXek8S0dBC4hJmiIUe8lezmO4t9nu'); 12 | INSERT INTO user (id, username, password) VALUES (3, 'superadmin', '$2a$10$.vqKeONK..aJ1Dy1P6z5peftRXek8S0dBC4hJmiIUe8lezmO4t9nu'); 13 | 14 | INSERT INTO user_role(user_id, role_id) VALUES(1,1); 15 | INSERT INTO user_role(user_id, role_id) VALUES(2,2); 16 | INSERT INTO user_role(user_id, role_id) VALUES(3,3); 17 | 18 | INSERT INTO country_code(id, name, code, iso_code) VALUES (1, 'Sri Lanka', '94', 'LK'); 19 | INSERT INTO country_code(id, name, code, iso_code) VALUES (2, 'India', '91', 'IN'); 20 | INSERT INTO country_code(id, name, code, iso_code) VALUES (3, 'United Kingdom', '44', 'GB'); 21 | INSERT INTO country_code(id, name, code, iso_code) VALUES (4, 'United States', '1', 'US'); 22 | INSERT INTO country_code(id, name, code, iso_code) VALUES (5, 'Singapore', '65', 'SG'); -------------------------------------------------------------------------------- /src/main/resources/sql/schema.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE country_code ( 2 | id INT NOT NULL AUTO_INCREMENT, 3 | name varchar(255) DEFAULT NULL, 4 | code varchar(5) DEFAULT NULL, 5 | iso_code varchar(5) DEFAULT NULL, 6 | PRIMARY KEY (id) 7 | ); 8 | 9 | CREATE TABLE role ( 10 | id INT NOT NULL AUTO_INCREMENT, 11 | name varchar(20) DEFAULT NULL, 12 | description varchar(100) DEFAULT NULL, 13 | PRIMARY KEY (id) 14 | ); 15 | 16 | 17 | CREATE TABLE user ( 18 | id INT NOT NULL AUTO_INCREMENT, 19 | username varchar(50) NOT NULL, 20 | password varchar(255) NOT NULL, 21 | PRIMARY KEY (id) 22 | ); 23 | 24 | 25 | CREATE TABLE user_role ( 26 | user_id INT NOT NULL, 27 | role_id INT NOT NULL, 28 | CONSTRAINT fk_user_role_user_id FOREIGN KEY (user_id) REFERENCES user (id), 29 | CONSTRAINT fk_user_role_role_id FOREIGN KEY (role_id) REFERENCES role (id) 30 | ); -------------------------------------------------------------------------------- /src/test/java/asia/embla/SpringBootJwtApplicationTests.java: -------------------------------------------------------------------------------- 1 | package asia.embla; 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 SpringBootJwtApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------