├── .gitignore ├── .mvn └── wrapper │ └── maven-wrapper.properties ├── .travis.yml ├── LICENSE ├── README.md ├── build-tools └── quality │ ├── checkstyle │ ├── checkstyle-suppress.xml │ └── checkstyle.xml │ └── pmd │ └── pmd-ruleset.xml ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── github │ │ └── vlsidlyarevich │ │ ├── Application.java │ │ ├── config │ │ ├── CorsFilter.java │ │ └── SecurityConfig.java │ │ ├── controller │ │ ├── AuthenticationController.java │ │ ├── SecuredController.java │ │ └── SignUpController.java │ │ ├── converter │ │ ├── ConverterFacade.java │ │ ├── dto │ │ │ └── UserDTOConverter.java │ │ └── factory │ │ │ └── ConverterFactory.java │ │ ├── dto │ │ ├── LoginDTO.java │ │ ├── TokenDTO.java │ │ └── UserDTO.java │ │ ├── exception │ │ ├── handler │ │ │ └── CustomExceptionHandler.java │ │ └── model │ │ │ ├── ServiceException.java │ │ │ └── UserNotFoundException.java │ │ ├── model │ │ ├── Authority.java │ │ ├── BaseEntity.java │ │ ├── User.java │ │ └── UserAuthentication.java │ │ ├── repository │ │ └── UserRepository.java │ │ ├── security │ │ ├── RestAuthenticationEntryPoint.java │ │ ├── constants │ │ │ └── SecurityConstants.java │ │ ├── filter │ │ │ └── AuthenticationTokenFilter.java │ │ └── service │ │ │ ├── BasicUserDetailsService.java │ │ │ ├── JsonWebTokenAuthenticationService.java │ │ │ ├── JsonWebTokenService.java │ │ │ ├── TokenAuthenticationService.java │ │ │ └── TokenService.java │ │ └── service │ │ ├── BasicUserService.java │ │ └── UserService.java └── resources │ └── application.properties └── test └── resourсes └── application.properties /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Node template 3 | # Logs 4 | logs 5 | *.log 6 | npm-debug.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | 13 | # Directory for instrumented libs generated by jscoverage/JSCover 14 | lib-cov 15 | 16 | # Coverage directory used by tools like istanbul 17 | coverage 18 | 19 | # nyc test coverage 20 | .nyc_output 21 | 22 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 23 | .grunt 24 | 25 | # node-waf configuration 26 | .lock-wscript 27 | 28 | # Compiled binary addons (http://nodejs.org/api/addons.html) 29 | build/Release 30 | 31 | # Dependency directories 32 | node_modules 33 | jspm_packages 34 | bower_components 35 | 36 | # Optional npm cache dirnectory 37 | .npm 38 | 39 | # Optional REPL history 40 | .node_repl_history 41 | ### Java template 42 | *.class 43 | 44 | # Mobile Tools for Java (J2ME) 45 | .mtj.tmp/ 46 | 47 | # Package Files # 48 | *.jar 49 | *.war 50 | *.ear 51 | 52 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 53 | hs_err_pid* 54 | ### JetBrains template 55 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 56 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 57 | 58 | # User-specific stuff: 59 | *.iml 60 | .idea 61 | .idea/workspace.xml 62 | .idea/tasks.xml 63 | .idea/dictionaries 64 | .idea/vcs.xml 65 | .idea/jsLibraryMappings.xml 66 | 67 | # Sensitive or high-churn files: 68 | .idea/dataSources.ids 69 | .idea/dataSources.xml 70 | .idea/dataSources.local.xml 71 | .idea/sqlDataSources.xml 72 | .idea/dynamic.xml 73 | .idea/uiDesigner.xml 74 | 75 | # Gradle: 76 | .idea/gradle.xml 77 | .idea/libraries 78 | 79 | # Mongo Explorer plugin: 80 | .idea/mongoSettings.xml 81 | 82 | ## File-based project format: 83 | *.iws 84 | 85 | ## Plugin-specific files: 86 | 87 | # IntelliJ 88 | /out/ 89 | 90 | # mpeltonen/sbt-idea plugin 91 | .idea_modules/ 92 | 93 | # JIRA plugin 94 | atlassian-ide-plugin.xml 95 | 96 | # Crashlytics plugin (for Android Studio and IntelliJ) 97 | com_crashlytics_export_strings.xml 98 | crashlytics.properties 99 | crashlytics-build.properties 100 | fabric.properties 101 | ### Maven template 102 | target/ 103 | pom.xml.tag 104 | pom.xml.releaseBackup 105 | pom.xml.versionsBackup 106 | pom.xml.next 107 | release.properties 108 | dependency-reduced-pom.xml 109 | buildNumber.properties 110 | .mvn/timing.properties 111 | 112 | # Project specific 113 | node 114 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: oraclejdk8 3 | services: mongodb 4 | before_install: 5 | - mvn -N io.takari:maven:wrapper 6 | after_success: 7 | - mvn clean install 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring-Boot-MongoDB-JWT 2 | [![Build Status](https://travis-ci.org/vlsidlyarevich/Spring-Boot-MongoDB-JWT.svg?branch=master)](https://travis-ci.org/vlsidlyarevich/Spring-Boot-MongoDB-JWT) 3 | ### Spring Boot base for projects with MongoDB and JWT based security. 4 | --- 5 | This is a quick-start base for java projects with Spring Boot, MongoDB and configured JWT security. 6 | ### Running 7 | * Download this base 8 | * Start the MongoDB service/daemon in your system 9 | * Run project by `Application.class` or by `mvn clean install`, `java -jar target/*.jar`, or by `mvn spring-boot:run` 10 | 11 | --- 12 | ### JWT security 13 | Page `http://localhost:8080/api/hello` is secured. To access this page, you need to do the following: 14 | 15 | * **POST** request to `http://localhost:8080/api/signup` with body 16 | ```json 17 | username: "user", 18 | password: "12345" 19 | ``` 20 | * **POST** request to `http://localhost:8080/api/auth`, then take token from responce and use it in header to access secured page 21 | * **GET** request to `http://localhost:8080/api/hello` with header: 22 | ```json 23 | x-auth-token: 24 | ``` 25 | 26 | Security is based on [AuthenticationTokenFilter](https://github.com/vlsidlyarevich/Spring-Boot-MongoDB-JWT/blob/master/src/main/java/com/github/vlsidlyarevich/security/filter/AuthenticationTokenFilter.java#L16-L33): 27 | 28 | ```java 29 | @Override 30 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) 31 | throws IOException, ServletException { 32 | HttpServletRequest httpRequest = (HttpServletRequest) request; 33 | Authentication authentication = authenticationService.authenticate(httpRequest); 34 | SecurityContextHolder.getContext().setAuthentication(authentication); 35 | filterChain.doFilter(request, response); 36 | SecurityContextHolder.getContext().setAuthentication(null); 37 | } 38 | ``` 39 | And some services for [Token creation](https://github.com/vlsidlyarevich/Spring-Boot-MongoDB-JWT/blob/master/src/main/java/com/github/vlsidlyarevich/security/service/impl/TokenServiceImpl.java) and [Token verification](https://github.com/vlsidlyarevich/Spring-Boot-MongoDB-JWT/blob/master/src/main/java/com/github/vlsidlyarevich/security/service/impl/TokenAuthenticationServiceImpl.java). 40 | -------------------------------------------------------------------------------- /build-tools/quality/checkstyle/checkstyle-suppress.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /build-tools/quality/checkstyle/checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 21 | 22 | 23 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | -------------------------------------------------------------------------------- /build-tools/quality/pmd/pmd-ruleset.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | This ruleset defines the PMD rules for project "unity". 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /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 | # 58 | # Look for the Apple JDKs first to preserve the existing behaviour, and then look 59 | # for the new JDKs provided by Oracle. 60 | # 61 | if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then 62 | # 63 | # Apple JDKs 64 | # 65 | export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home 66 | fi 67 | 68 | if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then 69 | # 70 | # Apple JDKs 71 | # 72 | export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home 73 | fi 74 | 75 | if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then 76 | # 77 | # Oracle JDKs 78 | # 79 | export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home 80 | fi 81 | 82 | if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then 83 | # 84 | # Apple JDKs 85 | # 86 | export JAVA_HOME=`/usr/libexec/java_home` 87 | fi 88 | ;; 89 | esac 90 | 91 | if [ -z "$JAVA_HOME" ] ; then 92 | if [ -r /etc/gentoo-release ] ; then 93 | JAVA_HOME=`java-config --jre-home` 94 | fi 95 | fi 96 | 97 | if [ -z "$M2_HOME" ] ; then 98 | ## resolve links - $0 may be a link to maven's home 99 | PRG="$0" 100 | 101 | # need this for relative symlinks 102 | while [ -h "$PRG" ] ; do 103 | ls=`ls -ld "$PRG"` 104 | link=`expr "$ls" : '.*-> \(.*\)$'` 105 | if expr "$link" : '/.*' > /dev/null; then 106 | PRG="$link" 107 | else 108 | PRG="`dirname "$PRG"`/$link" 109 | fi 110 | done 111 | 112 | saveddir=`pwd` 113 | 114 | M2_HOME=`dirname "$PRG"`/.. 115 | 116 | # make it fully qualified 117 | M2_HOME=`cd "$M2_HOME" && pwd` 118 | 119 | cd "$saveddir" 120 | # echo Using m2 at $M2_HOME 121 | fi 122 | 123 | # For Cygwin, ensure paths are in UNIX format before anything is touched 124 | if $cygwin ; then 125 | [ -n "$M2_HOME" ] && 126 | M2_HOME=`cygpath --unix "$M2_HOME"` 127 | [ -n "$JAVA_HOME" ] && 128 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 129 | [ -n "$CLASSPATH" ] && 130 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 131 | fi 132 | 133 | # For Migwn, ensure paths are in UNIX format before anything is touched 134 | if $mingw ; then 135 | [ -n "$M2_HOME" ] && 136 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 137 | [ -n "$JAVA_HOME" ] && 138 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 139 | # TODO classpath? 140 | fi 141 | 142 | if [ -z "$JAVA_HOME" ]; then 143 | javaExecutable="`which javac`" 144 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 145 | # readlink(1) is not available as standard on Solaris 10. 146 | readLink=`which readlink` 147 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 148 | if $darwin ; then 149 | javaHome="`dirname \"$javaExecutable\"`" 150 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 151 | else 152 | javaExecutable="`readlink -f \"$javaExecutable\"`" 153 | fi 154 | javaHome="`dirname \"$javaExecutable\"`" 155 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 156 | JAVA_HOME="$javaHome" 157 | export JAVA_HOME 158 | fi 159 | fi 160 | fi 161 | 162 | if [ -z "$JAVACMD" ] ; then 163 | if [ -n "$JAVA_HOME" ] ; then 164 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 165 | # IBM's JDK on AIX uses strange locations for the executables 166 | JAVACMD="$JAVA_HOME/jre/sh/java" 167 | else 168 | JAVACMD="$JAVA_HOME/bin/java" 169 | fi 170 | else 171 | JAVACMD="`which java`" 172 | fi 173 | fi 174 | 175 | if [ ! -x "$JAVACMD" ] ; then 176 | echo "Error: JAVA_HOME is not defined correctly." >&2 177 | echo " We cannot execute $JAVACMD" >&2 178 | exit 1 179 | fi 180 | 181 | if [ -z "$JAVA_HOME" ] ; then 182 | echo "Warning: JAVA_HOME environment variable is not set." 183 | fi 184 | 185 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 186 | 187 | # traverses directory structure from process work directory to filesystem root 188 | # first directory with .mvn subdirectory is considered project base directory 189 | find_maven_basedir() { 190 | local basedir=$(pwd) 191 | local wdir=$(pwd) 192 | while [ "$wdir" != '/' ] ; do 193 | if [ -d "$wdir"/.mvn ] ; then 194 | basedir=$wdir 195 | break 196 | fi 197 | wdir=$(cd "$wdir/.."; pwd) 198 | done 199 | echo "${basedir}" 200 | } 201 | 202 | # concatenates all lines of a file 203 | concat_lines() { 204 | if [ -f "$1" ]; then 205 | echo "$(tr -s '\n' ' ' < "$1")" 206 | fi 207 | } 208 | 209 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} 210 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 211 | 212 | # For Cygwin, switch paths to Windows format before running java 213 | if $cygwin; then 214 | [ -n "$M2_HOME" ] && 215 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 216 | [ -n "$JAVA_HOME" ] && 217 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 218 | [ -n "$CLASSPATH" ] && 219 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 220 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 221 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 222 | fi 223 | 224 | # Provide a "standardized" way to retrieve the CLI args that will 225 | # work with both Windows and non-Windows executions. 226 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 227 | export MAVEN_CMD_LINE_ARGS 228 | 229 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 230 | 231 | # avoid using MAVEN_CMD_LINE_ARGS below since that would loose parameter escaping in $@ 232 | exec "$JAVACMD" \ 233 | $MAVEN_OPTS \ 234 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 235 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 236 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 237 | -------------------------------------------------------------------------------- /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 | set MAVEN_CMD_LINE_ARGS=%MAVEN_CONFIG% %* 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | 121 | set WRAPPER_JAR=""%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"" 122 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 123 | 124 | # avoid using MAVEN_CMD_LINE_ARGS below since that would loose parameter escaping in %* 125 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 126 | if ERRORLEVEL 1 goto error 127 | goto end 128 | 129 | :error 130 | set ERROR_CODE=1 131 | 132 | :end 133 | @endlocal & set ERROR_CODE=%ERROR_CODE% 134 | 135 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 136 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 137 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 138 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 139 | :skipRcPost 140 | 141 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 142 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 143 | 144 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 145 | 146 | exit /B %ERROR_CODE% 147 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.github.vlsidlyarevich 7 | spring-boot-mongodb-jwt 8 | 0.0.1-SNAPSHOT 9 | jar 10 | Spring-Boot-MongoDB-JWT 11 | Base for Spring Boot projects with MongoDB and JWT authentication 12 | 13 | 14 | org.springframework.boot 15 | spring-boot-starter-parent 16 | 1.4.0.RELEASE 17 | 18 | 19 | 20 | com.github.vlsidlyarevich.Application 21 | 0.7.0 22 | 4.1 23 | 3.5 24 | 21.0 25 | 3.8 26 | 2.17 27 | 3.6.0 28 | UTF-8 29 | UTF-8 30 | 1.8 31 | 32 | 33 | 34 | 35 | test 36 | 37 | http://neo4j:test@localhost:7473 38 | false 39 | 40 | 41 | 42 | 43 | dev 44 | 45 | http://neo4j:unity@localhost:7474 46 | true 47 | 48 | 49 | true 50 | 51 | 52 | 53 | 54 | 55 | 56 | org.springframework.boot 57 | spring-boot-starter 58 | 59 | 60 | org.springframework.boot 61 | spring-boot-starter-web 62 | 63 | 64 | org.springframework.boot 65 | spring-boot-starter-data-mongodb 66 | 67 | 68 | org.springframework.boot 69 | spring-boot-starter-security 70 | 71 | 72 | org.springframework.boot 73 | spring-boot-starter-aop 74 | 75 | 76 | io.jsonwebtoken 77 | jjwt 78 | ${jjwt.version} 79 | 80 | 81 | org.springframework.boot 82 | spring-boot-configuration-processor 83 | true 84 | 85 | 86 | org.apache.commons 87 | commons-collections4 88 | ${commons-collections4.version} 89 | 90 | 91 | org.apache.commons 92 | commons-lang3 93 | ${commons-lang3.version} 94 | 95 | 96 | com.google.guava 97 | guava 98 | ${guava.version} 99 | 100 | 101 | org.springframework.boot 102 | spring-boot-starter-test 103 | test 104 | 105 | 106 | org.hamcrest 107 | hamcrest-library 108 | test 109 | 110 | 111 | junit 112 | junit 113 | test 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | org.springframework.boot 122 | spring-boot-maven-plugin 123 | 124 | 125 | 126 | 127 | org.apache.maven.plugins 128 | maven-compiler-plugin 129 | ${maven-compiler-plugin.version} 130 | 131 | ${java.version} 132 | ${java.version} 133 | 134 | 135 | 136 | 137 | 138 | org.apache.maven.plugins 139 | maven-surefire-plugin 140 | 141 | ${skip.test} 142 | 143 | 144 | 145 | 146 | 147 | org.apache.maven.plugins 148 | maven-pmd-plugin 149 | ${maven-pmd-plugin.version} 150 | 151 | 152 | build-tools/quality/pmd/pmd-ruleset.xml 153 | 154 | true 155 | 156 | 157 | 158 | 159 | check 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | org.apache.maven.plugins 168 | maven-checkstyle-plugin 169 | ${maven-checkstyle-plugin.version} 170 | 171 | build-tools/quality/checkstyle/checkstyle.xml 172 | build-tools/quality/checkstyle/checkstyle-suppress.xml 173 | 174 | 175 | 176 | 177 | check 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/Application.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | 7 | @SpringBootApplication 8 | public class Application { 9 | 10 | public static void main(final String[] args) { 11 | SpringApplication.run(Application.class, args); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/config/CorsFilter.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.config; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | import javax.servlet.Filter; 6 | import javax.servlet.FilterChain; 7 | import javax.servlet.FilterConfig; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.ServletRequest; 10 | import javax.servlet.ServletResponse; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | import java.io.IOException; 14 | 15 | 16 | @Component 17 | public class CorsFilter implements Filter { 18 | 19 | @Override 20 | public void init(final FilterConfig filterConfig) throws ServletException { 21 | 22 | } 23 | 24 | @Override 25 | public void doFilter(final ServletRequest req, final ServletResponse res, 26 | final FilterChain chain) throws IOException, ServletException { 27 | final HttpServletResponse response = (HttpServletResponse) res; 28 | response.setHeader("Access-Control-Allow-Origin", "*"); 29 | response.setHeader("Access-Control-Allow-Methods", 30 | "POST, GET, PUT, OPTIONS, DELETE, PATCH"); 31 | response.setHeader("Access-Control-Max-Age", "3600"); 32 | response.setHeader("Access-Control-Allow-Headers", "x-auth-token, Content-Type"); 33 | response.setHeader("Access-Control-Expose-Headers", "x-auth-token, Content-Type"); 34 | 35 | final HttpServletRequest request = (HttpServletRequest) req; 36 | 37 | if (request.getMethod().equals("OPTIONS")) { 38 | try { 39 | response.getWriter().print("OK"); 40 | response.getWriter().flush(); 41 | } catch (IOException e) { 42 | e.printStackTrace(); 43 | } 44 | } else { 45 | chain.doFilter(request, response); 46 | } 47 | } 48 | 49 | @Override 50 | public void destroy() { 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.config; 2 | 3 | import com.github.vlsidlyarevich.security.filter.AuthenticationTokenFilter; 4 | import com.github.vlsidlyarevich.security.service.TokenAuthenticationService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 7 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 8 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 9 | import org.springframework.security.config.http.SessionCreationPolicy; 10 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 11 | 12 | 13 | @EnableWebSecurity 14 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 15 | 16 | private final TokenAuthenticationService tokenAuthenticationService; 17 | 18 | @Autowired 19 | protected SecurityConfig(final TokenAuthenticationService tokenAuthenticationService) { 20 | super(); 21 | this.tokenAuthenticationService = tokenAuthenticationService; 22 | } 23 | 24 | @Override 25 | protected void configure(final HttpSecurity http) throws Exception { 26 | http.authorizeRequests() 27 | .antMatchers("/api/auth").permitAll() 28 | .antMatchers("/api/signup").permitAll() 29 | .anyRequest().authenticated() 30 | .and() 31 | .addFilterBefore(new AuthenticationTokenFilter(tokenAuthenticationService), 32 | UsernamePasswordAuthenticationFilter.class) 33 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 34 | .and() 35 | .csrf().disable(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/controller/AuthenticationController.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.controller; 2 | 3 | import com.github.vlsidlyarevich.dto.LoginDTO; 4 | import com.github.vlsidlyarevich.dto.TokenDTO; 5 | import com.github.vlsidlyarevich.security.service.TokenService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.RequestBody; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RequestMethod; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | 15 | @RestController 16 | @RequestMapping("/api/auth") 17 | public class AuthenticationController { 18 | 19 | private final TokenService tokenService; 20 | 21 | @Autowired 22 | public AuthenticationController(final TokenService tokenService) { 23 | this.tokenService = tokenService; 24 | } 25 | 26 | @RequestMapping(method = RequestMethod.POST) 27 | public ResponseEntity authenticate(@RequestBody final LoginDTO dto) { 28 | final String token = tokenService.getToken(dto.getUsername(), dto.getPassword()); 29 | if (token != null) { 30 | final TokenDTO response = new TokenDTO(); 31 | response.setToken(token); 32 | return new ResponseEntity<>(response, HttpStatus.OK); 33 | } else { 34 | return new ResponseEntity<>("Authentication failed", HttpStatus.BAD_REQUEST); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/controller/SecuredController.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.controller; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.http.ResponseEntity; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RequestMethod; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | 10 | @RestController 11 | @RequestMapping("/api/hello") 12 | public class SecuredController { 13 | 14 | @RequestMapping(method = RequestMethod.GET) 15 | public ResponseEntity sayHello() { 16 | return new ResponseEntity<>("Secured hello!", HttpStatus.OK); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/controller/SignUpController.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.controller; 2 | 3 | import com.github.vlsidlyarevich.converter.ConverterFacade; 4 | import com.github.vlsidlyarevich.dto.UserDTO; 5 | import com.github.vlsidlyarevich.service.UserService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.RequestBody; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RequestMethod; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | 15 | @RestController 16 | @RequestMapping("/api/signup") 17 | public class SignUpController { 18 | 19 | private final UserService service; 20 | 21 | private final ConverterFacade converterFacade; 22 | 23 | @Autowired 24 | public SignUpController(final UserService service, 25 | final ConverterFacade converterFacade) { 26 | this.service = service; 27 | this.converterFacade = converterFacade; 28 | } 29 | 30 | @RequestMapping(method = RequestMethod.POST) 31 | public ResponseEntity signUp(@RequestBody final UserDTO dto) { 32 | return new ResponseEntity<>(service.create(converterFacade.convert(dto)), HttpStatus.OK); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/converter/ConverterFacade.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.converter; 2 | 3 | import com.github.vlsidlyarevich.converter.factory.ConverterFactory; 4 | import com.github.vlsidlyarevich.dto.UserDTO; 5 | import com.github.vlsidlyarevich.model.User; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Component; 8 | 9 | 10 | @Component 11 | public class ConverterFacade { 12 | 13 | @Autowired 14 | private ConverterFactory converterFactory; 15 | 16 | public User convert(final UserDTO dto) { 17 | return (User) converterFactory.getConverter(dto.getClass()).convert(dto); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/converter/dto/UserDTOConverter.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.converter.dto; 2 | 3 | import com.github.vlsidlyarevich.dto.UserDTO; 4 | import com.github.vlsidlyarevich.model.Authority; 5 | import com.github.vlsidlyarevich.model.User; 6 | import org.springframework.core.convert.converter.Converter; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | 12 | public class UserDTOConverter implements Converter { 13 | 14 | @Override 15 | public User convert(final UserDTO dto) { 16 | final User user = new User(); 17 | 18 | user.setUsername(dto.getUsername()); 19 | user.setPassword(dto.getPassword()); 20 | user.setAccountNonExpired(false); 21 | user.setCredentialsNonExpired(false); 22 | user.setEnabled(true); 23 | 24 | List authorities = new ArrayList<>(); 25 | authorities.add(Authority.ROLE_USER); 26 | user.setAuthorities(authorities); 27 | return user; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/converter/factory/ConverterFactory.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.converter.factory; 2 | 3 | import com.github.vlsidlyarevich.converter.dto.UserDTOConverter; 4 | import com.github.vlsidlyarevich.dto.UserDTO; 5 | import org.springframework.core.convert.converter.Converter; 6 | import org.springframework.stereotype.Component; 7 | 8 | import javax.annotation.PostConstruct; 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | 13 | @Component 14 | public class ConverterFactory { 15 | 16 | private Map converters; 17 | 18 | public ConverterFactory() { 19 | 20 | } 21 | 22 | @PostConstruct 23 | public void init() { 24 | converters = new HashMap<>(); 25 | converters.put(UserDTO.class, new UserDTOConverter()); 26 | } 27 | 28 | public Converter getConverter(final Object type) { 29 | return converters.get(type); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/dto/LoginDTO.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.dto; 2 | 3 | import java.io.Serializable; 4 | 5 | 6 | public class LoginDTO implements Serializable { 7 | 8 | private static final long serialVersionUID = -4159366809929151486L; 9 | 10 | private String username; 11 | private String password; 12 | 13 | public LoginDTO() { 14 | } 15 | 16 | public String getUsername() { 17 | return username; 18 | } 19 | 20 | public void setUsername(final String username) { 21 | this.username = username; 22 | } 23 | 24 | public String getPassword() { 25 | return password; 26 | } 27 | 28 | public void setPassword(final String password) { 29 | this.password = password; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/dto/TokenDTO.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.dto; 2 | 3 | import java.io.Serializable; 4 | 5 | 6 | public class TokenDTO implements Serializable { 7 | 8 | private static final long serialVersionUID = 6710061358371752955L; 9 | 10 | private String token; 11 | 12 | public TokenDTO() { 13 | } 14 | 15 | public String getToken() { 16 | return token; 17 | } 18 | 19 | public void setToken(final String token) { 20 | this.token = token; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/dto/UserDTO.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.dto; 2 | 3 | import java.io.Serializable; 4 | 5 | 6 | public class UserDTO implements Serializable { 7 | 8 | private static final long serialVersionUID = 91901774547107674L; 9 | 10 | private String username; 11 | private String password; 12 | 13 | public UserDTO() { 14 | } 15 | 16 | public String getUsername() { 17 | return username; 18 | } 19 | 20 | public void setUsername(final String username) { 21 | this.username = username; 22 | } 23 | 24 | public String getPassword() { 25 | return password; 26 | } 27 | 28 | public void setPassword(final String password) { 29 | this.password = password; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/exception/handler/CustomExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.exception.handler; 2 | 3 | import com.github.vlsidlyarevich.exception.model.ServiceException; 4 | import com.github.vlsidlyarevich.exception.model.UserNotFoundException; 5 | import com.mongodb.MongoException; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.web.bind.annotation.ControllerAdvice; 11 | import org.springframework.web.bind.annotation.ExceptionHandler; 12 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 13 | 14 | 15 | @ControllerAdvice 16 | public class CustomExceptionHandler extends ResponseEntityExceptionHandler { 17 | 18 | private final Logger log = LoggerFactory.getLogger(CustomExceptionHandler.class); 19 | 20 | @ExceptionHandler(MongoException.class) 21 | public ResponseEntity handleMongoException(final MongoException exception) { 22 | log.warn("Processing mongo exception: {}", exception.getMessage()); 23 | 24 | return new ResponseEntity<>(exception.getLocalizedMessage(), HttpStatus.BAD_REQUEST); 25 | } 26 | 27 | @ExceptionHandler(ServiceException.class) 28 | public ResponseEntity handleServiceException(final ServiceException exception) { 29 | log.warn("Processing service exception: {}", exception.getMessage()); 30 | 31 | return new ResponseEntity<>(exception.getLocalizedMessage(), HttpStatus.BAD_REQUEST); 32 | } 33 | 34 | @ExceptionHandler(UserNotFoundException.class) 35 | public ResponseEntity handleUserNotFoundException(final UserNotFoundException exception) { 36 | log.warn("Processing user not found exception: {}", exception.getMessage()); 37 | 38 | return new ResponseEntity<>(exception.getLocalizedMessage(), HttpStatus.BAD_REQUEST); 39 | } 40 | 41 | @ExceptionHandler(Exception.class) 42 | public ResponseEntity handleAbstractException(final Exception exception) { 43 | log.warn("Processing abstract exception: {}", exception.getMessage()); 44 | 45 | return new ResponseEntity<>(exception.getLocalizedMessage(), HttpStatus.BAD_REQUEST); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/exception/model/ServiceException.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.exception.model; 2 | 3 | 4 | public class ServiceException extends RuntimeException { 5 | 6 | private static final long serialVersionUID = -8658131859261427602L; 7 | 8 | private String service; 9 | 10 | public ServiceException(final String service) { 11 | super(); 12 | this.service = service; 13 | } 14 | 15 | public ServiceException(final String message, final String service) { 16 | super(message); 17 | this.service = service; 18 | } 19 | 20 | public ServiceException(final String message, final Throwable cause, 21 | final String service) { 22 | super(message, cause); 23 | this.service = service; 24 | } 25 | 26 | public String getService() { 27 | return service; 28 | } 29 | 30 | public void setService(final String service) { 31 | this.service = service; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/exception/model/UserNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.exception.model; 2 | 3 | 4 | public class UserNotFoundException extends RuntimeException { 5 | 6 | private static final long serialVersionUID = 2967357473314163159L; 7 | 8 | public UserNotFoundException() { 9 | super(); 10 | } 11 | 12 | public UserNotFoundException(final String message) { 13 | super(message); 14 | } 15 | 16 | public UserNotFoundException(final String message, final Throwable cause) { 17 | super(message, cause); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/model/Authority.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.model; 2 | 3 | import org.springframework.security.core.GrantedAuthority; 4 | 5 | 6 | public enum Authority implements GrantedAuthority { 7 | ROLE_USER, 8 | ROLE_ADMIN, 9 | ANONYMOUS; 10 | 11 | @Override 12 | public String getAuthority() { 13 | return this.name(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/model/BaseEntity.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.model; 2 | 3 | import org.springframework.data.annotation.Id; 4 | import org.springframework.data.mongodb.core.mapping.Document; 5 | 6 | import java.io.Serializable; 7 | 8 | 9 | @Document 10 | public class BaseEntity implements Serializable { 11 | 12 | private static final long serialVersionUID = 8571261118900116242L; 13 | 14 | @Id 15 | private String id; 16 | private String createdAt; 17 | private String updatedAt; 18 | 19 | public BaseEntity() { 20 | } 21 | 22 | public String getId() { 23 | return id; 24 | } 25 | 26 | public void setId(final String id) { 27 | this.id = id; 28 | } 29 | 30 | public String getCreatedAt() { 31 | return createdAt; 32 | } 33 | 34 | public void setCreatedAt(final String createdAt) { 35 | this.createdAt = createdAt; 36 | } 37 | 38 | public String getUpdatedAt() { 39 | return updatedAt; 40 | } 41 | 42 | public void setUpdatedAt(final String updatedAt) { 43 | this.updatedAt = updatedAt; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/model/User.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.model; 2 | 3 | import org.springframework.security.core.GrantedAuthority; 4 | import org.springframework.security.core.userdetails.UserDetails; 5 | 6 | import java.util.Collection; 7 | import java.util.List; 8 | 9 | 10 | public class User extends BaseEntity implements UserDetails { 11 | 12 | private static final long serialVersionUID = 7954325925563724664L; 13 | 14 | private List authorities; 15 | private String username; 16 | private String password; 17 | private boolean accountNonExpired; 18 | private boolean accountNonLocked; 19 | private boolean credentialsNonExpired; 20 | private boolean isEnabled; 21 | 22 | @Override 23 | public Collection getAuthorities() { 24 | return authorities; 25 | } 26 | 27 | @Override 28 | public String getPassword() { 29 | return password; 30 | } 31 | 32 | @Override 33 | public String getUsername() { 34 | return username; 35 | } 36 | 37 | @Override 38 | public boolean isAccountNonExpired() { 39 | return accountNonExpired; 40 | } 41 | 42 | @Override 43 | public boolean isAccountNonLocked() { 44 | return accountNonLocked; 45 | } 46 | 47 | @Override 48 | public boolean isCredentialsNonExpired() { 49 | return credentialsNonExpired; 50 | } 51 | 52 | @Override 53 | public boolean isEnabled() { 54 | return isEnabled; 55 | } 56 | 57 | public void setAuthorities(final List authorities) { 58 | this.authorities = authorities; 59 | } 60 | 61 | public void setUsername(final String username) { 62 | this.username = username; 63 | } 64 | 65 | public void setPassword(final String password) { 66 | this.password = password; 67 | } 68 | 69 | public void setAccountNonExpired(final boolean accountNonExpired) { 70 | this.accountNonExpired = accountNonExpired; 71 | } 72 | 73 | public void setAccountNonLocked(final boolean accountNonLocked) { 74 | this.accountNonLocked = accountNonLocked; 75 | } 76 | 77 | public void setCredentialsNonExpired(final boolean credentialsNonExpired) { 78 | this.credentialsNonExpired = credentialsNonExpired; 79 | } 80 | 81 | public void setEnabled(final boolean enabled) { 82 | isEnabled = enabled; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/model/UserAuthentication.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.model; 2 | 3 | import org.springframework.security.core.Authentication; 4 | import org.springframework.security.core.GrantedAuthority; 5 | 6 | import java.util.Collection; 7 | 8 | 9 | public class UserAuthentication implements Authentication { 10 | 11 | private static final long serialVersionUID = -7170337143687707450L; 12 | 13 | private final User user; 14 | private boolean authenticated = true; 15 | 16 | public UserAuthentication(final User user) { 17 | this.user = user; 18 | } 19 | 20 | @Override 21 | public Collection getAuthorities() { 22 | return user.getAuthorities(); 23 | } 24 | 25 | @Override 26 | public Object getCredentials() { 27 | return user.getPassword(); 28 | } 29 | 30 | @Override 31 | public Object getDetails() { 32 | return user; 33 | } 34 | 35 | @Override 36 | public Object getPrincipal() { 37 | return user.getUsername(); 38 | } 39 | 40 | @Override 41 | public boolean isAuthenticated() { 42 | return authenticated; 43 | } 44 | 45 | @Override 46 | public void setAuthenticated(final boolean authenticated) throws IllegalArgumentException { 47 | this.authenticated = authenticated; 48 | } 49 | 50 | @Override 51 | public String getName() { 52 | return user.getUsername(); 53 | } 54 | 55 | public User getUser() { 56 | return user; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.repository; 2 | 3 | import com.github.vlsidlyarevich.model.User; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | 8 | @Repository 9 | public interface UserRepository extends MongoRepository { 10 | 11 | User findByUsername(final String userName); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/security/RestAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.security; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | import org.springframework.security.web.AuthenticationEntryPoint; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.servlet.ServletException; 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | import java.io.IOException; 11 | 12 | 13 | @Component 14 | public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { 15 | 16 | @Override 17 | public void commence(final HttpServletRequest request, 18 | final HttpServletResponse response, 19 | final AuthenticationException e) 20 | throws IOException, ServletException { 21 | response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/security/constants/SecurityConstants.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.security.constants; 2 | 3 | 4 | public final class SecurityConstants { 5 | 6 | public static final String AUTH_HEADER_NAME = "x-auth-token"; 7 | 8 | private SecurityConstants() { 9 | 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/security/filter/AuthenticationTokenFilter.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.security.filter; 2 | 3 | import com.github.vlsidlyarevich.security.service.TokenAuthenticationService; 4 | import org.springframework.security.core.Authentication; 5 | import org.springframework.security.core.context.SecurityContextHolder; 6 | import org.springframework.web.filter.GenericFilterBean; 7 | 8 | import javax.servlet.FilterChain; 9 | import javax.servlet.ServletException; 10 | import javax.servlet.ServletRequest; 11 | import javax.servlet.ServletResponse; 12 | import javax.servlet.http.HttpServletRequest; 13 | import java.io.IOException; 14 | 15 | 16 | public class AuthenticationTokenFilter extends GenericFilterBean { 17 | 18 | private final TokenAuthenticationService authenticationService; 19 | 20 | public AuthenticationTokenFilter(final TokenAuthenticationService authenticationService) { 21 | this.authenticationService = authenticationService; 22 | } 23 | 24 | @Override 25 | public void doFilter(final ServletRequest request, final ServletResponse response, 26 | final FilterChain filterChain) 27 | throws IOException, ServletException { 28 | final HttpServletRequest httpRequest = (HttpServletRequest) request; 29 | final Authentication authentication = authenticationService.authenticate(httpRequest); 30 | SecurityContextHolder.getContext().setAuthentication(authentication); 31 | filterChain.doFilter(request, response); 32 | SecurityContextHolder.getContext().setAuthentication(null); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/security/service/BasicUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.security.service; 2 | 3 | import com.github.vlsidlyarevich.model.User; 4 | import com.github.vlsidlyarevich.service.UserService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | import org.springframework.security.core.userdetails.UserDetailsService; 8 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 9 | import org.springframework.stereotype.Service; 10 | 11 | 12 | @Service 13 | public class BasicUserDetailsService implements UserDetailsService { 14 | 15 | private final UserService userService; 16 | 17 | @Autowired 18 | public BasicUserDetailsService(final UserService userService) { 19 | this.userService = userService; 20 | } 21 | 22 | @Override 23 | public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { 24 | final User user = userService.findByUsername(username); 25 | if (user != null) { 26 | return user; 27 | } else { 28 | throw new UsernameNotFoundException("User with username:" + username + " not found"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/security/service/JsonWebTokenAuthenticationService.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.security.service; 2 | 3 | import com.github.vlsidlyarevich.exception.model.UserNotFoundException; 4 | import com.github.vlsidlyarevich.model.User; 5 | import com.github.vlsidlyarevich.model.UserAuthentication; 6 | import com.github.vlsidlyarevich.security.constants.SecurityConstants; 7 | import io.jsonwebtoken.Claims; 8 | import io.jsonwebtoken.ExpiredJwtException; 9 | import io.jsonwebtoken.Jws; 10 | import io.jsonwebtoken.Jwts; 11 | import io.jsonwebtoken.MalformedJwtException; 12 | import io.jsonwebtoken.SignatureException; 13 | import io.jsonwebtoken.UnsupportedJwtException; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.beans.factory.annotation.Value; 16 | import org.springframework.security.core.Authentication; 17 | import org.springframework.security.core.userdetails.UserDetailsService; 18 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 19 | import org.springframework.stereotype.Service; 20 | 21 | import javax.servlet.http.HttpServletRequest; 22 | 23 | 24 | @Service 25 | public class JsonWebTokenAuthenticationService implements TokenAuthenticationService { 26 | 27 | @Value("${security.token.secret.key}") 28 | private String secretKey; 29 | 30 | private final UserDetailsService userDetailsService; 31 | 32 | @Autowired 33 | public JsonWebTokenAuthenticationService(final UserDetailsService userDetailsService) { 34 | this.userDetailsService = userDetailsService; 35 | } 36 | 37 | @Override 38 | public Authentication authenticate(final HttpServletRequest request) { 39 | final String token = request.getHeader(SecurityConstants.AUTH_HEADER_NAME); 40 | final Jws tokenData = parseToken(token); 41 | if (tokenData != null) { 42 | User user = getUserFromToken(tokenData); 43 | if (user != null) { 44 | return new UserAuthentication(user); 45 | } 46 | } 47 | return null; 48 | } 49 | 50 | private Jws parseToken(final String token) { 51 | if (token != null) { 52 | try { 53 | return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); 54 | } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException 55 | | SignatureException | IllegalArgumentException e) { 56 | return null; 57 | } 58 | } 59 | return null; 60 | } 61 | 62 | private User getUserFromToken(final Jws tokenData) { 63 | try { 64 | return (User) userDetailsService 65 | .loadUserByUsername(tokenData.getBody().get("username").toString()); 66 | } catch (UsernameNotFoundException e) { 67 | throw new UserNotFoundException("User " 68 | + tokenData.getBody().get("username").toString() + " not found"); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/security/service/JsonWebTokenService.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.security.service; 2 | 3 | import com.github.vlsidlyarevich.exception.model.ServiceException; 4 | import com.github.vlsidlyarevich.model.User; 5 | import io.jsonwebtoken.JwtBuilder; 6 | import io.jsonwebtoken.Jwts; 7 | import io.jsonwebtoken.SignatureAlgorithm; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.security.core.userdetails.UserDetailsService; 11 | import org.springframework.stereotype.Service; 12 | 13 | import java.time.LocalDateTime; 14 | import java.util.Calendar; 15 | import java.util.HashMap; 16 | import java.util.Map; 17 | 18 | 19 | @Service 20 | public class JsonWebTokenService implements TokenService { 21 | 22 | private static int tokenExpirationTime = 30; 23 | 24 | @Value("${security.token.secret.key}") 25 | private String tokenKey; 26 | 27 | private final UserDetailsService userDetailsService; 28 | 29 | @Autowired 30 | public JsonWebTokenService(final UserDetailsService userDetailsService) { 31 | this.userDetailsService = userDetailsService; 32 | } 33 | 34 | @Override 35 | public String getToken(final String username, final String password) { 36 | if (username == null || password == null) { 37 | return null; 38 | } 39 | final User user = (User) userDetailsService.loadUserByUsername(username); 40 | Map tokenData = new HashMap<>(); 41 | if (password.equals(user.getPassword())) { 42 | tokenData.put("clientType", "user"); 43 | tokenData.put("userID", user.getId()); 44 | tokenData.put("username", user.getUsername()); 45 | tokenData.put("token_create_date", LocalDateTime.now()); 46 | Calendar calendar = Calendar.getInstance(); 47 | calendar.add(Calendar.MINUTE, tokenExpirationTime); 48 | tokenData.put("token_expiration_date", calendar.getTime()); 49 | JwtBuilder jwtBuilder = Jwts.builder(); 50 | jwtBuilder.setExpiration(calendar.getTime()); 51 | jwtBuilder.setClaims(tokenData); 52 | return jwtBuilder.signWith(SignatureAlgorithm.HS512, tokenKey).compact(); 53 | 54 | } else { 55 | throw new ServiceException("Authentication error", this.getClass().getName()); 56 | } 57 | } 58 | 59 | public static void setTokenExpirationTime(final int tokenExpirationTime) { 60 | JsonWebTokenService.tokenExpirationTime = tokenExpirationTime; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/security/service/TokenAuthenticationService.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.security.service; 2 | 3 | import org.springframework.security.core.Authentication; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | 7 | 8 | public interface TokenAuthenticationService { 9 | 10 | Authentication authenticate(HttpServletRequest request); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/security/service/TokenService.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.security.service; 2 | 3 | 4 | public interface TokenService { 5 | 6 | String getToken(String username, String password); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/service/BasicUserService.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.service; 2 | 3 | import com.github.vlsidlyarevich.model.User; 4 | import com.github.vlsidlyarevich.repository.UserRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | import java.time.LocalDateTime; 9 | import java.util.List; 10 | 11 | 12 | @Service 13 | public class BasicUserService implements UserService { 14 | 15 | private final UserRepository repository; 16 | 17 | @Autowired 18 | public BasicUserService(final UserRepository repository) { 19 | this.repository = repository; 20 | } 21 | 22 | @Override 23 | public User create(final User user) { 24 | user.setCreatedAt(String.valueOf(LocalDateTime.now())); 25 | return repository.save(user); 26 | } 27 | 28 | @Override 29 | public User find(final String id) { 30 | return repository.findOne(id); 31 | } 32 | 33 | @Override 34 | public User findByUsername(final String userName) { 35 | return repository.findByUsername(userName); 36 | } 37 | 38 | @Override 39 | public List findAll() { 40 | return repository.findAll(); 41 | } 42 | 43 | @Override 44 | public User update(final String id, final User user) { 45 | user.setId(id); 46 | 47 | final User saved = repository.findOne(id); 48 | 49 | if (saved != null) { 50 | user.setCreatedAt(saved.getCreatedAt()); 51 | user.setUpdatedAt(String.valueOf(LocalDateTime.now())); 52 | } else { 53 | user.setCreatedAt(String.valueOf(LocalDateTime.now())); 54 | } 55 | repository.save(user); 56 | return user; 57 | } 58 | 59 | @Override 60 | public String delete(final String id) { 61 | repository.delete(id); 62 | return id; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/github/vlsidlyarevich/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.github.vlsidlyarevich.service; 2 | 3 | import com.github.vlsidlyarevich.model.User; 4 | 5 | import java.util.List; 6 | 7 | 8 | public interface UserService { 9 | 10 | User create(User object); 11 | 12 | User find(String id); 13 | 14 | User findByUsername(String userName); 15 | 16 | List findAll(); 17 | 18 | User update(String id, User object); 19 | 20 | String delete(String id); 21 | } 22 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.data.mongodb.host=localhost 2 | spring.data.mongodb.port=27017 3 | spring.data.mongodb.database=project 4 | security.token.secret.key=Asjfwol2asf123142Ags1k23hnSA36as6f4qQ324FEsvb 5 | server.port=8080 6 | -------------------------------------------------------------------------------- /src/test/resourсes/application.properties: -------------------------------------------------------------------------------- 1 | spring.data.mongodb.host=localhost 2 | spring.data.mongodb.port=27017 3 | spring.data.mongodb.database=project-test 4 | server.port=8080 5 | 6 | storage.path=../temp/test-files --------------------------------------------------------------------------------