├── .github └── workflows │ └── publish.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── docker-compose.yml ├── local-docker-compose.yml ├── pom.xml └── src └── main ├── java └── com │ └── farukgenc │ └── boilerplate │ └── springboot │ ├── SpringBootBoilerplateApplication.java │ ├── configuration │ ├── MessageConfiguration.java │ ├── PasswordEncoderConfiguration.java │ ├── SecurityConfiguration.java │ └── SwaggerConfiguration.java │ ├── controller │ ├── HelloController.java │ ├── LoginController.java │ └── RegistrationController.java │ ├── exceptions │ ├── ApiExceptionResponse.java │ ├── LoginControllerAdvice.java │ ├── RegistrationControllerAdvice.java │ ├── RegistrationException.java │ ├── ValidationAdvice.java │ └── ValidationErrorResponse.java │ ├── model │ ├── User.java │ └── UserRole.java │ ├── repository │ └── UserRepository.java │ ├── security │ ├── dto │ │ ├── AuthenticatedUserDto.java │ │ ├── LoginRequest.java │ │ ├── LoginResponse.java │ │ ├── RegistrationRequest.java │ │ └── RegistrationResponse.java │ ├── jwt │ │ ├── JwtAuthenticationEntryPoint.java │ │ ├── JwtAuthenticationFilter.java │ │ ├── JwtProperties.java │ │ ├── JwtTokenManager.java │ │ └── JwtTokenService.java │ ├── mapper │ │ └── UserMapper.java │ ├── service │ │ ├── UserDetailsServiceImpl.java │ │ ├── UserService.java │ │ └── UserServiceImpl.java │ └── utils │ │ └── SecurityConstants.java │ ├── service │ └── UserValidationService.java │ └── utils │ ├── ExceptionMessageAccessor.java │ ├── GeneralMessageAccessor.java │ └── ProjectConstants.java └── resources ├── application.yml ├── banner.txt └── messages ├── exception ├── ExceptionMessages.properties └── ExceptionMessages_tr.properties ├── general ├── GeneralMessages.properties └── GeneralMessages_tr.properties └── validation ├── ValidationMessages.properties └── ValidationMessages_tr.properties /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Build Maven Package And Publish Docker Image 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v3 15 | - name: Set up JDK 17 16 | uses: actions/setup-java@v3 17 | with: 18 | java-version: '17' 19 | distribution: 'temurin' 20 | 21 | - name: Build with Maven 22 | run: mvn -B package --file pom.xml 23 | 24 | - name: Extract Project Version 25 | run: echo "version=$(mvn -q -Dexec.executable=echo -Dexec.args='${project.version}' --non-recursive exec:exec)" >> $GITHUB_OUTPUT 26 | id: project 27 | 28 | - name: Show Project version 29 | run: echo ${{steps.project.outputs.version}} 30 | 31 | - name: Set up QEMU 32 | uses: docker/setup-qemu-action@v2 33 | 34 | - name: Set up Docker Buildx 35 | uses: docker/setup-buildx-action@v2 36 | 37 | - name: Login to Docker Hub 38 | uses: docker/login-action@v2 39 | with: 40 | username: ${{ secrets.DOCKER_USERNAME }} 41 | password: ${{ secrets.DOCKER_TOKEN }} 42 | 43 | - name: Build and push docker image 44 | uses: docker/build-push-action@v4 45 | with: 46 | context: . 47 | push: true 48 | tags: | 49 | omerfarukgenc34/spring-boot-boilerplate:${{steps.project.outputs.version}} 50 | omerfarukgenc34/spring-boot-boilerplate:latest 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM eclipse-temurin:17 2 | WORKDIR app 3 | ARG JAR_FILE=target/*.jar 4 | COPY ${JAR_FILE} spring-boot-boilerplate.jar 5 | EXPOSE 8080 6 | ENTRYPOINT ["java","-jar","spring-boot-boilerplate.jar"] -------------------------------------------------------------------------------- /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 Boilerplate 2 | *Spring Boot Boilerplate* is a **starter kit**. This project is a very simple and useful. 3 | 4 | ## Technologies 5 | - Spring Boot (v3.4.0) 6 | - Spring Data JPA 7 | - Spring Validation 8 | - Spring Security + JWT Token 9 | - PostgreSQL 10 | - Mapstruct 11 | - Lombok 12 | - Swagger (Open API) 13 | 14 | ## Customization 15 | 16 | - You can customize ```token information (secret key, issuer, expiry date) ``` in [*application.yml*](https://github.com/Genc/spring-boot-boilerplate/blob/master/src/main/resources/application.yml#L40) file. 17 | - You can customize ```database connection information``` in [*application.yml*](https://github.com/Genc/spring-boot-boilerplate/blob/master/src/main/resources/application.yml#L3) file. 18 | - You can customize ```swagger information``` in [*application.yml*](https://github.com/Genc/spring-boot-boilerplate/blob/master/src/main/resources/application.yml#L45) file. 19 | - You can customize ```which endpoints are accessible without token information``` in [*SecurityConfiguration.java*](https://github.com/Genc/spring-boot-boilerplate/blob/master/src/main/java/com/farukgenc/boilerplate/springboot/configuration/SecurityConfiguration.java#L45) file. 20 | 21 | ## Run the Application 22 | 23 | First you need to make sure that the database is up. 24 | If you're using Docker, you can use ```docker compose up -d``` command. (If you have made changes in local, you should use the *local-docker-compose* file.) 25 | 26 | Navigate to the root of the project. For building the project using command line, run below command : 27 | 28 | ``` mvn clean install``` 29 | 30 | Run service in command line. Navigate to *target* directory. 31 | 32 | ``` java -jar spring-boot-boilerplate.jar ``` 33 | 34 | ## Postman Collection 35 | 36 | - [You can access the Postman collection here and you can try it after you get the project up and running.](https://www.postman.com/postmanfaruk/workspace/faruk-genc-projects/collection/11439300-3d0317df-f217-40ff-a2a6-4eaaf66e1c55?action=share&creator=11439300) 37 | 38 | ### Others 39 | 40 | - [For Angular] 41 | 42 | ### License 43 | 44 | Apache License 2.0 45 | 46 | [For Angular]: 47 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | 3 | db: 4 | container_name: db 5 | image: postgres 6 | restart: always 7 | ports: 8 | - "5432:5432" 9 | environment: 10 | POSTGRES_PASSWORD: example 11 | healthcheck: 12 | test: ["CMD-SHELL", "pg_isready -U postgres"] 13 | interval: 10s 14 | timeout: 5s 15 | retries: 5 16 | 17 | app: 18 | container_name: app 19 | image: omerfarukgenc34/spring-boot-boilerplate:3.4.0 20 | ports: 21 | - "8080:8080" 22 | environment: 23 | - "POSTGRES_DB_SERVER_ADDRESS=db" 24 | - "POSTGRES_DB_SERVER_PORT=5432" 25 | - "POSTGRES_USER=postgres" 26 | - "POSTGRES_PASSWORD=example" 27 | healthcheck: 28 | test: "curl --fail --silent localhost:8080/actuator/health/readiness | grep UP || exit 1" 29 | interval: 2s 30 | timeout: 3s 31 | retries: 5 32 | start_period: 2s 33 | depends_on: 34 | db: 35 | condition: service_healthy 36 | -------------------------------------------------------------------------------- /local-docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | 3 | db: 4 | container_name: db 5 | image: postgres 6 | restart: always 7 | ports: 8 | - "5432:5432" 9 | environment: 10 | POSTGRES_PASSWORD: example 11 | healthcheck: 12 | test: ["CMD-SHELL", "pg_isready -U postgres"] 13 | interval: 10s 14 | timeout: 5s 15 | retries: 5 16 | 17 | app: 18 | container_name: app 19 | build: . 20 | ports: 21 | - "8080:8080" 22 | environment: 23 | - "POSTGRES_DB_SERVER_ADDRESS=db" 24 | - "POSTGRES_DB_SERVER_PORT=5432" 25 | - "POSTGRES_USER=postgres" 26 | - "POSTGRES_PASSWORD=example" 27 | healthcheck: 28 | test: "curl --fail --silent localhost:8080/actuator/health/readiness | grep UP || exit 1" 29 | interval: 2s 30 | timeout: 3s 31 | retries: 5 32 | start_period: 2s 33 | depends_on: 34 | db: 35 | condition: service_healthy 36 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | 7 | org.springframework.boot 8 | spring-boot-starter-parent 9 | 3.4.0 10 | 11 | 12 | com.farukgenc 13 | springboot-boilerplate 14 | 3.4.0 15 | 16 | spring-boot-boilerplate 17 | 18 | Spring Boot Boilerplate is a starter kit. 19 | This project includes : Spring Boot(3.4.0), Spring Data JPA, Spring Validation, Spring Security + JWT Token, PostgreSQL, Mapstruct, Lombok, Swagger (Open API) 20 | 21 | 22 | 23 | 24 | Faruk Genc 25 | omer@farukgenc.com 26 | https://farukgenc.com 27 | 28 | 29 | 30 | 31 | 32 | 17 33 | 4.4.0 34 | 35 | 2.7.0 36 | 37 | 1.6.3 38 | 0.2.0 39 | 40 | 41 | 42 | 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-web 47 | 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-data-jpa 52 | 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-starter-validation 57 | 58 | 59 | 60 | org.springframework.boot 61 | spring-boot-starter-security 62 | 63 | 64 | 65 | org.springframework.boot 66 | spring-boot-starter-actuator 67 | 68 | 69 | 70 | com.auth0 71 | java-jwt 72 | ${jwt.version} 73 | 74 | 75 | 76 | org.postgresql 77 | postgresql 78 | runtime 79 | 80 | 81 | 82 | org.mapstruct 83 | mapstruct 84 | ${mapstruct.version} 85 | 86 | 87 | 88 | org.mapstruct 89 | mapstruct-processor 90 | ${mapstruct.version} 91 | 92 | 93 | 94 | org.projectlombok 95 | lombok 96 | provided 97 | 98 | 99 | 100 | org.projectlombok 101 | lombok-mapstruct-binding 102 | ${lombok-mapstruct-binding.version} 103 | 104 | 105 | 106 | org.springdoc 107 | springdoc-openapi-starter-webmvc-ui 108 | ${openapi-swagger.version} 109 | 110 | 111 | 112 | org.springframework.boot 113 | spring-boot-starter-test 114 | test 115 | 116 | 117 | 118 | 119 | 120 | 121 | spring-boot-boilerplate 122 | 123 | 124 | 125 | 126 | org.springframework.boot 127 | spring-boot-maven-plugin 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/SpringBootBoilerplateApplication.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.EnableAspectJAutoProxy; 6 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 7 | 8 | @SpringBootApplication 9 | @EnableJpaRepositories 10 | @EnableAspectJAutoProxy 11 | public class SpringBootBoilerplateApplication { 12 | 13 | public static void main(String[] args) { 14 | 15 | SpringApplication.run(SpringBootBoilerplateApplication.class, args); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/configuration/MessageConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.configuration; 2 | 3 | import com.farukgenc.boilerplate.springboot.utils.ProjectConstants; 4 | import org.springframework.context.MessageSource; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.context.support.ReloadableResourceBundleMessageSource; 8 | import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; 9 | 10 | /** 11 | * Created on Ağustos, 2020 12 | * 13 | * @author Faruk 14 | */ 15 | @Configuration 16 | public class MessageConfiguration { 17 | 18 | @Bean 19 | MessageSource generalMessageSource() { 20 | 21 | final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 22 | messageSource.setBasename("classpath:/messages/general/GeneralMessages"); 23 | messageSource.setDefaultEncoding(ProjectConstants.DEFAULT_ENCODING); 24 | 25 | return messageSource; 26 | } 27 | 28 | @Bean 29 | MessageSource exceptionMessageSource() { 30 | 31 | final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 32 | messageSource.setBasename("classpath:/messages/exception/ExceptionMessages"); 33 | messageSource.setDefaultEncoding(ProjectConstants.DEFAULT_ENCODING); 34 | 35 | return messageSource; 36 | } 37 | 38 | @Bean 39 | public MessageSource validationMessageSource() { 40 | 41 | final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 42 | messageSource.setBasename("classpath:/messages/validation/ValidationMessages"); 43 | messageSource.setDefaultEncoding(ProjectConstants.DEFAULT_ENCODING); 44 | 45 | return messageSource; 46 | } 47 | 48 | @Bean 49 | public LocalValidatorFactoryBean getValidator() { 50 | 51 | final LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean(); 52 | bean.setValidationMessageSource(validationMessageSource()); 53 | 54 | return bean; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/configuration/PasswordEncoderConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.configuration; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 6 | 7 | /** 8 | * Created on March, 2023 9 | * 10 | * @author Faruk 11 | */ 12 | 13 | @Configuration 14 | public class PasswordEncoderConfiguration { 15 | 16 | @Bean 17 | public BCryptPasswordEncoder encoder() { 18 | return new BCryptPasswordEncoder(); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/configuration/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.configuration; 2 | 3 | import com.farukgenc.boilerplate.springboot.security.jwt.JwtAuthenticationEntryPoint; 4 | import com.farukgenc.boilerplate.springboot.security.jwt.JwtAuthenticationFilter; 5 | import lombok.RequiredArgsConstructor; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.security.authentication.AuthenticationManager; 9 | import org.springframework.security.config.Customizer; 10 | import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; 11 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 12 | import org.springframework.security.config.annotation.web.configurers.*; 13 | import org.springframework.security.config.http.SessionCreationPolicy; 14 | import org.springframework.security.web.SecurityFilterChain; 15 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 16 | 17 | /** 18 | * Created on Ağustos, 2020 19 | * 20 | * @author Faruk 21 | */ 22 | @Configuration 23 | @RequiredArgsConstructor 24 | public class SecurityConfiguration { 25 | 26 | private final JwtAuthenticationFilter jwtAuthenticationFilter; 27 | 28 | private final JwtAuthenticationEntryPoint unauthorizedHandler; 29 | 30 | @Bean 31 | public AuthenticationManager authenticationManager(final AuthenticationConfiguration authenticationConfiguration) throws Exception { 32 | return authenticationConfiguration.getAuthenticationManager(); 33 | } 34 | 35 | @Bean 36 | public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 37 | 38 | //@formatter:off 39 | 40 | return http 41 | .csrf(CsrfConfigurer::disable) 42 | .cors(CorsConfigurer::disable) 43 | .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) 44 | .authorizeHttpRequests(request -> request.requestMatchers("/register", 45 | "/login", 46 | "/v3/api-docs/**", 47 | "/swagger-ui/**", 48 | "/swagger-ui.html", 49 | "/actuator/**") 50 | .permitAll() 51 | .anyRequest() 52 | .authenticated()) 53 | .sessionManagement(manager -> manager.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) 54 | .exceptionHandling(handler -> handler.authenticationEntryPoint(unauthorizedHandler)) 55 | .build(); 56 | 57 | //@formatter:on 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/configuration/SwaggerConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.configuration; 2 | 3 | import io.swagger.v3.oas.models.Components; 4 | import io.swagger.v3.oas.models.OpenAPI; 5 | import io.swagger.v3.oas.models.info.Contact; 6 | import io.swagger.v3.oas.models.info.Info; 7 | import io.swagger.v3.oas.models.info.License; 8 | import io.swagger.v3.oas.models.security.SecurityRequirement; 9 | import io.swagger.v3.oas.models.security.SecurityScheme; 10 | import lombok.Getter; 11 | import lombok.Setter; 12 | import org.springdoc.core.models.GroupedOpenApi; 13 | import org.springframework.boot.context.properties.ConfigurationProperties; 14 | import org.springframework.context.annotation.Bean; 15 | import org.springframework.context.annotation.Configuration; 16 | 17 | import static io.swagger.v3.oas.models.security.SecurityScheme.Type.HTTP; 18 | 19 | /** 20 | * Created on Ağustos, 2020 21 | * 22 | * @author Faruk 23 | */ 24 | @Getter 25 | @Setter 26 | @Configuration 27 | @ConfigurationProperties(prefix = "swagger") 28 | public class SwaggerConfiguration { 29 | 30 | private String appName; 31 | 32 | private String appDescription; 33 | 34 | private String appVersion; 35 | 36 | private String appLicense; 37 | 38 | private String appLicenseUrl; 39 | 40 | private String contactName; 41 | 42 | private String contactUrl; 43 | 44 | private String contactMail; 45 | 46 | @Bean 47 | public OpenAPI openAPI() { 48 | 49 | final Info apiInformation = getApiInformation(); 50 | final Components components = new Components(); 51 | 52 | final String schemeName = "bearerAuth"; 53 | components.addSecuritySchemes(schemeName, new SecurityScheme().name(schemeName).type(HTTP).scheme("Bearer").bearerFormat("JWT")); 54 | 55 | final OpenAPI openAPI = new OpenAPI(); 56 | openAPI.setInfo(apiInformation); 57 | openAPI.setComponents(components); 58 | openAPI.addSecurityItem(new SecurityRequirement().addList(schemeName)); 59 | 60 | return openAPI; 61 | } 62 | 63 | private Info getApiInformation() { 64 | 65 | final License license = new License(); 66 | license.setName(appLicense); 67 | license.setUrl(appLicenseUrl); 68 | 69 | final Contact contact = new Contact(); 70 | contact.setName(contactName); 71 | contact.setUrl(contactUrl); 72 | contact.setEmail(contactMail); 73 | 74 | final Info info = new Info(); 75 | info.setTitle(appName); 76 | info.setVersion(appVersion); 77 | info.setDescription(appDescription); 78 | info.setLicense(license); 79 | info.setContact(contact); 80 | 81 | return info; 82 | } 83 | 84 | @Bean 85 | GroupedOpenApi managementApi() { 86 | return GroupedOpenApi.builder().pathsToMatch("/actuator/**").group("Management Api").build(); 87 | } 88 | 89 | @Bean 90 | GroupedOpenApi defaultApi() { 91 | return GroupedOpenApi.builder().pathsToExclude("/actuator/**").group("Default Api").build(); 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/controller/HelloController.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.controller; 2 | 3 | import io.swagger.v3.oas.annotations.Operation; 4 | import org.springframework.http.ResponseEntity; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | /** 9 | * Created on Ağustos, 2020 10 | * 11 | * @author Faruk 12 | */ 13 | @RestController 14 | public class HelloController { 15 | 16 | @GetMapping("/hello") 17 | @Operation(tags = "Hello Service", description = "When you send token information in the header it just says Hello") 18 | public ResponseEntity sayHello() { 19 | 20 | return ResponseEntity.ok("Hello Spring Boot Boilerplate"); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.controller; 2 | 3 | import com.farukgenc.boilerplate.springboot.security.dto.LoginRequest; 4 | import com.farukgenc.boilerplate.springboot.security.dto.LoginResponse; 5 | import com.farukgenc.boilerplate.springboot.security.jwt.JwtTokenService; 6 | import io.swagger.v3.oas.annotations.Operation; 7 | import jakarta.validation.Valid; 8 | import lombok.RequiredArgsConstructor; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.web.bind.annotation.*; 11 | 12 | /** 13 | * Created on Ağustos, 2020 14 | * 15 | * @author Faruk 16 | */ 17 | @RestController 18 | @RequiredArgsConstructor 19 | @RequestMapping("/login") 20 | public class LoginController { 21 | 22 | private final JwtTokenService jwtTokenService; 23 | 24 | @PostMapping 25 | @Operation(tags = "Login Service", description = "You must log in with the correct information to successfully obtain the token information.") 26 | public ResponseEntity loginRequest(@Valid @RequestBody LoginRequest loginRequest) { 27 | 28 | final LoginResponse loginResponse = jwtTokenService.getLoginResponse(loginRequest); 29 | 30 | return ResponseEntity.ok(loginResponse); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/controller/RegistrationController.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.controller; 2 | 3 | import com.farukgenc.boilerplate.springboot.security.dto.RegistrationRequest; 4 | import com.farukgenc.boilerplate.springboot.security.dto.RegistrationResponse; 5 | import com.farukgenc.boilerplate.springboot.security.service.UserService; 6 | import io.swagger.v3.oas.annotations.Operation; 7 | import jakarta.validation.Valid; 8 | import lombok.RequiredArgsConstructor; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | 14 | /** 15 | * Created on Ağustos, 2020 16 | * 17 | * @author Faruk 18 | */ 19 | @RestController 20 | @RequiredArgsConstructor 21 | @RequestMapping("/register") 22 | public class RegistrationController { 23 | 24 | private final UserService userService; 25 | 26 | @PostMapping 27 | @Operation(tags = "Register Service", description = "You can register to the system by sending information in the appropriate format.") 28 | public ResponseEntity registrationRequest(@Valid @RequestBody RegistrationRequest registrationRequest) { 29 | 30 | final RegistrationResponse registrationResponse = userService.registration(registrationRequest); 31 | 32 | return ResponseEntity.status(HttpStatus.CREATED).body(registrationResponse); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/exceptions/ApiExceptionResponse.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.exceptions; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | import org.springframework.http.HttpStatus; 8 | 9 | import java.time.LocalDateTime; 10 | 11 | /** 12 | * Created on Ağustos, 2020 13 | * 14 | * @author Faruk 15 | */ 16 | @Getter 17 | @Setter 18 | @NoArgsConstructor 19 | @AllArgsConstructor 20 | public class ApiExceptionResponse { 21 | 22 | private String message; 23 | 24 | private HttpStatus status; 25 | 26 | private LocalDateTime time; 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/exceptions/LoginControllerAdvice.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.exceptions; 2 | 3 | import com.farukgenc.boilerplate.springboot.controller.LoginController; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.http.ResponseEntity; 6 | import org.springframework.security.authentication.BadCredentialsException; 7 | import org.springframework.web.bind.annotation.ExceptionHandler; 8 | import org.springframework.web.bind.annotation.RestControllerAdvice; 9 | 10 | import java.time.LocalDateTime; 11 | 12 | /** 13 | * Created on Ağustos, 2020 14 | * 15 | * @author Faruk 16 | */ 17 | @RestControllerAdvice(basePackageClasses = LoginController.class) 18 | public class LoginControllerAdvice { 19 | 20 | @ExceptionHandler(BadCredentialsException.class) 21 | ResponseEntity handleRegistrationException(BadCredentialsException exception) { 22 | 23 | final ApiExceptionResponse response = new ApiExceptionResponse(exception.getMessage(), HttpStatus.UNAUTHORIZED, LocalDateTime.now()); 24 | 25 | return ResponseEntity.status(response.getStatus()).body(response); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/exceptions/RegistrationControllerAdvice.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.exceptions; 2 | 3 | import com.farukgenc.boilerplate.springboot.controller.RegistrationController; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.http.ResponseEntity; 6 | import org.springframework.web.bind.annotation.ExceptionHandler; 7 | import org.springframework.web.bind.annotation.RestControllerAdvice; 8 | 9 | import java.time.LocalDateTime; 10 | 11 | /** 12 | * Created on Ağustos, 2020 13 | * 14 | * @author Faruk 15 | */ 16 | @RestControllerAdvice(basePackageClasses = RegistrationController.class) 17 | public class RegistrationControllerAdvice { 18 | 19 | @ExceptionHandler(RegistrationException.class) 20 | ResponseEntity handleRegistrationException(RegistrationException exception) { 21 | 22 | final ApiExceptionResponse response = new ApiExceptionResponse(exception.getErrorMessage(), HttpStatus.BAD_REQUEST, LocalDateTime.now()); 23 | 24 | return ResponseEntity.status(response.getStatus()).body(response); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/exceptions/RegistrationException.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.exceptions; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | 6 | /** 7 | * Created on Ağustos, 2020 8 | * 9 | * @author Faruk 10 | */ 11 | @Getter 12 | @RequiredArgsConstructor 13 | public class RegistrationException extends RuntimeException { 14 | 15 | private final String errorMessage; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/exceptions/ValidationAdvice.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.exceptions; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.context.support.DefaultMessageSourceResolvable; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.validation.FieldError; 8 | import org.springframework.web.bind.MethodArgumentNotValidException; 9 | import org.springframework.web.bind.annotation.ExceptionHandler; 10 | import org.springframework.web.bind.annotation.RestControllerAdvice; 11 | 12 | import java.time.LocalDateTime; 13 | import java.util.List; 14 | import java.util.stream.Collectors; 15 | 16 | /** 17 | * Created on Ağustos, 2020 18 | * 19 | * @author Faruk 20 | */ 21 | @Slf4j 22 | @RestControllerAdvice 23 | public class ValidationAdvice { 24 | 25 | @ExceptionHandler(MethodArgumentNotValidException.class) 26 | public final ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) { 27 | 28 | final List fieldErrors = exception.getBindingResult().getFieldErrors(); 29 | final List errorList = fieldErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList()); 30 | 31 | final ValidationErrorResponse validationErrorResponse = new ValidationErrorResponse(HttpStatus.BAD_REQUEST, LocalDateTime.now(), errorList); 32 | 33 | log.warn("Validation errors : {} , Parameters : {}", errorList, exception.getBindingResult().getTarget()); 34 | 35 | return ResponseEntity.status(validationErrorResponse.getStatus()).body(validationErrorResponse); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/exceptions/ValidationErrorResponse.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.exceptions; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | import org.springframework.http.HttpStatus; 8 | 9 | import java.time.LocalDateTime; 10 | import java.util.List; 11 | 12 | /** 13 | * Created on Ağustos, 2020 14 | * 15 | * @author Faruk 16 | */ 17 | @Getter 18 | @Setter 19 | @NoArgsConstructor 20 | @AllArgsConstructor 21 | public class ValidationErrorResponse { 22 | 23 | private HttpStatus status; 24 | 25 | private LocalDateTime time; 26 | 27 | private List message; 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/model/User.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.model; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.*; 5 | 6 | 7 | /** 8 | * Created on Ağustos, 2020 9 | * 10 | * @author Faruk 11 | */ 12 | @Getter 13 | @Setter 14 | @Entity 15 | @Builder 16 | @NoArgsConstructor 17 | @AllArgsConstructor 18 | @Table(name = "USERS") 19 | public class User { 20 | 21 | @Id 22 | @GeneratedValue(strategy = GenerationType.IDENTITY) 23 | private Long id; 24 | 25 | private String name; 26 | 27 | @Column(unique = true) 28 | private String username; 29 | 30 | private String password; 31 | 32 | private String email; 33 | 34 | @Enumerated(EnumType.STRING) 35 | private UserRole userRole; 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/model/UserRole.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.model; 2 | 3 | /** 4 | * Created on Ağustos, 2020 5 | * 6 | * @author Faruk 7 | */ 8 | public enum UserRole { 9 | 10 | USER, ADMIN 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.repository; 2 | 3 | import com.farukgenc.boilerplate.springboot.model.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | /** 7 | * Created on Ağustos, 2020 8 | * 9 | * @author Faruk 10 | */ 11 | public interface UserRepository extends JpaRepository { 12 | 13 | User findByUsername(String username); 14 | 15 | boolean existsByEmail(String email); 16 | 17 | boolean existsByUsername(String username); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/dto/AuthenticatedUserDto.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.dto; 2 | 3 | import com.farukgenc.boilerplate.springboot.model.UserRole; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | 8 | /** 9 | * Created on Ağustos, 2020 10 | * 11 | * @author Faruk 12 | */ 13 | @Getter 14 | @Setter 15 | @NoArgsConstructor 16 | public class AuthenticatedUserDto { 17 | 18 | private String name; 19 | 20 | private String username; 21 | 22 | private String password; 23 | 24 | private UserRole userRole; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/dto/LoginRequest.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.dto; 2 | 3 | import jakarta.validation.constraints.NotEmpty; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | 8 | 9 | /** 10 | * Created on Ağustos, 2020 11 | * 12 | * @author Faruk 13 | */ 14 | @Getter 15 | @Setter 16 | @NoArgsConstructor 17 | public class LoginRequest { 18 | 19 | @NotEmpty(message = "{login_username_not_empty}") 20 | private String username; 21 | 22 | @NotEmpty(message = "{login_password_not_empty}") 23 | private String password; 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/dto/LoginResponse.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.dto; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | /** 8 | * Created on Ağustos, 2020 9 | * 10 | * @author Faruk 11 | */ 12 | @Getter 13 | @Setter 14 | @AllArgsConstructor 15 | public class LoginResponse { 16 | 17 | private String token; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/dto/RegistrationRequest.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.dto; 2 | 3 | import jakarta.validation.constraints.Email; 4 | import jakarta.validation.constraints.NotEmpty; 5 | import lombok.Getter; 6 | import lombok.NoArgsConstructor; 7 | import lombok.Setter; 8 | import lombok.ToString; 9 | 10 | /** 11 | * Created on Ağustos, 2020 12 | * 13 | * @author Faruk 14 | */ 15 | @Getter 16 | @Setter 17 | @ToString 18 | @NoArgsConstructor 19 | public class RegistrationRequest { 20 | 21 | @NotEmpty(message = "{registration_name_not_empty}") 22 | private String name; 23 | 24 | @Email(message = "{registration_email_is_not_valid}") 25 | @NotEmpty(message = "{registration_email_not_empty}") 26 | private String email; 27 | 28 | @NotEmpty(message = "{registration_username_not_empty}") 29 | private String username; 30 | 31 | @NotEmpty(message = "{registration_password_not_empty}") 32 | private String password; 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/dto/RegistrationResponse.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.dto; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | 8 | /** 9 | * Created on Ağustos, 2020 10 | * 11 | * @author Faruk 12 | */ 13 | @Getter 14 | @Setter 15 | @NoArgsConstructor 16 | @AllArgsConstructor 17 | public class RegistrationResponse { 18 | 19 | private String message; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/jwt/JwtAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.jwt; 2 | 3 | import jakarta.servlet.http.HttpServletRequest; 4 | import jakarta.servlet.http.HttpServletResponse; 5 | import org.springframework.security.core.AuthenticationException; 6 | import org.springframework.security.web.AuthenticationEntryPoint; 7 | import org.springframework.stereotype.Component; 8 | 9 | import java.io.IOException; 10 | 11 | /** 12 | * Created on Ağustos, 2020 13 | * 14 | * @author Faruk 15 | */ 16 | @Component 17 | public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { 18 | 19 | @Override 20 | public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { 21 | 22 | response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/jwt/JwtAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.jwt; 2 | 3 | import com.farukgenc.boilerplate.springboot.security.service.UserDetailsServiceImpl; 4 | import com.farukgenc.boilerplate.springboot.security.utils.SecurityConstants; 5 | import jakarta.servlet.FilterChain; 6 | import jakarta.servlet.ServletException; 7 | import jakarta.servlet.http.HttpServletRequest; 8 | import jakarta.servlet.http.HttpServletResponse; 9 | import lombok.RequiredArgsConstructor; 10 | import lombok.extern.slf4j.Slf4j; 11 | import org.apache.logging.log4j.util.Strings; 12 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 13 | import org.springframework.security.core.context.SecurityContext; 14 | import org.springframework.security.core.context.SecurityContextHolder; 15 | import org.springframework.security.core.userdetails.UserDetails; 16 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 17 | import org.springframework.stereotype.Service; 18 | import org.springframework.web.filter.OncePerRequestFilter; 19 | 20 | import java.io.IOException; 21 | import java.util.Objects; 22 | 23 | /** 24 | * Created on Ağustos, 2020 25 | * 26 | * @author Faruk 27 | */ 28 | @Slf4j 29 | @Service 30 | @RequiredArgsConstructor 31 | public class JwtAuthenticationFilter extends OncePerRequestFilter { 32 | 33 | private final JwtTokenManager jwtTokenManager; 34 | 35 | private final UserDetailsServiceImpl userDetailsService; 36 | 37 | @Override 38 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) 39 | throws IOException, ServletException { 40 | 41 | final String header = request.getHeader(SecurityConstants.HEADER_STRING); 42 | 43 | String username = null; 44 | String authToken = null; 45 | if (Objects.nonNull(header) && header.startsWith(SecurityConstants.TOKEN_PREFIX)) { 46 | 47 | authToken = header.replace(SecurityConstants.TOKEN_PREFIX, Strings.EMPTY); 48 | 49 | try { 50 | username = jwtTokenManager.getUsernameFromToken(authToken); 51 | } 52 | catch (Exception e) { 53 | log.error("Authentication Exception : {}", e.getMessage()); 54 | chain.doFilter(request, response); 55 | return; 56 | } 57 | } 58 | 59 | final SecurityContext securityContext = SecurityContextHolder.getContext(); 60 | 61 | final boolean canBeStartTokenValidation = Objects.nonNull(username) && Objects.isNull(securityContext.getAuthentication()); 62 | 63 | if (!canBeStartTokenValidation) { 64 | chain.doFilter(request, response); 65 | return; 66 | } 67 | 68 | final UserDetails user = userDetailsService.loadUserByUsername(username); 69 | final boolean validToken = jwtTokenManager.validateToken(authToken, user.getUsername()); 70 | 71 | if (!validToken) { 72 | chain.doFilter(request, response); 73 | return; 74 | } 75 | 76 | final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); 77 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); 78 | securityContext.setAuthentication(authentication); 79 | 80 | log.info("Authentication successful. Logged in username : {} ", username); 81 | 82 | chain.doFilter(request, response); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/jwt/JwtProperties.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.jwt; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | /** 9 | * Created on October, 2022 10 | * 11 | * @author Faruk 12 | */ 13 | 14 | @Getter 15 | @Setter 16 | @Configuration 17 | @ConfigurationProperties(prefix = "jwt") 18 | public class JwtProperties { 19 | 20 | private String issuer; 21 | 22 | private String secretKey; 23 | 24 | private long expirationMinute; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/jwt/JwtTokenManager.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.jwt; 2 | 3 | import com.auth0.jwt.JWT; 4 | import com.auth0.jwt.JWTVerifier; 5 | import com.auth0.jwt.algorithms.Algorithm; 6 | import com.auth0.jwt.interfaces.DecodedJWT; 7 | import com.farukgenc.boilerplate.springboot.model.User; 8 | import com.farukgenc.boilerplate.springboot.model.UserRole; 9 | import lombok.RequiredArgsConstructor; 10 | import org.springframework.stereotype.Component; 11 | 12 | import java.util.Date; 13 | 14 | /** 15 | * Created on Ağustos, 2020 16 | * 17 | * @author Faruk 18 | */ 19 | @Component 20 | @RequiredArgsConstructor 21 | public class JwtTokenManager { 22 | 23 | private final JwtProperties jwtProperties; 24 | 25 | public String generateToken(User user) { 26 | 27 | final String username = user.getUsername(); 28 | final UserRole userRole = user.getUserRole(); 29 | 30 | //@formatter:off 31 | return JWT.create() 32 | .withSubject(username) 33 | .withIssuer(jwtProperties.getIssuer()) 34 | .withClaim("role", userRole.name()) 35 | .withIssuedAt(new Date()) 36 | .withExpiresAt(new Date(System.currentTimeMillis() + jwtProperties.getExpirationMinute() * 60 * 1000)) 37 | .sign(Algorithm.HMAC256(jwtProperties.getSecretKey().getBytes())); 38 | //@formatter:on 39 | } 40 | 41 | public String getUsernameFromToken(String token) { 42 | 43 | final DecodedJWT decodedJWT = getDecodedJWT(token); 44 | 45 | return decodedJWT.getSubject(); 46 | } 47 | 48 | public boolean validateToken(String token, String authenticatedUsername) { 49 | 50 | final String usernameFromToken = getUsernameFromToken(token); 51 | 52 | final boolean equalsUsername = usernameFromToken.equals(authenticatedUsername); 53 | final boolean tokenExpired = isTokenExpired(token); 54 | 55 | return equalsUsername && !tokenExpired; 56 | } 57 | 58 | private boolean isTokenExpired(String token) { 59 | 60 | final Date expirationDateFromToken = getExpirationDateFromToken(token); 61 | return expirationDateFromToken.before(new Date()); 62 | } 63 | 64 | private Date getExpirationDateFromToken(String token) { 65 | 66 | final DecodedJWT decodedJWT = getDecodedJWT(token); 67 | 68 | return decodedJWT.getExpiresAt(); 69 | } 70 | 71 | private DecodedJWT getDecodedJWT(String token) { 72 | 73 | final JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(jwtProperties.getSecretKey().getBytes())).build(); 74 | 75 | return jwtVerifier.verify(token); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/jwt/JwtTokenService.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.jwt; 2 | 3 | import com.farukgenc.boilerplate.springboot.security.mapper.UserMapper; 4 | import com.farukgenc.boilerplate.springboot.security.service.UserService; 5 | import com.farukgenc.boilerplate.springboot.model.User; 6 | import com.farukgenc.boilerplate.springboot.security.dto.AuthenticatedUserDto; 7 | import com.farukgenc.boilerplate.springboot.security.dto.LoginRequest; 8 | import com.farukgenc.boilerplate.springboot.security.dto.LoginResponse; 9 | import lombok.RequiredArgsConstructor; 10 | import lombok.extern.slf4j.Slf4j; 11 | import org.springframework.security.authentication.AuthenticationManager; 12 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 13 | import org.springframework.stereotype.Service; 14 | 15 | /** 16 | * Created on Ağustos, 2020 17 | * 18 | * @author Faruk 19 | */ 20 | @Slf4j 21 | @Service 22 | @RequiredArgsConstructor 23 | public class JwtTokenService { 24 | 25 | private final UserService userService; 26 | 27 | private final JwtTokenManager jwtTokenManager; 28 | 29 | private final AuthenticationManager authenticationManager; 30 | 31 | public LoginResponse getLoginResponse(LoginRequest loginRequest) { 32 | 33 | final String username = loginRequest.getUsername(); 34 | final String password = loginRequest.getPassword(); 35 | 36 | final UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password); 37 | 38 | authenticationManager.authenticate(usernamePasswordAuthenticationToken); 39 | 40 | final AuthenticatedUserDto authenticatedUserDto = userService.findAuthenticatedUserByUsername(username); 41 | 42 | final User user = UserMapper.INSTANCE.convertToUser(authenticatedUserDto); 43 | final String token = jwtTokenManager.generateToken(user); 44 | 45 | log.info("{} has successfully logged in!", user.getUsername()); 46 | 47 | return new LoginResponse(token); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.mapper; 2 | 3 | import com.farukgenc.boilerplate.springboot.model.User; 4 | import com.farukgenc.boilerplate.springboot.security.dto.AuthenticatedUserDto; 5 | import com.farukgenc.boilerplate.springboot.security.dto.RegistrationRequest; 6 | import org.mapstruct.Mapper; 7 | import org.mapstruct.ReportingPolicy; 8 | import org.mapstruct.factory.Mappers; 9 | 10 | /** 11 | * Created on Ağustos, 2020 12 | * 13 | * @author Faruk 14 | */ 15 | @Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE) 16 | public interface UserMapper { 17 | 18 | UserMapper INSTANCE = Mappers.getMapper(UserMapper.class); 19 | 20 | User convertToUser(RegistrationRequest registrationRequest); 21 | 22 | AuthenticatedUserDto convertToAuthenticatedUserDto(User user); 23 | 24 | User convertToUser(AuthenticatedUserDto authenticatedUserDto); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/service/UserDetailsServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.service; 2 | 3 | import com.farukgenc.boilerplate.springboot.model.UserRole; 4 | import com.farukgenc.boilerplate.springboot.security.dto.AuthenticatedUserDto; 5 | import lombok.RequiredArgsConstructor; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 8 | import org.springframework.security.core.userdetails.User; 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.Collections; 15 | import java.util.Objects; 16 | 17 | /** 18 | * Created on Ağustos, 2020 19 | * 20 | * @author Faruk 21 | */ 22 | @Slf4j 23 | @Service 24 | @RequiredArgsConstructor 25 | public class UserDetailsServiceImpl implements UserDetailsService { 26 | 27 | private static final String USERNAME_OR_PASSWORD_INVALID = "Invalid username or password."; 28 | 29 | private final UserService userService; 30 | 31 | @Override 32 | public UserDetails loadUserByUsername(String username) { 33 | 34 | final AuthenticatedUserDto authenticatedUser = userService.findAuthenticatedUserByUsername(username); 35 | 36 | if (Objects.isNull(authenticatedUser)) { 37 | throw new UsernameNotFoundException(USERNAME_OR_PASSWORD_INVALID); 38 | } 39 | 40 | final String authenticatedUsername = authenticatedUser.getUsername(); 41 | final String authenticatedPassword = authenticatedUser.getPassword(); 42 | final UserRole userRole = authenticatedUser.getUserRole(); 43 | final SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(userRole.name()); 44 | 45 | return new User(authenticatedUsername, authenticatedPassword, Collections.singletonList(grantedAuthority)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.service; 2 | 3 | import com.farukgenc.boilerplate.springboot.model.User; 4 | import com.farukgenc.boilerplate.springboot.security.dto.AuthenticatedUserDto; 5 | import com.farukgenc.boilerplate.springboot.security.dto.RegistrationRequest; 6 | import com.farukgenc.boilerplate.springboot.security.dto.RegistrationResponse; 7 | 8 | /** 9 | * Created on Ağustos, 2020 10 | * 11 | * @author Faruk 12 | */ 13 | public interface UserService { 14 | 15 | User findByUsername(String username); 16 | 17 | RegistrationResponse registration(RegistrationRequest registrationRequest); 18 | 19 | AuthenticatedUserDto findAuthenticatedUserByUsername(String username); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/service/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.service; 2 | 3 | import com.farukgenc.boilerplate.springboot.service.UserValidationService; 4 | import com.farukgenc.boilerplate.springboot.model.User; 5 | import com.farukgenc.boilerplate.springboot.model.UserRole; 6 | import com.farukgenc.boilerplate.springboot.security.dto.AuthenticatedUserDto; 7 | import com.farukgenc.boilerplate.springboot.security.dto.RegistrationRequest; 8 | import com.farukgenc.boilerplate.springboot.security.dto.RegistrationResponse; 9 | import com.farukgenc.boilerplate.springboot.security.mapper.UserMapper; 10 | import com.farukgenc.boilerplate.springboot.utils.GeneralMessageAccessor; 11 | import com.farukgenc.boilerplate.springboot.repository.UserRepository; 12 | import lombok.RequiredArgsConstructor; 13 | import lombok.extern.slf4j.Slf4j; 14 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 15 | import org.springframework.stereotype.Service; 16 | 17 | /** 18 | * Created on Ağustos, 2020 19 | * 20 | * @author Faruk 21 | */ 22 | @Slf4j 23 | @Service 24 | @RequiredArgsConstructor 25 | public class UserServiceImpl implements UserService { 26 | 27 | private static final String REGISTRATION_SUCCESSFUL = "registration_successful"; 28 | 29 | private final UserRepository userRepository; 30 | 31 | private final BCryptPasswordEncoder bCryptPasswordEncoder; 32 | 33 | private final UserValidationService userValidationService; 34 | 35 | private final GeneralMessageAccessor generalMessageAccessor; 36 | 37 | @Override 38 | public User findByUsername(String username) { 39 | 40 | return userRepository.findByUsername(username); 41 | } 42 | 43 | @Override 44 | public RegistrationResponse registration(RegistrationRequest registrationRequest) { 45 | 46 | userValidationService.validateUser(registrationRequest); 47 | 48 | final User user = UserMapper.INSTANCE.convertToUser(registrationRequest); 49 | user.setPassword(bCryptPasswordEncoder.encode(user.getPassword())); 50 | user.setUserRole(UserRole.USER); 51 | 52 | userRepository.save(user); 53 | 54 | final String username = registrationRequest.getUsername(); 55 | final String registrationSuccessMessage = generalMessageAccessor.getMessage(null, REGISTRATION_SUCCESSFUL, username); 56 | 57 | log.info("{} registered successfully!", username); 58 | 59 | return new RegistrationResponse(registrationSuccessMessage); 60 | } 61 | 62 | @Override 63 | public AuthenticatedUserDto findAuthenticatedUserByUsername(String username) { 64 | 65 | final User user = findByUsername(username); 66 | 67 | return UserMapper.INSTANCE.convertToAuthenticatedUserDto(user); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/security/utils/SecurityConstants.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.security.utils; 2 | 3 | import org.springframework.security.core.Authentication; 4 | import org.springframework.security.core.context.SecurityContextHolder; 5 | import org.springframework.security.core.userdetails.UserDetails; 6 | 7 | /** 8 | * Created on Ağustos, 2020 9 | * 10 | * @author Faruk 11 | */ 12 | public class SecurityConstants { 13 | 14 | // FIXME : Customize security constants for your application. 15 | 16 | /** 17 | * Token expiration time 1 days. 18 | */ 19 | public static final long EXPIRATION_TIME = 24 * 60 * 60 * 1000; 20 | 21 | /** 22 | * Secret key for signature 23 | */ 24 | public static final String SECRET_KEY = "mySecretKey"; 25 | 26 | /** 27 | * The company who provided token. 28 | * You can customize issuer name, this is given as an example. 29 | */ 30 | public static final String ISSUER = "www.boilerplate.design"; 31 | 32 | /** 33 | * Token Prefix 34 | * We will use this prefix when parsing JWT Token 35 | */ 36 | public static final String TOKEN_PREFIX = "Bearer "; 37 | 38 | /** 39 | * Authorization Prefix in HttpServletRequest 40 | * Authorization: 41 | * For Example : Authorization: Bearer YWxhZGxa1qea32GVuc2VzYW1l 42 | */ 43 | public static final String HEADER_STRING = "Authorization"; 44 | 45 | public static final String LOGIN_REQUEST_URI = "/login"; 46 | 47 | public static final String REGISTRATION_REQUEST_URI = "/register"; 48 | 49 | private SecurityConstants() { 50 | 51 | throw new UnsupportedOperationException(); 52 | } 53 | 54 | /** 55 | * @return authenticated username from Security Context 56 | */ 57 | public static String getAuthenticatedUsername() { 58 | 59 | final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 60 | final UserDetails userDetails = (UserDetails) authentication.getPrincipal(); 61 | 62 | return userDetails.getUsername(); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/service/UserValidationService.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.service; 2 | 3 | import com.farukgenc.boilerplate.springboot.utils.ExceptionMessageAccessor; 4 | import com.farukgenc.boilerplate.springboot.exceptions.RegistrationException; 5 | import com.farukgenc.boilerplate.springboot.repository.UserRepository; 6 | import com.farukgenc.boilerplate.springboot.security.dto.RegistrationRequest; 7 | import lombok.RequiredArgsConstructor; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.stereotype.Service; 10 | 11 | /** 12 | * Created on Ağustos, 2020 13 | * 14 | * @author Faruk 15 | */ 16 | @Slf4j 17 | @Service 18 | @RequiredArgsConstructor 19 | public class UserValidationService { 20 | 21 | private static final String EMAIL_ALREADY_EXISTS = "email_already_exists"; 22 | 23 | private static final String USERNAME_ALREADY_EXISTS = "username_already_exists"; 24 | 25 | private final UserRepository userRepository; 26 | 27 | private final ExceptionMessageAccessor exceptionMessageAccessor; 28 | 29 | public void validateUser(RegistrationRequest registrationRequest) { 30 | 31 | final String email = registrationRequest.getEmail(); 32 | final String username = registrationRequest.getUsername(); 33 | 34 | checkEmail(email); 35 | checkUsername(username); 36 | } 37 | 38 | private void checkUsername(String username) { 39 | 40 | final boolean existsByUsername = userRepository.existsByUsername(username); 41 | 42 | if (existsByUsername) { 43 | 44 | log.warn("{} is already being used!", username); 45 | 46 | final String existsUsername = exceptionMessageAccessor.getMessage(null, USERNAME_ALREADY_EXISTS); 47 | throw new RegistrationException(existsUsername); 48 | } 49 | 50 | } 51 | 52 | private void checkEmail(String email) { 53 | 54 | final boolean existsByEmail = userRepository.existsByEmail(email); 55 | 56 | if (existsByEmail) { 57 | 58 | log.warn("{} is already being used!", email); 59 | 60 | final String existsEmail = exceptionMessageAccessor.getMessage(null, EMAIL_ALREADY_EXISTS); 61 | throw new RegistrationException(existsEmail); 62 | } 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/utils/ExceptionMessageAccessor.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.utils; 2 | 3 | import org.springframework.beans.factory.annotation.Qualifier; 4 | import org.springframework.context.MessageSource; 5 | import org.springframework.stereotype.Service; 6 | 7 | import java.util.Locale; 8 | import java.util.Objects; 9 | 10 | /** 11 | * Created on Ağustos, 2020 12 | * 13 | * @author Faruk 14 | */ 15 | @Service 16 | public class ExceptionMessageAccessor { 17 | 18 | private final MessageSource messageSource; 19 | 20 | ExceptionMessageAccessor(@Qualifier("exceptionMessageSource") MessageSource messageSource) { 21 | this.messageSource = messageSource; 22 | } 23 | 24 | public String getMessage(Locale locale, String key, Object... parameter) { 25 | 26 | if (Objects.isNull(locale)) { 27 | return messageSource.getMessage(key, parameter, ProjectConstants.TURKISH_LOCALE); 28 | } 29 | 30 | return messageSource.getMessage(key, parameter, locale); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/utils/GeneralMessageAccessor.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.utils; 2 | 3 | import org.springframework.beans.factory.annotation.Qualifier; 4 | import org.springframework.context.MessageSource; 5 | import org.springframework.stereotype.Service; 6 | 7 | import java.util.Locale; 8 | import java.util.Objects; 9 | 10 | /** 11 | * Created on Ağustos, 2020 12 | * 13 | * @author Faruk 14 | */ 15 | @Service 16 | public class GeneralMessageAccessor { 17 | 18 | private final MessageSource messageSource; 19 | 20 | GeneralMessageAccessor(@Qualifier("generalMessageSource") MessageSource messageSource) { 21 | this.messageSource = messageSource; 22 | } 23 | 24 | public String getMessage(Locale locale, String key, Object... parameter) { 25 | 26 | if (Objects.isNull(locale)) { 27 | return messageSource.getMessage(key, parameter, ProjectConstants.TURKISH_LOCALE); 28 | } 29 | 30 | return messageSource.getMessage(key, parameter, locale); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/farukgenc/boilerplate/springboot/utils/ProjectConstants.java: -------------------------------------------------------------------------------- 1 | package com.farukgenc.boilerplate.springboot.utils; 2 | 3 | import java.util.Locale; 4 | 5 | /** 6 | * Created on Ağustos, 2020 7 | * 8 | * @author Faruk 9 | */ 10 | public final class ProjectConstants { 11 | 12 | // FIXME : Customize project constants for your application. 13 | 14 | public static final String DEFAULT_ENCODING = "UTF-8"; 15 | 16 | public static final Locale TURKISH_LOCALE = new Locale.Builder().setLanguage("tr").setRegion("TR").build(); 17 | 18 | private ProjectConstants() { 19 | 20 | throw new UnsupportedOperationException(); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | http2: 3 | enabled: true 4 | 5 | spring: 6 | datasource: 7 | url: jdbc:postgresql://${POSTGRES_DB_SERVER_ADDRESS:localhost}:${POSTGRES_DB_SERVER_PORT:5432}/ 8 | username: ${POSTGRES_USER:postgres} 9 | password: ${POSTGRES_PASSWORD:example} 10 | hikari: 11 | pool-name: SpringBootBoilerplateHikariPool 12 | jpa: 13 | hibernate: 14 | ddl-auto: create 15 | open-in-view: false 16 | jta: 17 | enabled: false 18 | 19 | springdoc: 20 | show-actuator: true 21 | 22 | management: 23 | endpoint: 24 | health: 25 | show-details: ALWAYS 26 | probes: 27 | enabled: true 28 | endpoints: 29 | web: 30 | exposure: 31 | include: "*" 32 | 33 | logging: 34 | level: 35 | org.springframework: INFO 36 | com.farukgenc.boilerplate.springboot: INFO 37 | 38 | ## FIXME : Customize JWT token and Swagger information for your application 39 | 40 | jwt: 41 | secretKey: secret 42 | issuer: www.farukgenc.com 43 | expirationMinute: 10 44 | 45 | swagger: 46 | contact-name: Faruk Genc 47 | contact-mail: omer@farukgenc.com 48 | contact-url: https://farukgenc.com 49 | app-name: Spring Boot Boilerplate Project 50 | app-description: "Spring Boot Boilerplate is a starter kit. This project includes : Spring Boot(3.4.0), Spring Data JPA, Spring Validation, Spring Security + JWT Token, PostgreSQL, Mapstruct, Lombok, Swagger (Open API)" 51 | app-version: 3.4.0 52 | app-license-url: https://www.apache.org/licenses/LICENSE-2.0.html 53 | app-license: Apache 2.0 54 | -------------------------------------------------------------------------------- /src/main/resources/banner.txt: -------------------------------------------------------------------------------- 1 | _______ _____ ______ _____ __ _ ______ ______ _____ _____ _______ ______ _____ _____ _______ ______ _____ _______ _______ _______ 2 | |______ |_____] |_____/ | | \ | | ____ |_____] | | | | | |_____] | | | | |______ |_____/ |_____] | |_____| | |______ 3 | ______| | | \_ __|__ | \_| |_____| |_____] |_____| |_____| | |_____] |_____| __|__ |_____ |______ | \_ | |_____ | | | |______ 4 | 5 | -------------------------------------------------------------------------------- /src/main/resources/messages/exception/ExceptionMessages.properties: -------------------------------------------------------------------------------- 1 | username_already_exists = This username is already being used! 2 | email_already_exists = This email address is already being used! 3 | -------------------------------------------------------------------------------- /src/main/resources/messages/exception/ExceptionMessages_tr.properties: -------------------------------------------------------------------------------- 1 | email_already_exists = Bu e-posta adresi zaten kullan\u0131l\u0131yor! 2 | username_already_exists = Bu kullan\u0131c\u0131 ad\u0131 zaten kullan\u0131l\u0131yor! 3 | -------------------------------------------------------------------------------- /src/main/resources/messages/general/GeneralMessages.properties: -------------------------------------------------------------------------------- 1 | registration_successful = {0} registered successfully! -------------------------------------------------------------------------------- /src/main/resources/messages/general/GeneralMessages_tr.properties: -------------------------------------------------------------------------------- 1 | registration_successful = {0} kullanıcısı başarıyla kaydedildi. -------------------------------------------------------------------------------- /src/main/resources/messages/validation/ValidationMessages.properties: -------------------------------------------------------------------------------- 1 | # REGISTRATION VALIDATION 2 | registration_name_not_empty=Name can not be null! 3 | registration_email_not_empty=Email can not be null! 4 | registration_username_not_empty=Username can not be null! 5 | registration_password_not_empty=Password can not be null! 6 | registration_email_is_not_valid=Please enter a valid email! 7 | # LOGIN VALIDATION 8 | login_username_not_empty=Username can not be null! 9 | login_password_not_empty=Password can not be null! 10 | -------------------------------------------------------------------------------- /src/main/resources/messages/validation/ValidationMessages_tr.properties: -------------------------------------------------------------------------------- 1 | # REGISTRATION VALIDATION 2 | registration_name_not_empty=\u0130sim bo\u015F olamaz! 3 | registration_email_not_empty=Email bo\u015F olamaz! 4 | registration_username_not_empty=Kullan\u0131c\u0131 ad\u0131 bo\u00FE olamaz! 5 | registration_password_not_empty=Parola bo\u015F olamaz! 6 | registration_email_is_not_valid=L\u00FCtfen ge\u00E7erli bir email giriniz! 7 | # LOGIN VALIDATION 8 | login.username_not_empty=Kullan\u0131c\u0131 ad\u0131 bo\u00FE olamaz! 9 | login.password_not_empty=\u015Eifre bo\u015F olamaz! 10 | --------------------------------------------------------------------------------