├── .github └── workflows │ └── digitalocean.yml ├── LICENSE ├── README.md ├── angular-11-social-login ├── .browserslistrc ├── .dockerignore ├── .editorconfig ├── .gitignore ├── Dockerfile ├── README.md ├── angular.json ├── e2e │ ├── protractor.conf.js │ ├── src │ │ ├── app.e2e-spec.ts │ │ └── app.po.ts │ └── tsconfig.json ├── karma.conf.js ├── nginx-custom.conf ├── package-lock.json ├── package.json ├── src │ ├── app │ │ ├── _helpers │ │ │ └── auth.interceptor.ts │ │ ├── _services │ │ │ ├── auth.service.spec.ts │ │ │ ├── auth.service.ts │ │ │ ├── token-storage.service.spec.ts │ │ │ ├── token-storage.service.ts │ │ │ ├── user.service.spec.ts │ │ │ └── user.service.ts │ │ ├── app-routing.module.ts │ │ ├── app.component.css │ │ ├── app.component.html │ │ ├── app.component.spec.ts │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── board-admin │ │ │ ├── board-admin.component.css │ │ │ ├── board-admin.component.html │ │ │ ├── board-admin.component.spec.ts │ │ │ └── board-admin.component.ts │ │ ├── board-moderator │ │ │ ├── board-moderator.component.css │ │ │ ├── board-moderator.component.html │ │ │ ├── board-moderator.component.spec.ts │ │ │ └── board-moderator.component.ts │ │ ├── board-user │ │ │ ├── board-user.component.css │ │ │ ├── board-user.component.html │ │ │ ├── board-user.component.spec.ts │ │ │ └── board-user.component.ts │ │ ├── common │ │ │ └── app.constants.ts │ │ ├── home │ │ │ ├── home.component.css │ │ │ ├── home.component.html │ │ │ ├── home.component.spec.ts │ │ │ └── home.component.ts │ │ ├── login │ │ │ ├── login.component.css │ │ │ ├── login.component.html │ │ │ ├── login.component.spec.ts │ │ │ └── login.component.ts │ │ ├── profile │ │ │ ├── profile.component.css │ │ │ ├── profile.component.html │ │ │ ├── profile.component.spec.ts │ │ │ └── profile.component.ts │ │ ├── register │ │ │ ├── register.component.css │ │ │ ├── register.component.html │ │ │ ├── register.component.spec.ts │ │ │ └── register.component.ts │ │ └── totp │ │ │ ├── totp.component.css │ │ │ ├── totp.component.html │ │ │ └── totp.component.ts │ ├── assets │ │ ├── .gitkeep │ │ └── img │ │ │ ├── facebook.png │ │ │ ├── github.png │ │ │ ├── google.png │ │ │ ├── linkedin.png │ │ │ └── logo.png │ ├── environments │ │ ├── environment.prod.ts │ │ └── environment.ts │ ├── favicon.ico │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ ├── styles.css │ └── test.ts ├── tsconfig.app.json ├── tsconfig.base.json ├── tsconfig.json ├── tsconfig.spec.json └── tslint.json ├── docker-compose.yml ├── k8s ├── app-client.yml ├── app-server.yml ├── ingress-nginx-https.yml ├── ingress-nginx.yml ├── mysql.yml ├── prod-issuer.yml └── staging-issuer.yml └── spring-boot-oauth2-social-login ├── .mvn └── wrapper │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── Dockerfile ├── mvnw ├── mvnw.cmd ├── pom.xml └── src └── main ├── java └── com │ └── javachinna │ ├── DemoApplication.java │ ├── config │ ├── AppProperties.java │ ├── CurrentUser.java │ ├── RestAuthenticationEntryPoint.java │ ├── SetupDataLoader.java │ ├── WebConfig.java │ └── WebSecurityConfig.java │ ├── controller │ ├── AuthController.java │ └── UserController.java │ ├── dto │ ├── ApiResponse.java │ ├── JwtAuthenticationResponse.java │ ├── LocalUser.java │ ├── LoginRequest.java │ ├── SignUpRequest.java │ ├── SignUpResponse.java │ ├── SocialProvider.java │ └── UserInfo.java │ ├── exception │ ├── BadRequestException.java │ ├── OAuth2AuthenticationProcessingException.java │ ├── ResourceNotFoundException.java │ ├── UserAlreadyExistAuthenticationException.java │ └── handler │ │ └── RestResponseEntityExceptionHandler.java │ ├── model │ ├── Role.java │ └── User.java │ ├── repo │ ├── RoleRepository.java │ └── UserRepository.java │ ├── security │ ├── jwt │ │ ├── TokenAuthenticationFilter.java │ │ └── TokenProvider.java │ └── oauth2 │ │ ├── CustomOAuth2UserService.java │ │ ├── CustomOidcUserService.java │ │ ├── HttpCookieOAuth2AuthorizationRequestRepository.java │ │ ├── OAuth2AccessTokenResponseConverterWithDefaults.java │ │ ├── OAuth2AuthenticationFailureHandler.java │ │ ├── OAuth2AuthenticationSuccessHandler.java │ │ └── user │ │ ├── FacebookOAuth2UserInfo.java │ │ ├── GithubOAuth2UserInfo.java │ │ ├── GoogleOAuth2UserInfo.java │ │ ├── LinkedinOAuth2UserInfo.java │ │ ├── OAuth2UserInfo.java │ │ └── OAuth2UserInfoFactory.java │ ├── service │ ├── LocalUserDetailService.java │ ├── UserService.java │ └── UserServiceImpl.java │ ├── util │ ├── CookieUtils.java │ └── GeneralUtils.java │ └── validator │ ├── PasswordMatches.java │ └── PasswordMatchesValidator.java └── resources ├── application.properties └── messages_en.properties /.github/workflows/digitalocean.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - main 5 | pull_request: 6 | branches: 7 | - main 8 | # Environment variables available to all jobs and steps in this workflow 9 | env: 10 | ANGULAR_IMAGE_NAME: social-login-app-client 11 | ANGULAR_CONTAINER_NAME: social-login-app-client 12 | ANGULAR_DEPLOYMENT_NAME: social-login-app-client 13 | SPRING_BOOT_IMAGE_NAME: social-login-app-server 14 | SPRING_BOOT_CONTAINER_NAME: social-login-app-server 15 | SPRING_BOOT_DEPLOYMENT_NAME: social-login-app-server 16 | jobs: 17 | 18 | build: 19 | name: Build, push, and deploy 20 | runs-on: ubuntu-latest 21 | steps: 22 | 23 | - name: Checkout main 24 | uses: actions/checkout@main 25 | 26 | - name: Login to Docker Hub 27 | uses: docker/login-action@v1 28 | with: 29 | username: ${{ secrets.DOCKER_HUB_USERNAME }} 30 | password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} 31 | 32 | - name: Provide permission to run mvnw 33 | run: chmod +x ./spring-boot-oauth2-social-login/mvnw 34 | 35 | - name: Build and push Angular Image 36 | id: angular_docker_build 37 | uses: docker/build-push-action@v2 38 | with: 39 | context: ./angular-11-social-login 40 | file: ./angular-11-social-login/Dockerfile 41 | push: true 42 | tags: ${{ secrets.DOCKER_HUB_USERNAME }}/${{ env.ANGULAR_IMAGE_NAME }}:${{ github.sha }} 43 | 44 | - name: Build and push Spring Boot Image 45 | id: spring-boot-docker_build 46 | uses: docker/build-push-action@v2 47 | with: 48 | context: ./spring-boot-oauth2-social-login 49 | file: ./spring-boot-oauth2-social-login/Dockerfile 50 | push: true 51 | tags: ${{ secrets.DOCKER_HUB_USERNAME }}/${{ env.SPRING_BOOT_IMAGE_NAME }}:${{ github.sha }} 52 | 53 | - name: Install doctl 54 | uses: digitalocean/action-doctl@v2 55 | with: 56 | token: ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }} 57 | 58 | - name: Save DigitalOcean kubeconfig with short-lived credentials 59 | run: doctl kubernetes cluster kubeconfig save --expiry-seconds 600 k8s-1-20-2-do-0-blr1-1619022201280 60 | 61 | # Deploy Angular & Spring Boot Docker image to the DigitalOcean kubernetes cluster 62 | - name: Deploy 63 | run: |- 64 | kubectl set image deployment/${{env.ANGULAR_DEPLOYMENT_NAME}} ${{env.ANGULAR_CONTAINER_NAME}}=${{ secrets.DOCKER_HUB_USERNAME }}/${{ env.ANGULAR_IMAGE_NAME }}:${{ github.sha }} 65 | kubectl set image deployment/${{env.SPRING_BOOT_DEPLOYMENT_NAME}} ${{ env.SPRING_BOOT_CONTAINER_NAME}}=${{ secrets.DOCKER_HUB_USERNAME }}/${{ env.SPRING_BOOT_IMAGE_NAME }}:${{ github.sha }} 66 | kubectl rollout status deployment/${{env.ANGULAR_DEPLOYMENT_NAME}} 67 | kubectl rollout status deployment/${{env.SPRING_BOOT_DEPLOYMENT_NAME}} 68 | kubectl get services -o wide 69 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Chinna 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Deploy Angular, Spring Boot, and MySQL Application to DigitalOcean Kubernetes in 30 mins 2 | 3 | [Creating Backend - Spring REST API - Part 1](https://www.javachinna.com/spring-boot-angular-two-factor-authentication/) 4 | 5 | [Creating Backend - Spring REST API - Part 2](https://www.javachinna.com/2020/10/23/spring-boot-angular-10-user-registration-oauth2-social-login-part-2/) 6 | 7 | [Creating Angular 10 Client Application - Part 3](https://www.javachinna.com/2020/10/28/spring-boot-angular-10-user-registration-oauth2-social-login-part-3/) 8 | 9 | [Secure Spring Boot Angular Application with Two Factor Authentication](https://www.javachinna.com/spring-boot-angular-two-factor-authentication/) 10 | 11 | [Dockerize Angular with NGINX and Spring Boot with MySQL using Docker Compose](https://www.javachinna.com/angular-nginx-spring-boot-mysql-docker-compose/) 12 | 13 | [Deploy Angular, Spring Boot, and MySQL Application to DigitalOcean Kubernetes in 30 mins](https://www.javachinna.com/deploy-angular-spring-boot-mysql-digitalocean-kubernetes/) 14 | 15 | [Create CI/CD pipeline using GitHub Actions to Build and Deploy Angular Spring Boot App on Kubernetes in 15 mins 16 | ](https://www.javachinna.com/spring-boot-angular-ci-cd-pipeline-github-actions-kubernetes/) 17 | -------------------------------------------------------------------------------- /angular-11-social-login/.browserslistrc: -------------------------------------------------------------------------------- 1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | 5 | # For the full list of supported browsers by the Angular framework, please see: 6 | # https://angular.io/guide/browser-support 7 | 8 | # You can see what browsers were selected by your queries by running: 9 | # npx browserslist 10 | 11 | last 1 Chrome version 12 | last 1 Firefox version 13 | last 2 Edge major versions 14 | last 2 Safari major version 15 | last 2 iOS major versions 16 | Firefox ESR 17 | not IE 9-11 # For IE 9-11 support, remove 'not'. 18 | -------------------------------------------------------------------------------- /angular-11-social-login/.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .git 3 | .gitignore -------------------------------------------------------------------------------- /angular-11-social-login/.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.ts] 12 | quote_type = single 13 | 14 | [*.md] 15 | max_line_length = off 16 | trim_trailing_whitespace = false 17 | -------------------------------------------------------------------------------- /angular-11-social-login/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | # Only exists if Bazel was run 8 | /bazel-out 9 | 10 | # dependencies 11 | /node_modules 12 | 13 | # profiling files 14 | chrome-profiler-events*.json 15 | speed-measure-plugin*.json 16 | 17 | # IDEs and editors 18 | /.idea 19 | .project 20 | .classpath 21 | .c9/ 22 | *.launch 23 | .settings/ 24 | *.sublime-workspace 25 | 26 | # IDE - VSCode 27 | .vscode/* 28 | !.vscode/settings.json 29 | !.vscode/tasks.json 30 | !.vscode/launch.json 31 | !.vscode/extensions.json 32 | .history/* 33 | 34 | # misc 35 | /.sass-cache 36 | /connect.lock 37 | /coverage 38 | /libpeerconnection.log 39 | npm-debug.log 40 | yarn-error.log 41 | testem.log 42 | /typings 43 | 44 | # System Files 45 | .DS_Store 46 | Thumbs.db 47 | -------------------------------------------------------------------------------- /angular-11-social-login/Dockerfile: -------------------------------------------------------------------------------- 1 | #### Stage 1: Build the angular application 2 | FROM node as build 3 | 4 | # Configure the main working directory inside the docker image. 5 | # This is the base directory used in any further RUN, COPY, and ENTRYPOINT 6 | # commands. 7 | WORKDIR /app 8 | 9 | # Copy the package.json as well as the package-lock.json and install 10 | # the dependencies. This is a separate step so the dependencies 11 | # will be cached unless changes to one of those two files 12 | # are made. 13 | COPY package*.json ./ 14 | RUN npm install 15 | 16 | # Copy the main application 17 | COPY . ./ 18 | 19 | # Arguments 20 | ARG configuration=production 21 | 22 | # Build the application 23 | RUN npm run build -- --outputPath=./dist/out --configuration $configuration 24 | 25 | #### Stage 2, use the compiled app, ready for production with Nginx 26 | FROM nginx 27 | 28 | # Copy the angular build from Stage 1 29 | COPY --from=build /app/dist/out/ /usr/share/nginx/html 30 | 31 | # Copy our custom nginx config 32 | COPY /nginx-custom.conf /etc/nginx/conf.d/default.conf 33 | 34 | 35 | # Expose port 80 to the Docker host, so we can access it 36 | # from the outside. 37 | EXPOSE 80 38 | 39 | ENTRYPOINT ["nginx","-g","daemon off;"] -------------------------------------------------------------------------------- /angular-11-social-login/README.md: -------------------------------------------------------------------------------- 1 | # Spring Boot 2 + Angular 10: User Registration and Login using JWT Authentication, OAuth2 Social Login with Facebook, Google, LinkedIn, and Github using Spring Security 5 and Two Factor Authentication (2FA) 2 | 3 | [Creating Backend - Spring REST API - Part 1](https://www.javachinna.com/spring-boot-angular-two-factor-authentication/) 4 | 5 | [Creating Backend - Spring REST API - Part 2](https://www.javachinna.com/2020/10/23/spring-boot-angular-10-user-registration-oauth2-social-login-part-2/) 6 | 7 | [Creating Angular 10 Client Application - Part 3](https://www.javachinna.com/2020/10/28/spring-boot-angular-10-user-registration-oauth2-social-login-part-3/) 8 | 9 | [Secure Spring Boot Angular Application with Two Factor Authentication](https://www.javachinna.com/spring-boot-angular-two-factor-authentication/) -------------------------------------------------------------------------------- /angular-11-social-login/angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema" : "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version" : 1, 4 | "newProjectRoot" : "projects", 5 | "defaultProject" : "Angular11SocialLogin", 6 | "projects" : { 7 | "Angular11SocialLogin" : { 8 | "root" : "", 9 | "sourceRoot" : "src", 10 | "projectType" : "application", 11 | "architect" : { 12 | "build" : { 13 | "builder" : "@angular-devkit/build-angular:browser", 14 | "options" : { 15 | "outputPath" : "dist/Angular11SocialLogin", 16 | "index" : "src/index.html", 17 | "main" : "src/main.ts", 18 | "polyfills" : "src/polyfills.ts", 19 | "tsConfig" : "tsconfig.app.json", 20 | "aot" : true, 21 | "assets" : [ "src/favicon.ico", "src/assets" ], 22 | "styles" : [ "src/styles.css" ], 23 | "scripts" : [ ] 24 | }, 25 | "configurations" : { 26 | "production" : { 27 | "fileReplacements" : [ { 28 | "replace" : "src/environments/environment.ts", 29 | "with" : "src/environments/environment.prod.ts" 30 | } ], 31 | "optimization" : true, 32 | "outputHashing" : "all", 33 | "sourceMap" : false, 34 | "namedChunks" : false, 35 | "extractLicenses" : true, 36 | "vendorChunk" : false, 37 | "buildOptimizer" : true, 38 | "budgets" : [ { 39 | "type" : "initial", 40 | "maximumWarning" : "2mb", 41 | "maximumError" : "5mb" 42 | }, { 43 | "type" : "anyComponentStyle", 44 | "maximumWarning" : "6kb", 45 | "maximumError" : "10kb" 46 | } ] 47 | } 48 | } 49 | }, 50 | "serve" : { 51 | "builder" : "@angular-devkit/build-angular:dev-server", 52 | "options" : { 53 | "browserTarget" : "Angular11SocialLogin:build" 54 | }, 55 | "configurations" : { 56 | "production" : { 57 | "browserTarget" : "Angular11SocialLogin:build:production" 58 | } 59 | } 60 | }, 61 | "extract-i18n" : { 62 | "builder" : "@angular-devkit/build-angular:extract-i18n", 63 | "options" : { 64 | "browserTarget" : "Angular11SocialLogin:build" 65 | } 66 | }, 67 | "test" : { 68 | "builder" : "@angular-devkit/build-angular:karma", 69 | "options" : { 70 | "main" : "src/test.ts", 71 | "polyfills" : "src/polyfills.ts", 72 | "tsConfig" : "tsconfig.spec.json", 73 | "karmaConfig" : "karma.conf.js", 74 | "assets" : [ "src/favicon.ico", "src/assets" ], 75 | "styles" : [ "src/styles.css" ], 76 | "scripts" : [ ] 77 | } 78 | }, 79 | "lint" : { 80 | "builder" : "@angular-devkit/build-angular:tslint", 81 | "options" : { 82 | "tsConfig" : [ "tsconfig.app.json", "tsconfig.spec.json", "e2e/tsconfig.json" ], 83 | "exclude" : [ "**/node_modules/**" ] 84 | } 85 | }, 86 | "e2e" : { 87 | "builder" : "@angular-devkit/build-angular:protractor", 88 | "options" : { 89 | "protractorConfig" : "e2e/protractor.conf.js", 90 | "devServerTarget" : "Angular11SocialLogin:serve" 91 | }, 92 | "configurations" : { 93 | "production" : { 94 | "devServerTarget" : "Angular11SocialLogin:serve:production" 95 | } 96 | } 97 | } 98 | } 99 | }, 100 | "__design__" : { 101 | "root" : "", 102 | "sourceRoot" : ".design", 103 | "projectType" : "application", 104 | "architect" : { 105 | "build" : { 106 | "builder" : "@angular-devkit/build-angular:browser", 107 | "options" : { 108 | "outputPath" : "dist/Angular11SocialLogin", 109 | "index" : ".design/index.html", 110 | "main" : ".design/main.ts", 111 | "polyfills" : ".design/polyfills.ts", 112 | "tsConfig" : "tsconfig.app.json", 113 | "aot" : true, 114 | "assets" : [ ".design/favicon.ico", ".design/assets" ], 115 | "styles" : [ ".design/styles.css" ], 116 | "scripts" : [ ] 117 | }, 118 | "configurations" : { 119 | "production" : { 120 | "fileReplacements" : [ { 121 | "replace" : ".design/environments/environment.ts", 122 | "with" : ".design/environments/environment.prod.ts" 123 | } ], 124 | "optimization" : true, 125 | "outputHashing" : "all", 126 | "sourceMap" : false, 127 | "namedChunks" : false, 128 | "extractLicenses" : true, 129 | "vendorChunk" : false, 130 | "buildOptimizer" : true, 131 | "budgets" : [ { 132 | "type" : "initial", 133 | "maximumWarning" : "2mb", 134 | "maximumError" : "5mb" 135 | }, { 136 | "type" : "anyComponentStyle", 137 | "maximumWarning" : "6kb", 138 | "maximumError" : "10kb" 139 | } ] 140 | } 141 | } 142 | }, 143 | "serve" : { 144 | "builder" : "@angular-devkit/build-angular:dev-server", 145 | "options" : { 146 | "browserTarget" : "__design__:build" 147 | }, 148 | "configurations" : { 149 | "production" : { 150 | "browserTarget" : "__design__:build:production" 151 | } 152 | } 153 | }, 154 | "extract-i18n" : { 155 | "builder" : "@angular-devkit/build-angular:extract-i18n", 156 | "options" : { 157 | "browserTarget" : "__design__:build" 158 | } 159 | }, 160 | "test" : { 161 | "builder" : "@angular-devkit/build-angular:karma", 162 | "options" : { 163 | "main" : ".design/test.ts", 164 | "polyfills" : ".design/polyfills.ts", 165 | "tsConfig" : "tsconfig.spec.json", 166 | "karmaConfig" : "karma.conf.js", 167 | "assets" : [ ".design/favicon.ico", ".design/assets" ], 168 | "styles" : [ ".design/styles.css" ], 169 | "scripts" : [ ] 170 | } 171 | }, 172 | "lint" : { 173 | "builder" : "@angular-devkit/build-angular:tslint", 174 | "options" : { 175 | "tsConfig" : [ "tsconfig.app.json", "tsconfig.spec.json", "e2e/tsconfig.json" ], 176 | "exclude" : [ "**/node_modules/**" ] 177 | } 178 | }, 179 | "e2e" : { 180 | "builder" : "@angular-devkit/build-angular:protractor", 181 | "options" : { 182 | "protractorConfig" : "e2e/protractor.conf.js", 183 | "devServerTarget" : "__design__:serve" 184 | }, 185 | "configurations" : { 186 | "production" : { 187 | "devServerTarget" : "__design__:serve:production" 188 | } 189 | } 190 | } 191 | } 192 | } 193 | }, 194 | "schematics" : null 195 | } -------------------------------------------------------------------------------- /angular-11-social-login/e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | // Protractor configuration file, see link for more information 3 | // https://github.com/angular/protractor/blob/master/lib/config.ts 4 | 5 | const { SpecReporter, StacktraceOption } = require('jasmine-spec-reporter'); 6 | 7 | /** 8 | * @type { import("protractor").Config } 9 | */ 10 | exports.config = { 11 | allScriptsTimeout: 11000, 12 | specs: [ 13 | './src/**/*.e2e-spec.ts' 14 | ], 15 | capabilities: { 16 | browserName: 'chrome' 17 | }, 18 | directConnect: true, 19 | baseUrl: 'http://localhost:4200/', 20 | framework: 'jasmine', 21 | jasmineNodeOpts: { 22 | showColors: true, 23 | defaultTimeoutInterval: 30000, 24 | print: function() {} 25 | }, 26 | onPrepare() { 27 | require('ts-node').register({ 28 | project: require('path').join(__dirname, './tsconfig.json') 29 | }); 30 | jasmine.getEnv().addReporter(new SpecReporter({ 31 | spec: { 32 | displayStacktrace: StacktraceOption.PRETTY 33 | } 34 | })); 35 | } 36 | }; -------------------------------------------------------------------------------- /angular-11-social-login/e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | import { browser, logging } from 'protractor'; 3 | 4 | describe('workspace-project App', () => { 5 | let page: AppPage; 6 | 7 | beforeEach(() => { 8 | page = new AppPage(); 9 | }); 10 | 11 | it('should display welcome message', () => { 12 | page.navigateTo(); 13 | expect(page.getTitleText()).toEqual('Angular10SocialLogin app is running!'); 14 | }); 15 | 16 | afterEach(async () => { 17 | // Assert that there are no errors emitted from the browser 18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER); 19 | expect(logs).not.toContain(jasmine.objectContaining({ 20 | level: logging.Level.SEVERE, 21 | } as logging.Entry)); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /angular-11-social-login/e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo(): Promise { 5 | return browser.get(browser.baseUrl) as Promise; 6 | } 7 | 8 | getTitleText(): Promise { 9 | return element(by.css('app-root .content span')).getText() as Promise; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /angular-11-social-login/e2e/tsconfig.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "../tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "../out-tsc/e2e", 6 | "module": "commonjs", 7 | "target": "es2018", 8 | "types": [ 9 | "jasmine", 10 | "jasminewd2", 11 | "node" 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /angular-11-social-login/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, './coverage/Angular10SocialLogin'), 20 | reports: ['html', 'lcovonly', 'text-summary'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false, 30 | restartOnFileChange: true 31 | }); 32 | }; 33 | -------------------------------------------------------------------------------- /angular-11-social-login/nginx-custom.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 80; 3 | location / { 4 | root /usr/share/nginx/html; 5 | index index.html index.htm; 6 | try_files $uri $uri/ /index.html =404; 7 | } 8 | } -------------------------------------------------------------------------------- /angular-11-social-login/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular10-jwt-auth", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint", 10 | "e2e": "ng e2e" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@angular/animations": "~11.0.2", 15 | "@angular/common": "~11.0.2", 16 | "@angular/compiler": "~11.0.2", 17 | "@angular/core": "~11.0.2", 18 | "@angular/forms": "~11.0.2", 19 | "@angular/platform-browser": "~11.0.2", 20 | "@angular/platform-browser-dynamic": "~11.0.2", 21 | "@angular/router": "~11.0.2", 22 | "rxjs": "~6.5.5", 23 | "tslib": "^2.0.0", 24 | "zone.js": "~0.10.3" 25 | }, 26 | "devDependencies": { 27 | "@angular-devkit/build-angular": "^0.1100.2", 28 | "@angular/cli": "~11.0.2", 29 | "@angular/compiler-cli": "~11.0.2", 30 | "@types/jasmine": "~3.6.0", 31 | "@types/jasminewd2": "~2.0.3", 32 | "@types/node": "^12.11.1", 33 | "codelyzer": "^6.0.0", 34 | "jasmine-core": "~3.6.0", 35 | "jasmine-spec-reporter": "~5.0.0", 36 | "karma": "~5.1.1", 37 | "karma-chrome-launcher": "~3.1.0", 38 | "karma-coverage-istanbul-reporter": "~3.0.2", 39 | "karma-jasmine": "~4.0.0", 40 | "karma-jasmine-html-reporter": "^1.5.0", 41 | "protractor": "~7.0.0", 42 | "ts-node": "~8.3.0", 43 | "tslint": "~6.1.0", 44 | "typescript": "~4.0.5" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/_helpers/auth.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { HTTP_INTERCEPTORS, HttpEvent } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http'; 4 | import { Router } from '@angular/router'; 5 | import { TokenStorageService } from '../_services/token-storage.service'; 6 | import {tap} from 'rxjs/operators'; 7 | import { Observable } from 'rxjs'; 8 | 9 | const TOKEN_HEADER_KEY = 'Authorization'; 10 | 11 | @Injectable() 12 | export class AuthInterceptor implements HttpInterceptor { 13 | constructor(private token: TokenStorageService, private router: Router) { 14 | 15 | } 16 | 17 | intercept(req: HttpRequest, next: HttpHandler): Observable> { 18 | let authReq = req; 19 | const loginPath = '/login'; 20 | const token = this.token.getToken(); 21 | if (token != null) { 22 | authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token) }); 23 | } 24 | return next.handle(authReq).pipe( tap(() => {}, 25 | (err: any) => { 26 | if (err instanceof HttpErrorResponse) { 27 | if (err.status !== 401 || window.location.pathname === loginPath) { 28 | return; 29 | } 30 | this.token.signOut(); 31 | window.location.href = loginPath; 32 | } 33 | } 34 | )); 35 | } 36 | } 37 | 38 | export const authInterceptorProviders = [ 39 | { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } 40 | ]; 41 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/_services/auth.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { AuthService } from './auth.service'; 4 | 5 | describe('AuthService', () => { 6 | let service: AuthService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(AuthService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/_services/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient, HttpHeaders } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | import { AppConstants } from '../common/app.constants'; 5 | 6 | const httpOptions = { 7 | headers: new HttpHeaders({ 'Content-Type': 'application/json' }) 8 | }; 9 | 10 | @Injectable({ 11 | providedIn: 'root' 12 | }) 13 | export class AuthService { 14 | constructor(private http: HttpClient) { } 15 | 16 | login(credentials): Observable { 17 | return this.http.post(AppConstants.AUTH_API + 'signin', { 18 | email: credentials.username, 19 | password: credentials.password 20 | }, httpOptions); 21 | } 22 | 23 | register(user): Observable { 24 | return this.http.post(AppConstants.AUTH_API + 'signup', { 25 | displayName: user.displayName, 26 | email: user.email, 27 | password: user.password, 28 | matchingPassword: user.matchingPassword, 29 | socialProvider: 'LOCAL', 30 | using2FA: user.using2FA 31 | }, httpOptions); 32 | } 33 | 34 | verify(credentials): Observable { 35 | return this.http.post(AppConstants.AUTH_API + 'verify', credentials.code, { 36 | headers: new HttpHeaders({ 'Content-Type': 'text/plain' }) 37 | }); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/_services/token-storage.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { TokenStorageService } from './token-storage.service'; 4 | 5 | describe('TokenStorageService', () => { 6 | let service: TokenStorageService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(TokenStorageService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/_services/token-storage.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | 3 | const TOKEN_KEY = 'auth-token'; 4 | const USER_KEY = 'auth-user'; 5 | 6 | @Injectable({ 7 | providedIn: 'root' 8 | }) 9 | export class TokenStorageService { 10 | 11 | constructor() { } 12 | 13 | signOut(): void { 14 | window.sessionStorage.clear(); 15 | } 16 | 17 | public saveToken(token: string): void { 18 | window.sessionStorage.removeItem(TOKEN_KEY); 19 | window.sessionStorage.setItem(TOKEN_KEY, token); 20 | } 21 | 22 | public getToken(): string { 23 | return sessionStorage.getItem(TOKEN_KEY); 24 | } 25 | 26 | public saveUser(user): void { 27 | window.sessionStorage.removeItem(USER_KEY); 28 | window.sessionStorage.setItem(USER_KEY, JSON.stringify(user)); 29 | } 30 | 31 | public getUser(): any { 32 | return JSON.parse(sessionStorage.getItem(USER_KEY)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/_services/user.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { UserService } from './user.service'; 4 | 5 | describe('UserService', () => { 6 | let service: UserService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(UserService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/_services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient, HttpHeaders } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | import { AppConstants } from '../common/app.constants'; 5 | 6 | const httpOptions = { 7 | headers: new HttpHeaders({ 'Content-Type': 'application/json' }) 8 | }; 9 | 10 | 11 | @Injectable({ 12 | providedIn: 'root' 13 | }) 14 | export class UserService { 15 | 16 | constructor(private http: HttpClient) { } 17 | 18 | getPublicContent(): Observable { 19 | return this.http.get(AppConstants.API_URL + 'all', { responseType: 'text' }); 20 | } 21 | 22 | getUserBoard(): Observable { 23 | return this.http.get(AppConstants.API_URL + 'user', { responseType: 'text' }); 24 | } 25 | 26 | getModeratorBoard(): Observable { 27 | return this.http.get(AppConstants.API_URL + 'mod', { responseType: 'text' }); 28 | } 29 | 30 | getAdminBoard(): Observable { 31 | return this.http.get(AppConstants.API_URL + 'admin', { responseType: 'text' }); 32 | } 33 | 34 | getCurrentUser(): Observable { 35 | return this.http.get(AppConstants.API_URL + 'user/me', httpOptions); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | 4 | import { RegisterComponent } from './register/register.component'; 5 | import { LoginComponent } from './login/login.component'; 6 | import { HomeComponent } from './home/home.component'; 7 | import { ProfileComponent } from './profile/profile.component'; 8 | import { BoardUserComponent } from './board-user/board-user.component'; 9 | import { BoardModeratorComponent } from './board-moderator/board-moderator.component'; 10 | import { BoardAdminComponent } from './board-admin/board-admin.component'; 11 | import { TotpComponent } from './totp/totp.component'; 12 | 13 | const routes: Routes = [ 14 | { path: 'home', component: HomeComponent }, 15 | { path: 'login', component: LoginComponent }, 16 | { path: 'register', component: RegisterComponent }, 17 | { path: 'profile', component: ProfileComponent }, 18 | { path: 'user', component: BoardUserComponent }, 19 | { path: 'mod', component: BoardModeratorComponent }, 20 | { path: 'admin', component: BoardAdminComponent }, 21 | { path: 'totp', component: TotpComponent }, 22 | { path: '', redirectTo: 'home', pathMatch: 'full' } 23 | ]; 24 | 25 | @NgModule({ 26 | imports: [RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' })], 27 | exports: [RouterModule] 28 | }) 29 | export class AppRoutingModule { } 30 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/angular-11-social-login/src/app/app.component.css -------------------------------------------------------------------------------- /angular-11-social-login/src/app/app.component.html: -------------------------------------------------------------------------------- 1 |
2 | 21 |
22 | 23 |
24 |
-------------------------------------------------------------------------------- /angular-11-social-login/src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, waitForAsync } from '@angular/core/testing'; 2 | import { RouterTestingModule } from '@angular/router/testing'; 3 | import { AppComponent } from './app.component'; 4 | 5 | describe('AppComponent', () => { 6 | beforeEach(waitForAsync(() => { 7 | TestBed.configureTestingModule({ 8 | imports: [ 9 | RouterTestingModule 10 | ], 11 | declarations: [ 12 | AppComponent 13 | ], 14 | }).compileComponents(); 15 | })); 16 | 17 | it('should create the app', () => { 18 | const fixture = TestBed.createComponent(AppComponent); 19 | const app = fixture.componentInstance; 20 | expect(app).toBeTruthy(); 21 | }); 22 | 23 | it(`should have as title 'Angular10SocialLogin'`, () => { 24 | const fixture = TestBed.createComponent(AppComponent); 25 | const app = fixture.componentInstance; 26 | expect(app.title).toEqual('Angular10SocialLogin'); 27 | }); 28 | 29 | it('should render title', () => { 30 | const fixture = TestBed.createComponent(AppComponent); 31 | fixture.detectChanges(); 32 | const compiled = fixture.nativeElement; 33 | expect(compiled.querySelector('.content span').textContent).toContain('Angular10SocialLogin app is running!'); 34 | }); 35 | }); 36 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { TokenStorageService } from './_services/token-storage.service'; 3 | 4 | @Component({ 5 | selector: 'app-root', 6 | templateUrl: './app.component.html', 7 | styleUrls: ['./app.component.css'] 8 | }) 9 | export class AppComponent implements OnInit { 10 | private roles: string[]; 11 | isLoggedIn = false; 12 | showAdminBoard = false; 13 | showModeratorBoard = false; 14 | username: string; 15 | 16 | constructor(private tokenStorageService: TokenStorageService) { } 17 | 18 | ngOnInit(): void { 19 | this.isLoggedIn = !!this.tokenStorageService.getUser(); 20 | 21 | if (this.isLoggedIn) { 22 | const user = this.tokenStorageService.getUser(); 23 | this.roles = user.roles; 24 | 25 | this.showAdminBoard = this.roles.includes('ROLE_ADMIN'); 26 | this.showModeratorBoard = this.roles.includes('ROLE_MODERATOR'); 27 | 28 | this.username = user.displayName; 29 | } 30 | } 31 | 32 | logout(): void { 33 | this.tokenStorageService.signOut(); 34 | window.location.reload(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | 4 | import { AppRoutingModule } from './app-routing.module'; 5 | import { FormsModule } from '@angular/forms'; 6 | import { HttpClientModule } from '@angular/common/http'; 7 | 8 | import { AppComponent } from './app.component'; 9 | import { LoginComponent } from './login/login.component'; 10 | import { RegisterComponent } from './register/register.component'; 11 | import { HomeComponent } from './home/home.component'; 12 | import { ProfileComponent } from './profile/profile.component'; 13 | import { BoardAdminComponent } from './board-admin/board-admin.component'; 14 | import { BoardModeratorComponent } from './board-moderator/board-moderator.component'; 15 | import { BoardUserComponent } from './board-user/board-user.component'; 16 | import { TotpComponent } from './totp/totp.component'; 17 | 18 | import { authInterceptorProviders } from './_helpers/auth.interceptor'; 19 | 20 | @NgModule({ 21 | declarations: [ 22 | AppComponent, 23 | LoginComponent, 24 | RegisterComponent, 25 | HomeComponent, 26 | ProfileComponent, 27 | BoardAdminComponent, 28 | BoardModeratorComponent, 29 | BoardUserComponent, 30 | TotpComponent 31 | ], 32 | imports: [ 33 | BrowserModule, 34 | AppRoutingModule, 35 | FormsModule, 36 | HttpClientModule 37 | ], 38 | providers: [authInterceptorProviders], 39 | bootstrap: [AppComponent] 40 | }) 41 | export class AppModule { } 42 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-admin/board-admin.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/angular-11-social-login/src/app/board-admin/board-admin.component.css -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-admin/board-admin.component.html: -------------------------------------------------------------------------------- 1 |
2 |
{{ content }}
3 |
4 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-admin/board-admin.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { BoardAdminComponent } from './board-admin.component'; 4 | 5 | describe('BoardAdminComponent', () => { 6 | let component: BoardAdminComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ BoardAdminComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(BoardAdminComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-admin/board-admin.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-board-admin', 6 | templateUrl: './board-admin.component.html', 7 | styleUrls: ['./board-admin.component.css'] 8 | }) 9 | export class BoardAdminComponent implements OnInit { 10 | 11 | content: string; 12 | 13 | constructor(private userService: UserService) { } 14 | 15 | ngOnInit(): void { 16 | this.userService.getAdminBoard().subscribe( 17 | data => { 18 | this.content = data; 19 | }, 20 | err => { 21 | this.content = JSON.parse(err.error).message; 22 | } 23 | ); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-moderator/board-moderator.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/angular-11-social-login/src/app/board-moderator/board-moderator.component.css -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-moderator/board-moderator.component.html: -------------------------------------------------------------------------------- 1 |
2 |
{{ content }}
3 |
4 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-moderator/board-moderator.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { BoardModeratorComponent } from './board-moderator.component'; 4 | 5 | describe('BoardModeratorComponent', () => { 6 | let component: BoardModeratorComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ BoardModeratorComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(BoardModeratorComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-moderator/board-moderator.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-board-moderator', 6 | templateUrl: './board-moderator.component.html', 7 | styleUrls: ['./board-moderator.component.css'] 8 | }) 9 | export class BoardModeratorComponent implements OnInit { 10 | 11 | content: string; 12 | 13 | constructor(private userService: UserService) { } 14 | 15 | ngOnInit(): void { 16 | this.userService.getModeratorBoard().subscribe( 17 | data => { 18 | this.content = data; 19 | }, 20 | err => { 21 | this.content = JSON.parse(err.error).message; 22 | } 23 | ); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-user/board-user.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/angular-11-social-login/src/app/board-user/board-user.component.css -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-user/board-user.component.html: -------------------------------------------------------------------------------- 1 |
2 |
{{ content }}
3 |
4 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-user/board-user.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { BoardUserComponent } from './board-user.component'; 4 | 5 | describe('BoardUserComponent', () => { 6 | let component: BoardUserComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ BoardUserComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(BoardUserComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-user/board-user.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-board-user', 6 | templateUrl: './board-user.component.html', 7 | styleUrls: ['./board-user.component.css'] 8 | }) 9 | export class BoardUserComponent implements OnInit { 10 | 11 | content: string; 12 | 13 | constructor(private userService: UserService) { } 14 | 15 | ngOnInit(): void { 16 | this.userService.getUserBoard().subscribe( 17 | data => { 18 | this.content = data; 19 | }, 20 | err => { 21 | this.content = JSON.parse(err.error).message; 22 | } 23 | ); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/common/app.constants.ts: -------------------------------------------------------------------------------- 1 | import { environment } from '../../environments/environment'; 2 | 3 | export class AppConstants { 4 | private static API_BASE_URL = environment.apiBaseUrl; 5 | private static OAUTH2_URL = AppConstants.API_BASE_URL + "oauth2/authorization/"; 6 | private static REDIRECT_URL = environment.clientUrl; 7 | public static API_URL = AppConstants.API_BASE_URL + "api/"; 8 | public static AUTH_API = AppConstants.API_URL + "auth/"; 9 | public static GOOGLE_AUTH_URL = AppConstants.OAUTH2_URL + "google" + AppConstants.REDIRECT_URL; 10 | public static FACEBOOK_AUTH_URL = AppConstants.OAUTH2_URL + "facebook" + AppConstants.REDIRECT_URL; 11 | public static GITHUB_AUTH_URL = AppConstants.OAUTH2_URL + "github" + AppConstants.REDIRECT_URL; 12 | public static LINKEDIN_AUTH_URL = AppConstants.OAUTH2_URL + "linkedin" + AppConstants.REDIRECT_URL; 13 | } -------------------------------------------------------------------------------- /angular-11-social-login/src/app/home/home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/angular-11-social-login/src/app/home/home.component.css -------------------------------------------------------------------------------- /angular-11-social-login/src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |
2 |
{{ content }}
3 |
4 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/home/home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { HomeComponent } from './home.component'; 4 | 5 | describe('HomeComponent', () => { 6 | let component: HomeComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ HomeComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(HomeComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-home', 6 | templateUrl: './home.component.html', 7 | styleUrls: ['./home.component.css'] 8 | }) 9 | export class HomeComponent implements OnInit { 10 | 11 | content: string; 12 | 13 | constructor(private userService: UserService) { } 14 | 15 | ngOnInit(): void { 16 | this.userService.getPublicContent().subscribe( 17 | data => { 18 | this.content = data; 19 | }, 20 | err => { 21 | this.content = JSON.parse(err.error).message; 22 | } 23 | ); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/login/login.component.css: -------------------------------------------------------------------------------- 1 | label { 2 | display: block; 3 | margin-top: 10px; 4 | } 5 | 6 | .card-container.card { 7 | max-width: 400px !important; 8 | padding: 40px 40px; 9 | } 10 | 11 | .card { 12 | background-color: #f7f7f7; 13 | padding: 20px 25px 30px; 14 | margin: 0 auto 25px; 15 | margin-top: 50px; 16 | -moz-border-radius: 2px; 17 | -webkit-border-radius: 2px; 18 | border-radius: 2px; 19 | -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 20 | -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 21 | box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 22 | } 23 | 24 | .profile-img-card { 25 | width: 96px; 26 | height: 96px; 27 | margin: 0 auto 10px; 28 | display: block; 29 | -moz-border-radius: 50%; 30 | -webkit-border-radius: 50%; 31 | border-radius: 50%; 32 | } 33 | 34 | .content-divider.center { 35 | text-align: center; 36 | } 37 | 38 | .content-divider { 39 | position: relative; 40 | z-index: 1; 41 | } 42 | 43 | .content-divider>span, .content-divider>a { 44 | background-color: #fff; 45 | color: #000; 46 | display: inline-block; 47 | padding: 2px 12px; 48 | border-radius: 3px; 49 | text-transform: uppercase; 50 | font-weight: 500; 51 | } 52 | 53 | .content-divider>span:before, .content-divider>a:before { 54 | content: ""; 55 | position: absolute; 56 | top: 50%; 57 | left: 0; 58 | height: 1px; 59 | background-color: #ddd; 60 | width: 100%; 61 | z-index: -1; 62 | } 63 | 64 | .social-login .btn-img { 65 | width: 30px; 66 | height: auto; 67 | padding: 0.6rem 0; 68 | margin-right: 15px; 69 | } 70 | 71 | .btn-img-linkedin { 72 | width: auto; 73 | height: 50px; 74 | padding: 0.6rem 0; 75 | margin-right: 10px; 76 | } 77 | 78 | .form-group .has-error { 79 | color: red; 80 | } -------------------------------------------------------------------------------- /angular-11-social-login/src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 |
6 | 7 | 8 |
9 |
10 | 12 | 16 |
17 |
18 | 19 |
20 |
21 | 22 |
23 |
24 |

25 | or 26 |

27 | 42 |
43 |
44 |
Welcome {{currentUser.displayName}}
Logged in as {{ currentUser.roles }}.
45 |
46 |
47 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/login/login.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { LoginComponent } from './login.component'; 4 | 5 | describe('LoginComponent', () => { 6 | let component: LoginComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ LoginComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(LoginComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthService } from '../_services/auth.service'; 3 | import { UserService } from '../_services/user.service'; 4 | import { TokenStorageService } from '../_services/token-storage.service'; 5 | import { Router, ActivatedRoute } from '@angular/router'; 6 | import { AppConstants } from '../common/app.constants'; 7 | 8 | 9 | @Component({ 10 | selector: 'app-login', 11 | templateUrl: './login.component.html', 12 | styleUrls: ['./login.component.css'] 13 | }) 14 | export class LoginComponent implements OnInit { 15 | 16 | form: any = {}; 17 | isLoggedIn = false; 18 | isLoginFailed = false; 19 | errorMessage = ''; 20 | currentUser: any; 21 | googleURL = AppConstants.GOOGLE_AUTH_URL; 22 | facebookURL = AppConstants.FACEBOOK_AUTH_URL; 23 | githubURL = AppConstants.GITHUB_AUTH_URL; 24 | linkedinURL = AppConstants.LINKEDIN_AUTH_URL; 25 | 26 | constructor(private authService: AuthService, private tokenStorage: TokenStorageService, private route: ActivatedRoute, private userService: UserService, private router: Router) {} 27 | 28 | ngOnInit(): void { 29 | const token: string = this.route.snapshot.queryParamMap.get('token'); 30 | const error: string = this.route.snapshot.queryParamMap.get('error'); 31 | if (this.tokenStorage.getUser()) { 32 | this.isLoggedIn = true; 33 | this.currentUser = this.tokenStorage.getUser(); 34 | } 35 | else if(token){ 36 | this.tokenStorage.saveToken(token); 37 | this.userService.getCurrentUser().subscribe( 38 | data => { 39 | this.login(data); 40 | }, 41 | err => { 42 | this.errorMessage = err.error.message; 43 | this.isLoginFailed = true; 44 | } 45 | ); 46 | } 47 | else if(error){ 48 | this.errorMessage = error; 49 | this.isLoginFailed = true; 50 | } 51 | } 52 | 53 | onSubmit(): void { 54 | this.authService.login(this.form).subscribe( 55 | data => { 56 | this.tokenStorage.saveToken(data.accessToken); 57 | if(data.authenticated){ 58 | this.login(data.user); 59 | } else { 60 | this.router.navigate(['/totp']); 61 | } 62 | }, 63 | err => { 64 | this.errorMessage = err.error.message; 65 | this.isLoginFailed = true; 66 | } 67 | ); 68 | } 69 | 70 | login(user): void { 71 | this.tokenStorage.saveUser(user); 72 | this.isLoginFailed = false; 73 | this.isLoggedIn = true; 74 | this.currentUser = this.tokenStorage.getUser(); 75 | window.location.reload(); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/profile/profile.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/angular-11-social-login/src/app/profile/profile.component.css -------------------------------------------------------------------------------- /angular-11-social-login/src/app/profile/profile.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 | {{ currentUser.displayName }} Profile 5 |
6 |
7 |

8 | Email: {{ currentUser.email }} 9 |

10 | Roles: 11 |
    12 |
  • {{ role }}
  • 13 |
14 |
15 | Please login. 16 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/profile/profile.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { ProfileComponent } from './profile.component'; 4 | 5 | describe('ProfileComponent', () => { 6 | let component: ProfileComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ProfileComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ProfileComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/profile/profile.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { TokenStorageService } from '../_services/token-storage.service'; 3 | 4 | @Component({ 5 | selector: 'app-profile', 6 | templateUrl: './profile.component.html', 7 | styleUrls: ['./profile.component.css'] 8 | }) 9 | export class ProfileComponent implements OnInit { 10 | 11 | currentUser: any; 12 | 13 | constructor(private token: TokenStorageService) { } 14 | 15 | ngOnInit(): void { 16 | this.currentUser = this.token.getUser(); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/register/register.component.css: -------------------------------------------------------------------------------- 1 | label { 2 | display: block; 3 | margin-top: 10px; 4 | } 5 | 6 | .card-container.card { 7 | max-width: 400px !important; 8 | padding: 40px 40px; 9 | } 10 | 11 | .card { 12 | background-color: #f7f7f7; 13 | padding: 20px 25px 30px; 14 | margin: 0 auto 25px; 15 | margin-top: 50px; 16 | -moz-border-radius: 2px; 17 | -webkit-border-radius: 2px; 18 | border-radius: 2px; 19 | -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 20 | -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 21 | box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 22 | } 23 | 24 | .profile-img-card { 25 | width: 96px; 26 | height: 96px; 27 | margin: 0 auto 10px; 28 | display: block; 29 | -moz-border-radius: 50%; 30 | -webkit-border-radius: 50%; 31 | border-radius: 50%; 32 | } -------------------------------------------------------------------------------- /angular-11-social-login/src/app/register/register.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 |
6 | 8 |
9 |
Display Name is required
10 |
Display Name must be at least 3 characters
11 |
Display Name must be at most 20 characters
12 |
13 |
14 |
15 | 16 |
17 |
Email is required
18 |
Email must be a valid email address
19 |
20 |
21 |
22 | 24 |
25 |
Password is required
26 |
Password must be at least 6 characters
27 |
28 |
29 |
30 | 32 |
33 |
Confirm Password is required
34 |
Confirm Password must be at least 6 characters
35 |
36 |
37 |
38 | 40 |
41 |
42 | 43 |
44 |
45 | Signup failed!
{{ errorMessage }} 46 |
47 |
48 |
49 | Your registration is successful! 50 |
51 |

Scan this QR code using Google Authenticator app on your phone to use it later to login

52 | 53 |
54 |
55 |
56 |
57 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/register/register.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { RegisterComponent } from './register.component'; 4 | 5 | describe('RegisterComponent', () => { 6 | let component: RegisterComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ RegisterComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(RegisterComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/register/register.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthService } from '../_services/auth.service'; 3 | 4 | @Component({ 5 | selector: 'app-register', 6 | templateUrl: './register.component.html', 7 | styleUrls: ['./register.component.css'] 8 | }) 9 | export class RegisterComponent implements OnInit { 10 | 11 | form: any = {}; 12 | isSuccessful = false; 13 | isSignUpFailed = false; 14 | isUsing2FA = false; 15 | errorMessage = ''; 16 | qrCodeImage = ''; 17 | 18 | constructor(private authService: AuthService) { } 19 | 20 | ngOnInit(): void { 21 | } 22 | 23 | onSubmit(): void { 24 | this.authService.register(this.form).subscribe( 25 | data => { 26 | console.log(data); 27 | if(data.using2FA){ 28 | this.isUsing2FA = true; 29 | this.qrCodeImage = data.qrCodeImage; 30 | } 31 | this.isSuccessful = true; 32 | this.isSignUpFailed = false; 33 | }, 34 | err => { 35 | this.errorMessage = err.error.message; 36 | this.isSignUpFailed = true; 37 | } 38 | ); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/totp/totp.component.css: -------------------------------------------------------------------------------- 1 | .card-container.card { 2 | max-width: 400px !important; 3 | padding: 40px 40px; 4 | } 5 | 6 | .card { 7 | background-color: #f7f7f7; 8 | padding: 20px 25px 30px; 9 | margin: 0 auto 25px; 10 | margin-top: 50px; 11 | -moz-border-radius: 2px; 12 | -webkit-border-radius: 2px; 13 | border-radius: 2px; 14 | -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 15 | -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 16 | box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 17 | } 18 | 19 | .profile-img-card { 20 | width: 96px; 21 | height: 96px; 22 | margin: 0 auto 10px; 23 | display: block; 24 | -moz-border-radius: 50%; 25 | -webkit-border-radius: 50%; 26 | border-radius: 50%; 27 | } -------------------------------------------------------------------------------- /angular-11-social-login/src/app/totp/totp.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 |
6 | 7 | 11 |
12 |
13 | 14 |
15 |
16 | 17 |
18 |
19 |
Welcome {{currentUser.displayName}}
Logged in as {{ currentUser.roles }}.
20 |
21 |
22 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/totp/totp.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthService } from '../_services/auth.service'; 3 | import { TokenStorageService } from '../_services/token-storage.service'; 4 | 5 | 6 | @Component({ 7 | selector: 'app-totp', 8 | templateUrl: './totp.component.html', 9 | styleUrls: ['./totp.component.css'] 10 | }) 11 | export class TotpComponent implements OnInit { 12 | 13 | form: any = {}; 14 | isLoggedIn = false; 15 | isLoginFailed = false; 16 | errorMessage = ''; 17 | currentUser: any; 18 | 19 | constructor(private authService: AuthService, private tokenStorage: TokenStorageService) {} 20 | 21 | ngOnInit(): void { 22 | if (this.tokenStorage.getUser()) { 23 | this.isLoggedIn = true; 24 | this.currentUser = this.tokenStorage.getUser(); 25 | } 26 | } 27 | 28 | onSubmit(): void { 29 | this.authService.verify(this.form).subscribe( 30 | data => { 31 | this.tokenStorage.saveToken(data.accessToken); 32 | this.login(data.user); 33 | }, 34 | err => { 35 | this.errorMessage = err.error.message; 36 | this.isLoginFailed = true; 37 | } 38 | ); 39 | } 40 | 41 | login(user): void { 42 | this.tokenStorage.saveUser(user); 43 | this.isLoginFailed = false; 44 | this.isLoggedIn = true; 45 | this.currentUser = this.tokenStorage.getUser(); 46 | window.location.reload(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /angular-11-social-login/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/angular-11-social-login/src/assets/.gitkeep -------------------------------------------------------------------------------- /angular-11-social-login/src/assets/img/facebook.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/angular-11-social-login/src/assets/img/facebook.png -------------------------------------------------------------------------------- /angular-11-social-login/src/assets/img/github.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/angular-11-social-login/src/assets/img/github.png -------------------------------------------------------------------------------- /angular-11-social-login/src/assets/img/google.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/angular-11-social-login/src/assets/img/google.png -------------------------------------------------------------------------------- /angular-11-social-login/src/assets/img/linkedin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/angular-11-social-login/src/assets/img/linkedin.png -------------------------------------------------------------------------------- /angular-11-social-login/src/assets/img/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/angular-11-social-login/src/assets/img/logo.png -------------------------------------------------------------------------------- /angular-11-social-login/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | apiBaseUrl: 'https://server.javachinna.xyz/', 4 | clientUrl: '?redirect_uri=https://client.javachinna.xyz/login' 5 | }; 6 | -------------------------------------------------------------------------------- /angular-11-social-login/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false, 7 | apiBaseUrl: 'http://localhost:8080/', 8 | clientUrl: '?redirect_uri=http://localhost:8081/login' 9 | }; 10 | 11 | /* 12 | * For easier debugging in development mode, you can import the following file 13 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 14 | * 15 | * This import should be commented out in production mode because it will have a negative impact 16 | * on performance if an error is thrown. 17 | */ 18 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 19 | -------------------------------------------------------------------------------- /angular-11-social-login/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/angular-11-social-login/src/favicon.ico -------------------------------------------------------------------------------- /angular-11-social-login/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular11SocialLogin 6 | 7 | 8 | 9 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /angular-11-social-login/src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /angular-11-social-login/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 22 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 23 | 24 | /** 25 | * Web Animations `@angular/platform-browser/animations` 26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 28 | */ 29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 30 | 31 | /** 32 | * By default, zone.js will patch all possible macroTask and DomEvents 33 | * user can disable parts of macroTask/DomEvents patch by setting following flags 34 | * because those flags need to be set before `zone.js` being loaded, and webpack 35 | * will put import in the top of bundle, so user need to create a separate file 36 | * in this directory (for example: zone-flags.ts), and put the following flags 37 | * into that file, and then add the following code before importing zone.js. 38 | * import './zone-flags'; 39 | * 40 | * The flags allowed in zone-flags.ts are listed here. 41 | * 42 | * The following flags will work for all browsers. 43 | * 44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 47 | * 48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 50 | * 51 | * (window as any).__Zone_enable_cross_context_check = true; 52 | * 53 | */ 54 | 55 | /*************************************************************************************************** 56 | * Zone JS is required by default for Angular itself. 57 | */ 58 | import 'zone.js/dist/zone'; // Included with Angular CLI. 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | -------------------------------------------------------------------------------- /angular-11-social-login/src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /angular-11-social-login/src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/zone-testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: { 11 | context(path: string, deep?: boolean, filter?: RegExp): { 12 | keys(): string[]; 13 | (id: string): T; 14 | }; 15 | }; 16 | 17 | // First, initialize the Angular testing environment. 18 | getTestBed().initTestEnvironment( 19 | BrowserDynamicTestingModule, 20 | platformBrowserDynamicTesting() 21 | ); 22 | // Then we find all the tests. 23 | const context = require.context('./', true, /\.spec\.ts$/); 24 | // And load the modules. 25 | context.keys().map(context); 26 | -------------------------------------------------------------------------------- /angular-11-social-login/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/app", 6 | "types": [] 7 | }, 8 | "files": [ 9 | "src/main.ts", 10 | "src/polyfills.ts" 11 | ], 12 | "include": [ 13 | "src/**/*.d.ts" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /angular-11-social-login/tsconfig.base.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "compileOnSave": false, 4 | "compilerOptions": { 5 | "baseUrl": "./", 6 | "outDir": "./dist/out-tsc", 7 | "sourceMap": true, 8 | "declaration": false, 9 | "downlevelIteration": true, 10 | "experimentalDecorators": true, 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "target": "es2015", 14 | "module": "es2020", 15 | "lib": [ 16 | "es2018", 17 | "dom" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /angular-11-social-login/tsconfig.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "compileOnSave": false, 4 | "compilerOptions": { 5 | "baseUrl": "./", 6 | "outDir": "./dist/out-tsc", 7 | "sourceMap": true, 8 | "declaration": false, 9 | "downlevelIteration": true, 10 | "experimentalDecorators": true, 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "target": "es2015", 14 | "module": "es2020", 15 | "lib": [ 16 | "es2018", 17 | "dom" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /angular-11-social-login/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/spec", 6 | "types": [ 7 | "jasmine" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts", 12 | "src/polyfills.ts" 13 | ], 14 | "include": [ 15 | "src/**/*.spec.ts", 16 | "src/**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /angular-11-social-login/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rules": { 4 | "align": { 5 | "options": [ 6 | "parameters", 7 | "statements" 8 | ] 9 | }, 10 | "array-type": false, 11 | "arrow-return-shorthand": true, 12 | "curly": true, 13 | "deprecation": { 14 | "severity": "warning" 15 | }, 16 | "component-class-suffix": true, 17 | "contextual-lifecycle": true, 18 | "directive-class-suffix": true, 19 | "directive-selector": [ 20 | true, 21 | "attribute", 22 | "app", 23 | "camelCase" 24 | ], 25 | "component-selector": [ 26 | true, 27 | "element", 28 | "app", 29 | "kebab-case" 30 | ], 31 | "eofline": true, 32 | "import-blacklist": [ 33 | true, 34 | "rxjs/Rx" 35 | ], 36 | "import-spacing": true, 37 | "indent": { 38 | "options": [ 39 | "spaces" 40 | ] 41 | }, 42 | "max-classes-per-file": false, 43 | "max-line-length": [ 44 | true, 45 | 140 46 | ], 47 | "member-ordering": [ 48 | true, 49 | { 50 | "order": [ 51 | "static-field", 52 | "instance-field", 53 | "static-method", 54 | "instance-method" 55 | ] 56 | } 57 | ], 58 | "no-console": [ 59 | true, 60 | "debug", 61 | "info", 62 | "time", 63 | "timeEnd", 64 | "trace" 65 | ], 66 | "no-empty": false, 67 | "no-inferrable-types": [ 68 | true, 69 | "ignore-params" 70 | ], 71 | "no-non-null-assertion": true, 72 | "no-redundant-jsdoc": true, 73 | "no-switch-case-fall-through": true, 74 | "no-var-requires": false, 75 | "object-literal-key-quotes": [ 76 | true, 77 | "as-needed" 78 | ], 79 | "quotemark": [ 80 | true, 81 | "single" 82 | ], 83 | "semicolon": { 84 | "options": [ 85 | "always" 86 | ] 87 | }, 88 | "space-before-function-paren": { 89 | "options": { 90 | "anonymous": "never", 91 | "asyncArrow": "always", 92 | "constructor": "never", 93 | "method": "never", 94 | "named": "never" 95 | } 96 | }, 97 | "typedef": [ 98 | true, 99 | "call-signature" 100 | ], 101 | "typedef-whitespace": { 102 | "options": [ 103 | { 104 | "call-signature": "nospace", 105 | "index-signature": "nospace", 106 | "parameter": "nospace", 107 | "property-declaration": "nospace", 108 | "variable-declaration": "nospace" 109 | }, 110 | { 111 | "call-signature": "onespace", 112 | "index-signature": "onespace", 113 | "parameter": "onespace", 114 | "property-declaration": "onespace", 115 | "variable-declaration": "onespace" 116 | } 117 | ] 118 | }, 119 | "variable-name": { 120 | "options": [ 121 | "ban-keywords", 122 | "check-format", 123 | "allow-pascal-case" 124 | ] 125 | }, 126 | "whitespace": { 127 | "options": [ 128 | "check-branch", 129 | "check-decl", 130 | "check-operator", 131 | "check-separator", 132 | "check-type", 133 | "check-typecast" 134 | ] 135 | }, 136 | "no-conflicting-lifecycle": true, 137 | "no-host-metadata-property": true, 138 | "no-input-rename": true, 139 | "no-inputs-metadata-property": true, 140 | "no-output-native": true, 141 | "no-output-on-prefix": true, 142 | "no-output-rename": true, 143 | "no-outputs-metadata-property": true, 144 | "template-banana-in-box": true, 145 | "template-no-negated-async": true, 146 | "use-lifecycle-interface": true, 147 | "use-pipe-transform-interface": true 148 | }, 149 | "rulesDirectory": [ 150 | "codelyzer" 151 | ] 152 | } -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | # Docker Compose file Reference (https://docs.docker.com/compose/compose-file/) 2 | version: '3.7' 3 | 4 | # Define services 5 | services: 6 | # App backend service 7 | app-server: 8 | # Configuration for building the docker image for the backend service 9 | build: 10 | context: spring-boot-oauth2-social-login # Use an image built from the specified dockerfile in the `spring-boot-oauth2-social-login` directory. 11 | dockerfile: Dockerfile 12 | ports: 13 | - "8080:8080" # Forward the exposed port 8080 on the container to port 8080 on the host machine 14 | restart: always 15 | depends_on: 16 | - db # This service depends on mysql. Start that first. 17 | environment: # Pass environment variables to the service 18 | SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/demo?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false&allowPublicKeyRetrieval=true 19 | SPRING_DATASOURCE_USERNAME: javachinna 20 | SPRING_DATASOURCE_PASSWORD: javachinna 21 | networks: # Networks to join (Services on the same network can communicate with each other using their name) 22 | - backend 23 | - frontend 24 | 25 | # Frontend Service 26 | app-client: 27 | build: 28 | context: angular-11-social-login # Use an image built from the specified dockerfile in the `angular-11-social-login` directory. 29 | dockerfile: Dockerfile 30 | ports: 31 | - "8081:80" # Map the exposed port 80 on the container to port 8081 on the host machine 32 | restart: always 33 | depends_on: 34 | - app-server 35 | networks: 36 | - frontend 37 | 38 | # Database Service (Mysql) 39 | db: 40 | image: mysql:8.0 41 | ports: 42 | - "3306:3306" 43 | restart: always 44 | environment: 45 | MYSQL_DATABASE: demo 46 | MYSQL_USER: javachinna 47 | MYSQL_PASSWORD: javachinna 48 | MYSQL_ROOT_PASSWORD: root 49 | networks: 50 | - backend 51 | 52 | # Networks to be created to facilitate communication between containers 53 | networks: 54 | backend: 55 | frontend: -------------------------------------------------------------------------------- /k8s/app-client.yml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 # API version 2 | kind: Deployment # Type of kubernetes resource 3 | metadata: 4 | name: social-login-app-client # Name of the kubernetes resource 5 | spec: 6 | replicas: 1 # No of replicas/pods to run 7 | selector: 8 | matchLabels: # This deployment applies to Pods matching the specified labels 9 | app: social-login-app-client 10 | template: # Template for creating the Pods in this deployment 11 | metadata: 12 | labels: # Labels that will be applied to all the Pods in this deployment 13 | app: social-login-app-client 14 | spec: # Spec for the containers that will run inside the Pods 15 | containers: 16 | - name: social-login-app-client 17 | image: javachinna/social-login-app-client:1.0.0 18 | imagePullPolicy: Always 19 | ports: 20 | - name: http 21 | containerPort: 80 # Should match the Port that the container listens on 22 | resources: 23 | limits: 24 | cpu: 0.2 25 | memory: "10Mi" 26 | --- 27 | apiVersion: v1 # API version 28 | kind: Service # Type of kubernetes resource 29 | metadata: 30 | name: social-login-app-client # Name of the kubernetes resource 31 | spec: 32 | type: NodePort # Exposes the service by opening a port on each node 33 | selector: 34 | app: social-login-app-client # Any Pod matching the label `app=social-login-app-client` will be picked up by this service 35 | ports: # Forward incoming connections on port 8081 to the target port 80 in the Pod 36 | - name: http 37 | port: 8081 38 | targetPort: 80 -------------------------------------------------------------------------------- /k8s/app-server.yml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: apps/v1 # API version 3 | kind: Deployment # Type of kubernetes resource 4 | metadata: 5 | name: social-login-app-server # Name of the kubernetes resource 6 | labels: # Labels that will be applied to this resource 7 | app: social-login-app-server 8 | spec: 9 | replicas: 1 # No. of replicas/pods to run in this deployment 10 | selector: 11 | matchLabels: # The deployment applies to any pods mayching the specified labels 12 | app: social-login-app-server 13 | template: # Template for creating the pods in this deployment 14 | metadata: 15 | labels: # Labels that will be applied to each Pod in this deployment 16 | app: social-login-app-server 17 | spec: # Spec for the containers that will be run in the Pods 18 | containers: 19 | - name: social-login-app-server 20 | image: javachinna/social-login-app-server:1.0.0 21 | imagePullPolicy: Always 22 | ports: 23 | - name: http 24 | containerPort: 8080 # The port that the container exposes 25 | resources: 26 | limits: 27 | cpu: 0.2 28 | memory: "200Mi" 29 | env: # Environment variables supplied to the Pod 30 | - name: SPRING_DATASOURCE_USERNAME # Name of the environment variable 31 | valueFrom: # Get the value of environment variable from kubernetes secrets 32 | secretKeyRef: 33 | name: mysql-user-pass 34 | key: username 35 | - name: SPRING_DATASOURCE_PASSWORD 36 | valueFrom: 37 | secretKeyRef: 38 | name: mysql-user-pass 39 | key: password 40 | - name: SPRING_DATASOURCE_URL 41 | valueFrom: 42 | secretKeyRef: 43 | name: mysql-db-url 44 | key: url 45 | --- 46 | apiVersion: v1 # API version 47 | kind: Service # Type of the kubernetes resource 48 | metadata: 49 | name: social-login-app-server # Name of the kubernetes resource 50 | labels: # Labels that will be applied to this resource 51 | app: social-login-app-server 52 | spec: 53 | type: NodePort # The service will be exposed by opening a Port on each node and proxying it. 54 | selector: 55 | app: social-login-app-server # The service exposes Pods with label `app=social-login-app-server` 56 | ports: # Forward incoming connections on port 8080 to the target port 8080 57 | - name: http 58 | port: 8080 59 | targetPort: 8080 -------------------------------------------------------------------------------- /k8s/ingress-nginx-https.yml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1 2 | kind: Ingress 3 | metadata: 4 | name: social-login-app-ingress 5 | annotations: 6 | kubernetes.io/ingress.class: nginx 7 | cert-manager.io/cluster-issuer: letsencrypt-prod 8 | spec: 9 | tls: 10 | - hosts: 11 | - client.javachinna.xyz 12 | - server.javachinna.xyz 13 | secretName: social-login-app-tls 14 | rules: 15 | - host: "client.javachinna.xyz" 16 | http: 17 | paths: 18 | - pathType: Prefix 19 | path: / 20 | backend: 21 | service: 22 | name: social-login-app-client 23 | port: 24 | number: 80 25 | - host: "server.javachinna.xyz" 26 | http: 27 | paths: 28 | - pathType: Prefix 29 | path: /api/ 30 | backend: 31 | service: 32 | name: social-login-app-server 33 | port: 34 | number: 8080 35 | - pathType: Prefix 36 | path: /oauth2/ 37 | backend: 38 | service: 39 | name: social-login-app-server 40 | port: 41 | number: 8080 -------------------------------------------------------------------------------- /k8s/ingress-nginx.yml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1 2 | kind: Ingress 3 | metadata: 4 | name: social-login-app-ingress 5 | annotations: 6 | kubernetes.io/ingress.class: nginx 7 | spec: 8 | rules: 9 | - host: "client.javachinna.xyz" 10 | http: 11 | paths: 12 | - pathType: Prefix 13 | path: / 14 | backend: 15 | service: 16 | name: social-login-app-client 17 | port: 18 | number: 80 19 | - host: "server.javachinna.xyz" 20 | http: 21 | paths: 22 | - pathType: Prefix 23 | path: /api/ 24 | backend: 25 | service: 26 | name: social-login-app-server 27 | port: 28 | number: 8080 29 | - pathType: Prefix 30 | path: /oauth2/ 31 | backend: 32 | service: 33 | name: social-login-app-server 34 | port: 35 | number: 8080 -------------------------------------------------------------------------------- /k8s/mysql.yml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: PersistentVolume # Create a PersistentVolume 3 | metadata: 4 | name: mysql-pv 5 | labels: 6 | type: local 7 | spec: 8 | storageClassName: standard # Storage class. A PV Claim requesting the same storageClass can be bound to this volume. 9 | capacity: 10 | storage: 250Mi 11 | accessModes: 12 | - ReadWriteOnce 13 | hostPath: # hostPath PersistentVolume is used for development and testing. It uses a file/directory on the Node to emulate network-attached storage 14 | path: "/mnt/data" 15 | persistentVolumeReclaimPolicy: Retain # Retain the PersistentVolume even after PersistentVolumeClaim is deleted. The volume is considered “released”. But it is not yet available for another claim because the previous claimant’s data remains on the volume. 16 | --- 17 | apiVersion: v1 18 | kind: PersistentVolumeClaim # Create a PersistentVolumeClaim to request a PersistentVolume storage 19 | metadata: # Claim name and labels 20 | name: mysql-pv-claim 21 | labels: 22 | app: social-login-app 23 | spec: # Access mode and resource limits 24 | storageClassName: standard # Request a certain storage class 25 | accessModes: 26 | - ReadWriteOnce # ReadWriteOnce means the volume can be mounted as read-write by a single Node 27 | resources: 28 | requests: 29 | storage: 250Mi 30 | --- 31 | apiVersion: v1 # API version 32 | kind: Service # Type of kubernetes resource 33 | metadata: 34 | name: social-login-app-mysql # Name of the resource 35 | labels: # Labels that will be applied to the resource 36 | app: social-login-app 37 | spec: 38 | ports: 39 | - port: 3306 40 | selector: # Selects any Pod with labels `app=social-login-app,tier=mysql` 41 | app: social-login-app 42 | tier: mysql 43 | clusterIP: None 44 | --- 45 | apiVersion: apps/v1 46 | kind: Deployment # Type of the kubernetes resource 47 | metadata: 48 | name: social-login-app-mysql # Name of the deployment 49 | labels: # Labels applied to this deployment 50 | app: social-login-app 51 | spec: 52 | selector: 53 | matchLabels: # This deployment applies to the Pods matching the specified labels 54 | app: social-login-app 55 | tier: mysql 56 | strategy: 57 | type: Recreate 58 | template: # Template for the Pods in this deployment 59 | metadata: 60 | labels: # Labels to be applied to the Pods in this deployment 61 | app: social-login-app 62 | tier: mysql 63 | spec: # The spec for the containers that will be run inside the Pods in this deployment 64 | containers: 65 | - image: mysql:8.0 # The container image 66 | name: mysql 67 | env: # Environment variables passed to the container 68 | - name: MYSQL_ROOT_PASSWORD 69 | valueFrom: # Read environment variables from kubernetes secrets 70 | secretKeyRef: 71 | name: mysql-root-pass 72 | key: password 73 | - name: MYSQL_DATABASE 74 | valueFrom: 75 | secretKeyRef: 76 | name: mysql-db-url 77 | key: database 78 | - name: MYSQL_USER 79 | valueFrom: 80 | secretKeyRef: 81 | name: mysql-user-pass 82 | key: username 83 | - name: MYSQL_PASSWORD 84 | valueFrom: 85 | secretKeyRef: 86 | name: mysql-user-pass 87 | key: password 88 | ports: 89 | - containerPort: 3306 # The port that the container exposes 90 | name: mysql 91 | volumeMounts: 92 | - name: mysql-persistent-storage # This name should match the name specified in `volumes.name` 93 | mountPath: /var/lib/mysql 94 | volumes: # A PersistentVolume is mounted as a volume to the Pod 95 | - name: mysql-persistent-storage 96 | persistentVolumeClaim: 97 | claimName: mysql-pv-claim -------------------------------------------------------------------------------- /k8s/prod-issuer.yml: -------------------------------------------------------------------------------- 1 | apiVersion: cert-manager.io/v1 2 | kind: ClusterIssuer 3 | metadata: 4 | name: letsencrypt-prod 5 | spec: 6 | acme: 7 | # Email address used for ACME registration 8 | email: java4chinna@gmail.com 9 | server: https://acme-v02.api.letsencrypt.org/directory 10 | privateKeySecretRef: 11 | # Name of a secret used to store the ACME account private key 12 | name: letsencrypt-prod-private-key 13 | # Add a single challenge solver, HTTP01 using nginx 14 | solvers: 15 | - http01: 16 | ingress: 17 | class: nginx -------------------------------------------------------------------------------- /k8s/staging-issuer.yml: -------------------------------------------------------------------------------- 1 | apiVersion: cert-manager.io/v1 2 | kind: ClusterIssuer 3 | metadata: 4 | name: letsencrypt-staging 5 | spec: 6 | acme: 7 | # Email address used for ACME registration 8 | email: java4chinna@gmail.com 9 | server: https://acme-staging-v02.api.letsencrypt.org/directory 10 | privateKeySecretRef: 11 | # Name of a secret used to store the ACME account private key 12 | name: letsencrypt-staging-private-key 13 | # Add a single challenge solver, HTTP01 using nginx 14 | solvers: 15 | - http01: 16 | ingress: 17 | class: nginx -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.6"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-mysql-kubernetes/6dd2e6228326b06c0d058cfdbe6d77f5712c86ae/spring-boot-oauth2-social-login/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/Dockerfile: -------------------------------------------------------------------------------- 1 | #### Stage 1: Build the application 2 | FROM openjdk:11-jdk-slim as build 3 | 4 | # Set the current working directory inside the image 5 | WORKDIR /app 6 | 7 | # Copy maven executable to the image 8 | COPY mvnw . 9 | COPY .mvn .mvn 10 | 11 | # Copy the pom.xml file 12 | COPY pom.xml . 13 | 14 | # Build all the dependencies in preparation to go offline. 15 | # This is a separate step so the dependencies will be cached unless 16 | # the pom.xml file has changed. 17 | RUN ./mvnw dependency:go-offline -B 18 | 19 | # Copy the project source 20 | COPY src src 21 | 22 | # Package the application 23 | RUN ./mvnw package -DskipTests 24 | RUN mkdir -p target/dependency && (cd target/dependency; jar -xf ../*.jar) 25 | 26 | #### Stage 2: A minimal docker image with command to run the app 27 | FROM openjdk:11-jre-slim 28 | 29 | ARG DEPENDENCY=/app/target/dependency 30 | 31 | # Copy project dependencies from the build stage 32 | COPY --from=build ${DEPENDENCY}/BOOT-INF/lib /app/lib 33 | COPY --from=build ${DEPENDENCY}/META-INF /app/META-INF 34 | COPY --from=build ${DEPENDENCY}/BOOT-INF/classes /app 35 | 36 | ENTRYPOINT ["java","-cp","app:app/lib/*","com.javachinna.DemoApplication"] -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/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 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/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 Maven 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 keystroke 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 set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 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 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.4.0 9 | 10 | 11 | com.javachinna 12 | demo 13 | 1.1.0 14 | demo 15 | Demo project for Spring Boot 16 | 17 | 18 | 11 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-data-jpa 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-oauth2-client 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-web 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-validation 37 | 38 | 39 | io.jsonwebtoken 40 | jjwt 41 | 0.9.1 42 | 43 | 44 | 45 | mysql 46 | mysql-connector-java 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-test 51 | test 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-devtools 56 | 57 | 58 | org.projectlombok 59 | lombok 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-configuration-processor 64 | true 65 | 66 | 67 | dev.samstevens.totp 68 | totp-spring-boot-starter 69 | 1.7.1 70 | 71 | 72 | 73 | 74 | 75 | org.springframework.boot 76 | spring-boot-maven-plugin 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.javachinna; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.boot.builder.SpringApplicationBuilder; 5 | import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 6 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 7 | import org.springframework.transaction.annotation.EnableTransactionManagement; 8 | 9 | @SpringBootApplication(scanBasePackages = "com.javachinna") 10 | @EnableJpaRepositories 11 | @EnableTransactionManagement 12 | public class DemoApplication extends SpringBootServletInitializer { 13 | 14 | public static void main(String[] args) { 15 | SpringApplicationBuilder app = new SpringApplicationBuilder(DemoApplication.class); 16 | app.run(); 17 | } 18 | 19 | @Override 20 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 21 | return application.sources(DemoApplication.class); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/config/AppProperties.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.springframework.boot.context.properties.ConfigurationProperties; 7 | import org.springframework.stereotype.Component; 8 | 9 | @Component 10 | @ConfigurationProperties(prefix = "app") 11 | public class AppProperties { 12 | private final Auth auth = new Auth(); 13 | private final OAuth2 oauth2 = new OAuth2(); 14 | 15 | public static class Auth { 16 | private String tokenSecret; 17 | private long tokenExpirationMsec; 18 | 19 | public String getTokenSecret() { 20 | return tokenSecret; 21 | } 22 | 23 | public void setTokenSecret(String tokenSecret) { 24 | this.tokenSecret = tokenSecret; 25 | } 26 | 27 | public long getTokenExpirationMsec() { 28 | return tokenExpirationMsec; 29 | } 30 | 31 | public void setTokenExpirationMsec(long tokenExpirationMsec) { 32 | this.tokenExpirationMsec = tokenExpirationMsec; 33 | } 34 | } 35 | 36 | public static final class OAuth2 { 37 | private List authorizedRedirectUris = new ArrayList<>(); 38 | 39 | public List getAuthorizedRedirectUris() { 40 | return authorizedRedirectUris; 41 | } 42 | 43 | public OAuth2 authorizedRedirectUris(List authorizedRedirectUris) { 44 | this.authorizedRedirectUris = authorizedRedirectUris; 45 | return this; 46 | } 47 | } 48 | 49 | public Auth getAuth() { 50 | return auth; 51 | } 52 | 53 | public OAuth2 getOauth2() { 54 | return oauth2; 55 | } 56 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/config/CurrentUser.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 10 | 11 | @Target({ ElementType.PARAMETER, ElementType.TYPE }) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | @Documented 14 | @AuthenticationPrincipal 15 | public @interface CurrentUser { 16 | 17 | } 18 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/config/RestAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.ServletException; 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.security.core.AuthenticationException; 12 | import org.springframework.security.web.AuthenticationEntryPoint; 13 | 14 | public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { 15 | 16 | private static final Logger logger = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class); 17 | 18 | @Override 19 | public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { 20 | logger.error("Responding with unauthorized error. Message - {}", e.getMessage()); 21 | httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getLocalizedMessage()); 22 | } 23 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/config/SetupDataLoader.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.util.Calendar; 4 | import java.util.Date; 5 | import java.util.Set; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.context.ApplicationListener; 9 | import org.springframework.context.event.ContextRefreshedEvent; 10 | import org.springframework.security.crypto.password.PasswordEncoder; 11 | import org.springframework.stereotype.Component; 12 | import org.springframework.transaction.annotation.Transactional; 13 | 14 | import com.javachinna.dto.SocialProvider; 15 | import com.javachinna.model.Role; 16 | import com.javachinna.model.User; 17 | import com.javachinna.repo.RoleRepository; 18 | import com.javachinna.repo.UserRepository; 19 | 20 | @Component 21 | public class SetupDataLoader implements ApplicationListener { 22 | 23 | private boolean alreadySetup = false; 24 | 25 | @Autowired 26 | private UserRepository userRepository; 27 | 28 | @Autowired 29 | private RoleRepository roleRepository; 30 | 31 | @Autowired 32 | private PasswordEncoder passwordEncoder; 33 | 34 | @Override 35 | @Transactional 36 | public void onApplicationEvent(final ContextRefreshedEvent event) { 37 | if (alreadySetup) { 38 | return; 39 | } 40 | // Create initial roles 41 | Role userRole = createRoleIfNotFound(Role.ROLE_USER); 42 | Role adminRole = createRoleIfNotFound(Role.ROLE_ADMIN); 43 | Role modRole = createRoleIfNotFound(Role.ROLE_MODERATOR); 44 | createUserIfNotFound("admin@javachinna.com", Set.of(userRole, adminRole, modRole)); 45 | alreadySetup = true; 46 | } 47 | 48 | @Transactional 49 | private final User createUserIfNotFound(final String email, Set roles) { 50 | User user = userRepository.findByEmail(email); 51 | if (user == null) { 52 | user = new User(); 53 | user.setDisplayName("Admin"); 54 | user.setEmail(email); 55 | user.setPassword(passwordEncoder.encode("admin@")); 56 | user.setRoles(roles); 57 | user.setProvider(SocialProvider.LOCAL.getProviderType()); 58 | user.setEnabled(true); 59 | Date now = Calendar.getInstance().getTime(); 60 | user.setCreatedDate(now); 61 | user.setModifiedDate(now); 62 | user = userRepository.save(user); 63 | } 64 | return user; 65 | } 66 | 67 | @Transactional 68 | private final Role createRoleIfNotFound(final String name) { 69 | Role role = roleRepository.findByName(name); 70 | if (role == null) { 71 | role = roleRepository.save(new Role(name)); 72 | } 73 | return role; 74 | } 75 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.util.Locale; 4 | 5 | import org.springframework.context.MessageSource; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.support.ReloadableResourceBundleMessageSource; 9 | import org.springframework.validation.Validator; 10 | import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; 11 | import org.springframework.web.servlet.LocaleResolver; 12 | import org.springframework.web.servlet.config.annotation.CorsRegistry; 13 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 14 | import org.springframework.web.servlet.i18n.CookieLocaleResolver; 15 | 16 | @Configuration 17 | public class WebConfig implements WebMvcConfigurer { 18 | 19 | private final long MAX_AGE_SECS = 3600; 20 | 21 | @Override 22 | public void addCorsMappings(CorsRegistry registry) { 23 | registry.addMapping("/**").allowedOrigins("*").allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE").maxAge(MAX_AGE_SECS); 24 | } 25 | 26 | @Bean 27 | public MessageSource messageSource() { 28 | ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 29 | messageSource.setBasename("classpath:messages"); 30 | messageSource.setDefaultEncoding("UTF-8"); 31 | return messageSource; 32 | } 33 | 34 | @Bean 35 | public LocaleResolver localeResolver() { 36 | final CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); 37 | cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH); 38 | return cookieLocaleResolver; 39 | } 40 | 41 | @Override 42 | public Validator getValidator() { 43 | LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); 44 | validator.setValidationMessageSource(messageSource()); 45 | return validator; 46 | } 47 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.util.Arrays; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.http.converter.FormHttpMessageConverter; 9 | import org.springframework.security.authentication.AuthenticationManager; 10 | import org.springframework.security.config.BeanIds; 11 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 12 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 13 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 14 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 15 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 16 | import org.springframework.security.config.http.SessionCreationPolicy; 17 | import org.springframework.security.core.userdetails.UserDetailsService; 18 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 19 | import org.springframework.security.crypto.password.PasswordEncoder; 20 | import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient; 21 | import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; 22 | import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest; 23 | import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler; 24 | import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter; 25 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 26 | import org.springframework.web.client.RestTemplate; 27 | 28 | import com.javachinna.security.jwt.TokenAuthenticationFilter; 29 | import com.javachinna.security.oauth2.CustomOAuth2UserService; 30 | import com.javachinna.security.oauth2.CustomOidcUserService; 31 | import com.javachinna.security.oauth2.HttpCookieOAuth2AuthorizationRequestRepository; 32 | import com.javachinna.security.oauth2.OAuth2AccessTokenResponseConverterWithDefaults; 33 | import com.javachinna.security.oauth2.OAuth2AuthenticationFailureHandler; 34 | import com.javachinna.security.oauth2.OAuth2AuthenticationSuccessHandler; 35 | 36 | @Configuration 37 | @EnableWebSecurity 38 | @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) 39 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 40 | 41 | @Autowired 42 | private UserDetailsService userDetailsService; 43 | 44 | @Autowired 45 | private CustomOAuth2UserService customOAuth2UserService; 46 | 47 | @Autowired 48 | CustomOidcUserService customOidcUserService; 49 | 50 | @Autowired 51 | private OAuth2AuthenticationSuccessHandler oAuth2AuthenticationSuccessHandler; 52 | 53 | @Autowired 54 | private OAuth2AuthenticationFailureHandler oAuth2AuthenticationFailureHandler; 55 | 56 | @Autowired 57 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 58 | auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); 59 | } 60 | 61 | @Override 62 | protected void configure(HttpSecurity http) throws Exception { 63 | 64 | http.cors().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable().formLogin().disable().httpBasic().disable() 65 | .exceptionHandling().authenticationEntryPoint(new RestAuthenticationEntryPoint()).and().authorizeRequests() 66 | .antMatchers("/", "/error", "/api/all", "/api/auth/**", "/oauth2/**").permitAll().anyRequest().authenticated().and().oauth2Login().authorizationEndpoint() 67 | .authorizationRequestRepository(cookieAuthorizationRequestRepository()).and().redirectionEndpoint().and().userInfoEndpoint().oidcUserService(customOidcUserService) 68 | .userService(customOAuth2UserService).and().tokenEndpoint().accessTokenResponseClient(authorizationCodeTokenResponseClient()).and() 69 | .successHandler(oAuth2AuthenticationSuccessHandler).failureHandler(oAuth2AuthenticationFailureHandler); 70 | 71 | // Add our custom Token based authentication filter 72 | http.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); 73 | } 74 | 75 | @Bean 76 | public TokenAuthenticationFilter tokenAuthenticationFilter() { 77 | return new TokenAuthenticationFilter(); 78 | } 79 | 80 | /* 81 | * By default, Spring OAuth2 uses 82 | * HttpSessionOAuth2AuthorizationRequestRepository to save the authorization 83 | * request. But, since our service is stateless, we can't save it in the 84 | * session. We'll save the request in a Base64 encoded cookie instead. 85 | */ 86 | @Bean 87 | public HttpCookieOAuth2AuthorizationRequestRepository cookieAuthorizationRequestRepository() { 88 | return new HttpCookieOAuth2AuthorizationRequestRepository(); 89 | } 90 | 91 | // This bean is load the user specific data when form login is used. 92 | @Override 93 | public UserDetailsService userDetailsService() { 94 | return userDetailsService; 95 | } 96 | 97 | @Bean 98 | public PasswordEncoder passwordEncoder() { 99 | return new BCryptPasswordEncoder(10); 100 | } 101 | 102 | @Bean(BeanIds.AUTHENTICATION_MANAGER) 103 | @Override 104 | public AuthenticationManager authenticationManagerBean() throws Exception { 105 | return super.authenticationManagerBean(); 106 | } 107 | 108 | private OAuth2AccessTokenResponseClient authorizationCodeTokenResponseClient() { 109 | OAuth2AccessTokenResponseHttpMessageConverter tokenResponseHttpMessageConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); 110 | tokenResponseHttpMessageConverter.setTokenResponseConverter(new OAuth2AccessTokenResponseConverterWithDefaults()); 111 | RestTemplate restTemplate = new RestTemplate(Arrays.asList(new FormHttpMessageConverter(), tokenResponseHttpMessageConverter)); 112 | restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); 113 | DefaultAuthorizationCodeTokenResponseClient tokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient(); 114 | tokenResponseClient.setRestOperations(restTemplate); 115 | return tokenResponseClient; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/controller/AuthController.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.controller; 2 | 3 | import static dev.samstevens.totp.util.Utils.getDataUriForImage; 4 | 5 | import javax.validation.Valid; 6 | import javax.validation.constraints.NotEmpty; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.security.access.prepost.PreAuthorize; 12 | import org.springframework.security.authentication.AuthenticationManager; 13 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 14 | import org.springframework.security.core.Authentication; 15 | import org.springframework.security.core.context.SecurityContextHolder; 16 | import org.springframework.web.bind.annotation.PostMapping; 17 | import org.springframework.web.bind.annotation.RequestBody; 18 | import org.springframework.web.bind.annotation.RequestMapping; 19 | import org.springframework.web.bind.annotation.RestController; 20 | 21 | import com.javachinna.config.CurrentUser; 22 | import com.javachinna.dto.ApiResponse; 23 | import com.javachinna.dto.JwtAuthenticationResponse; 24 | import com.javachinna.dto.LocalUser; 25 | import com.javachinna.dto.LoginRequest; 26 | import com.javachinna.dto.SignUpRequest; 27 | import com.javachinna.dto.SignUpResponse; 28 | import com.javachinna.exception.UserAlreadyExistAuthenticationException; 29 | import com.javachinna.model.User; 30 | import com.javachinna.security.jwt.TokenProvider; 31 | import com.javachinna.service.UserService; 32 | import com.javachinna.util.GeneralUtils; 33 | 34 | import dev.samstevens.totp.code.CodeVerifier; 35 | import dev.samstevens.totp.exceptions.QrGenerationException; 36 | import dev.samstevens.totp.qr.QrData; 37 | import dev.samstevens.totp.qr.QrDataFactory; 38 | import dev.samstevens.totp.qr.QrGenerator; 39 | import lombok.extern.slf4j.Slf4j; 40 | 41 | @Slf4j 42 | @RestController 43 | @RequestMapping("/api/auth") 44 | public class AuthController { 45 | 46 | @Autowired 47 | AuthenticationManager authenticationManager; 48 | 49 | @Autowired 50 | UserService userService; 51 | 52 | @Autowired 53 | TokenProvider tokenProvider; 54 | 55 | @Autowired 56 | private QrDataFactory qrDataFactory; 57 | 58 | @Autowired 59 | private QrGenerator qrGenerator; 60 | 61 | @Autowired 62 | private CodeVerifier verifier; 63 | 64 | @PostMapping("/signin") 65 | public ResponseEntity authenticateUser(@Valid @RequestBody LoginRequest loginRequest) { 66 | Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword())); 67 | SecurityContextHolder.getContext().setAuthentication(authentication); 68 | LocalUser localUser = (LocalUser) authentication.getPrincipal(); 69 | boolean authenticated = !localUser.getUser().isUsing2FA(); 70 | String jwt = tokenProvider.createToken(localUser, authenticated); 71 | return ResponseEntity.ok(new JwtAuthenticationResponse(jwt, authenticated, authenticated ? GeneralUtils.buildUserInfo(localUser) : null)); 72 | } 73 | 74 | @PostMapping("/signup") 75 | public ResponseEntity registerUser(@Valid @RequestBody SignUpRequest signUpRequest) { 76 | try { 77 | User user = userService.registerNewUser(signUpRequest); 78 | if (signUpRequest.isUsing2FA()) { 79 | QrData data = qrDataFactory.newBuilder().label(user.getEmail()).secret(user.getSecret()).issuer("JavaChinna").build(); 80 | // Generate the QR code image data as a base64 string which can 81 | // be used in an tag: 82 | String qrCodeImage = getDataUriForImage(qrGenerator.generate(data), qrGenerator.getImageMimeType()); 83 | return ResponseEntity.ok().body(new SignUpResponse(true, qrCodeImage)); 84 | } 85 | } catch (UserAlreadyExistAuthenticationException e) { 86 | log.error("Exception Ocurred", e); 87 | return new ResponseEntity<>(new ApiResponse(false, "Email Address already in use!"), HttpStatus.BAD_REQUEST); 88 | } catch (QrGenerationException e) { 89 | log.error("QR Generation Exception Ocurred", e); 90 | return new ResponseEntity<>(new ApiResponse(false, "Unable to generate QR code!"), HttpStatus.BAD_REQUEST); 91 | } 92 | return ResponseEntity.ok().body(new ApiResponse(true, "User registered successfully")); 93 | } 94 | 95 | @PostMapping("/verify") 96 | @PreAuthorize("hasRole('PRE_VERIFICATION_USER')") 97 | public ResponseEntity verifyCode(@NotEmpty @RequestBody String code, @CurrentUser LocalUser user) { 98 | if (!verifier.isValidCode(user.getUser().getSecret(), code)) { 99 | return new ResponseEntity<>(new ApiResponse(false, "Invalid Code!"), HttpStatus.BAD_REQUEST); 100 | } 101 | String jwt = tokenProvider.createToken(user, true); 102 | return ResponseEntity.ok(new JwtAuthenticationResponse(jwt, true, GeneralUtils.buildUserInfo(user))); 103 | } 104 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.controller; 2 | 3 | import org.springframework.http.ResponseEntity; 4 | import org.springframework.security.access.prepost.PreAuthorize; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import com.javachinna.config.CurrentUser; 10 | import com.javachinna.dto.LocalUser; 11 | import com.javachinna.util.GeneralUtils; 12 | 13 | @RestController 14 | @RequestMapping("/api") 15 | public class UserController { 16 | 17 | @GetMapping("/user/me") 18 | @PreAuthorize("hasRole('USER')") 19 | public ResponseEntity getCurrentUser(@CurrentUser LocalUser user) { 20 | return ResponseEntity.ok(GeneralUtils.buildUserInfo(user)); 21 | } 22 | 23 | @GetMapping("/all") 24 | public ResponseEntity getContent() { 25 | return ResponseEntity.ok("Public content goes here"); 26 | } 27 | 28 | @GetMapping("/user") 29 | @PreAuthorize("hasRole('USER')") 30 | public ResponseEntity getUserContent() { 31 | return ResponseEntity.ok("User content goes here"); 32 | } 33 | 34 | @GetMapping("/admin") 35 | @PreAuthorize("hasRole('ADMIN')") 36 | public ResponseEntity getAdminContent() { 37 | return ResponseEntity.ok("Admin content goes here"); 38 | } 39 | 40 | @GetMapping("/mod") 41 | @PreAuthorize("hasRole('MODERATOR')") 42 | public ResponseEntity getModeratorContent() { 43 | return ResponseEntity.ok("Moderator content goes here"); 44 | } 45 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/ApiResponse.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import lombok.Value; 4 | 5 | @Value 6 | public class ApiResponse { 7 | private Boolean success; 8 | private String message; 9 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/JwtAuthenticationResponse.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import lombok.Value; 4 | 5 | @Value 6 | public class JwtAuthenticationResponse { 7 | private String accessToken; 8 | private boolean authenticated; 9 | private UserInfo user; 10 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/LocalUser.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import java.util.Collection; 4 | import java.util.Map; 5 | 6 | import org.springframework.security.core.GrantedAuthority; 7 | import org.springframework.security.core.userdetails.User; 8 | import org.springframework.security.oauth2.core.oidc.OidcIdToken; 9 | import org.springframework.security.oauth2.core.oidc.OidcUserInfo; 10 | import org.springframework.security.oauth2.core.oidc.user.OidcUser; 11 | import org.springframework.security.oauth2.core.user.OAuth2User; 12 | 13 | import com.javachinna.util.GeneralUtils; 14 | 15 | /** 16 | * 17 | * @author Chinna 18 | * 19 | */ 20 | public class LocalUser extends User implements OAuth2User, OidcUser { 21 | 22 | /** 23 | * 24 | */ 25 | private static final long serialVersionUID = -2845160792248762779L; 26 | private final OidcIdToken idToken; 27 | private final OidcUserInfo userInfo; 28 | private Map attributes; 29 | private com.javachinna.model.User user; 30 | 31 | public LocalUser(final String userID, final String password, final boolean enabled, final boolean accountNonExpired, final boolean credentialsNonExpired, 32 | final boolean accountNonLocked, final Collection authorities, final com.javachinna.model.User user) { 33 | this(userID, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities, user, null, null); 34 | } 35 | 36 | public LocalUser(final String userID, final String password, final boolean enabled, final boolean accountNonExpired, final boolean credentialsNonExpired, 37 | final boolean accountNonLocked, final Collection authorities, final com.javachinna.model.User user, OidcIdToken idToken, 38 | OidcUserInfo userInfo) { 39 | super(userID, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); 40 | this.user = user; 41 | this.idToken = idToken; 42 | this.userInfo = userInfo; 43 | } 44 | 45 | public static LocalUser create(com.javachinna.model.User user, Map attributes, OidcIdToken idToken, OidcUserInfo userInfo) { 46 | LocalUser localUser = new LocalUser(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, GeneralUtils.buildSimpleGrantedAuthorities(user.getRoles()), 47 | user, idToken, userInfo); 48 | localUser.setAttributes(attributes); 49 | return localUser; 50 | } 51 | 52 | public void setAttributes(Map attributes) { 53 | this.attributes = attributes; 54 | } 55 | 56 | @Override 57 | public String getName() { 58 | return this.user.getDisplayName(); 59 | } 60 | 61 | @Override 62 | public Map getAttributes() { 63 | return this.attributes; 64 | } 65 | 66 | @Override 67 | public Map getClaims() { 68 | return this.attributes; 69 | } 70 | 71 | @Override 72 | public OidcUserInfo getUserInfo() { 73 | return this.userInfo; 74 | } 75 | 76 | @Override 77 | public OidcIdToken getIdToken() { 78 | return this.idToken; 79 | } 80 | 81 | public com.javachinna.model.User getUser() { 82 | return user; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/LoginRequest.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import javax.validation.constraints.NotBlank; 4 | 5 | import lombok.Data; 6 | 7 | @Data 8 | public class LoginRequest { 9 | @NotBlank 10 | private String email; 11 | 12 | @NotBlank 13 | private String password; 14 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/SignUpRequest.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import javax.validation.constraints.NotEmpty; 4 | import javax.validation.constraints.Size; 5 | 6 | import com.javachinna.validator.PasswordMatches; 7 | 8 | import lombok.Data; 9 | 10 | /** 11 | * @author Chinna 12 | * @since 26/3/18 13 | */ 14 | @Data 15 | @PasswordMatches 16 | public class SignUpRequest { 17 | 18 | private Long userID; 19 | 20 | private String providerUserId; 21 | 22 | @NotEmpty 23 | private String displayName; 24 | 25 | @NotEmpty 26 | private String email; 27 | 28 | private SocialProvider socialProvider; 29 | 30 | @Size(min = 6, message = "{Size.userDto.password}") 31 | private String password; 32 | 33 | @NotEmpty 34 | private String matchingPassword; 35 | 36 | private boolean using2FA; 37 | 38 | public SignUpRequest(String providerUserId, String displayName, String email, String password, SocialProvider socialProvider) { 39 | this.providerUserId = providerUserId; 40 | this.displayName = displayName; 41 | this.email = email; 42 | this.password = password; 43 | this.socialProvider = socialProvider; 44 | } 45 | 46 | public static Builder getBuilder() { 47 | return new Builder(); 48 | } 49 | 50 | public static class Builder { 51 | private String providerUserID; 52 | private String displayName; 53 | private String email; 54 | private String password; 55 | private SocialProvider socialProvider; 56 | 57 | public Builder addProviderUserID(final String userID) { 58 | this.providerUserID = userID; 59 | return this; 60 | } 61 | 62 | public Builder addDisplayName(final String displayName) { 63 | this.displayName = displayName; 64 | return this; 65 | } 66 | 67 | public Builder addEmail(final String email) { 68 | this.email = email; 69 | return this; 70 | } 71 | 72 | public Builder addPassword(final String password) { 73 | this.password = password; 74 | return this; 75 | } 76 | 77 | public Builder addSocialProvider(final SocialProvider socialProvider) { 78 | this.socialProvider = socialProvider; 79 | return this; 80 | } 81 | 82 | public SignUpRequest build() { 83 | return new SignUpRequest(providerUserID, displayName, email, password, socialProvider); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/SignUpResponse.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import lombok.Value; 4 | 5 | @Value 6 | public class SignUpResponse { 7 | private boolean using2FA; 8 | private String qrCodeImage; 9 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/SocialProvider.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | /** 4 | * @author Chinna 5 | * @since 26/3/18 6 | */ 7 | public enum SocialProvider { 8 | 9 | FACEBOOK("facebook"), TWITTER("twitter"), LINKEDIN("linkedin"), GOOGLE("google"), GITHUB("github"), LOCAL("local"); 10 | 11 | private String providerType; 12 | 13 | public String getProviderType() { 14 | return providerType; 15 | } 16 | 17 | SocialProvider(final String providerType) { 18 | this.providerType = providerType; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import java.util.List; 4 | 5 | import lombok.Value; 6 | 7 | @Value 8 | public class UserInfo { 9 | private String id, displayName, email; 10 | private List roles; 11 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/exception/BadRequestException.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | @ResponseStatus(HttpStatus.BAD_REQUEST) 7 | public class BadRequestException extends RuntimeException { 8 | /** 9 | * 10 | */ 11 | private static final long serialVersionUID = 752858877580882829L; 12 | 13 | public BadRequestException(String message) { 14 | super(message); 15 | } 16 | 17 | public BadRequestException(String message, Throwable cause) { 18 | super(message, cause); 19 | } 20 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/exception/OAuth2AuthenticationProcessingException.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.exception; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | 5 | public class OAuth2AuthenticationProcessingException extends AuthenticationException { 6 | /** 7 | * 8 | */ 9 | private static final long serialVersionUID = 3392450042101522832L; 10 | 11 | public OAuth2AuthenticationProcessingException(String msg, Throwable t) { 12 | super(msg, t); 13 | } 14 | 15 | public OAuth2AuthenticationProcessingException(String msg) { 16 | super(msg); 17 | } 18 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/exception/ResourceNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | import lombok.Getter; 7 | 8 | @Getter 9 | @ResponseStatus(HttpStatus.NOT_FOUND) 10 | public class ResourceNotFoundException extends RuntimeException { 11 | private static final long serialVersionUID = 7004203416628447047L; 12 | private String resourceName; 13 | private String fieldName; 14 | private Object fieldValue; 15 | 16 | public ResourceNotFoundException(String resourceName, String fieldName, Object fieldValue) { 17 | super(String.format("%s not found with %s : '%s'", resourceName, fieldName, fieldValue)); 18 | this.resourceName = resourceName; 19 | this.fieldName = fieldName; 20 | this.fieldValue = fieldValue; 21 | } 22 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/exception/UserAlreadyExistAuthenticationException.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.exception; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | 5 | /** 6 | * 7 | * @author Chinna 8 | * 9 | */ 10 | public class UserAlreadyExistAuthenticationException extends AuthenticationException { 11 | 12 | /** 13 | * 14 | */ 15 | private static final long serialVersionUID = 5570981880007077317L; 16 | 17 | public UserAlreadyExistAuthenticationException(final String msg) { 18 | super(msg); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/exception/handler/RestResponseEntityExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.exception.handler; 2 | 3 | import java.util.stream.Collectors; 4 | 5 | import org.springframework.http.HttpHeaders; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.validation.BindingResult; 9 | import org.springframework.validation.FieldError; 10 | import org.springframework.web.bind.MethodArgumentNotValidException; 11 | import org.springframework.web.bind.annotation.ControllerAdvice; 12 | import org.springframework.web.context.request.WebRequest; 13 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 14 | 15 | import com.javachinna.dto.ApiResponse; 16 | 17 | @ControllerAdvice 18 | public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { 19 | 20 | public RestResponseEntityExceptionHandler() { 21 | super(); 22 | } 23 | 24 | @Override 25 | protected ResponseEntity handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status, 26 | final WebRequest request) { 27 | logger.error("400 Status Code", ex); 28 | final BindingResult result = ex.getBindingResult(); 29 | 30 | String error = result.getAllErrors().stream().map(e -> { 31 | if (e instanceof FieldError) { 32 | return ((FieldError) e).getField() + " : " + e.getDefaultMessage(); 33 | } else { 34 | return e.getObjectName() + " : " + e.getDefaultMessage(); 35 | } 36 | }).collect(Collectors.joining(", ")); 37 | return handleExceptionInternal(ex, new ApiResponse(false, error), new HttpHeaders(), HttpStatus.BAD_REQUEST, request); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.model; 2 | 3 | import java.io.Serializable; 4 | import java.util.Set; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.GenerationType; 10 | import javax.persistence.Id; 11 | import javax.persistence.ManyToMany; 12 | 13 | import lombok.Getter; 14 | import lombok.NoArgsConstructor; 15 | import lombok.Setter; 16 | 17 | /** 18 | * The persistent class for the role database table. 19 | * 20 | */ 21 | @Entity 22 | @Getter 23 | @Setter 24 | @NoArgsConstructor 25 | public class Role implements Serializable { 26 | private static final long serialVersionUID = 1L; 27 | public static final String USER = "USER"; 28 | public static final String ROLE_USER = "ROLE_USER"; 29 | public static final String ROLE_ADMIN = "ROLE_ADMIN"; 30 | public static final String ROLE_MODERATOR = "ROLE_MODERATOR"; 31 | public static final String ROLE_PRE_VERIFICATION_USER = "ROLE_PRE_VERIFICATION_USER"; 32 | 33 | @Id 34 | @GeneratedValue(strategy = GenerationType.IDENTITY) 35 | @Column(name = "ROLE_ID") 36 | private Long roleId; 37 | 38 | private String name; 39 | 40 | // bi-directional many-to-many association to User 41 | @ManyToMany(mappedBy = "roles") 42 | private Set users; 43 | 44 | public Role(String name) { 45 | this.name = name; 46 | } 47 | 48 | @Override 49 | public int hashCode() { 50 | final int prime = 31; 51 | int result = 1; 52 | result = prime * result + ((name == null) ? 0 : name.hashCode()); 53 | return result; 54 | } 55 | 56 | @Override 57 | public boolean equals(final Object obj) { 58 | if (this == obj) { 59 | return true; 60 | } 61 | if (obj == null) { 62 | return false; 63 | } 64 | if (getClass() != obj.getClass()) { 65 | return false; 66 | } 67 | final Role role = (Role) obj; 68 | if (!role.equals(role.name)) { 69 | return false; 70 | } 71 | return true; 72 | } 73 | 74 | @Override 75 | public String toString() { 76 | final StringBuilder builder = new StringBuilder(); 77 | builder.append("Role [name=").append(name).append("]").append("[id=").append(roleId).append("]"); 78 | return builder.toString(); 79 | } 80 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/model/User.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.model; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | import java.util.Set; 6 | 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.GeneratedValue; 10 | import javax.persistence.GenerationType; 11 | import javax.persistence.Id; 12 | import javax.persistence.JoinColumn; 13 | import javax.persistence.JoinTable; 14 | import javax.persistence.ManyToMany; 15 | import javax.persistence.Temporal; 16 | import javax.persistence.TemporalType; 17 | 18 | import com.fasterxml.jackson.annotation.JsonIgnore; 19 | 20 | import lombok.Getter; 21 | import lombok.NoArgsConstructor; 22 | import lombok.Setter; 23 | 24 | /** 25 | * The persistent class for the user database table. 26 | * 27 | */ 28 | @Entity 29 | @NoArgsConstructor 30 | @Getter 31 | @Setter 32 | public class User implements Serializable { 33 | 34 | /** 35 | * 36 | */ 37 | private static final long serialVersionUID = 65981149772133526L; 38 | 39 | @Id 40 | @GeneratedValue(strategy = GenerationType.IDENTITY) 41 | @Column(name = "USER_ID") 42 | private Long id; 43 | 44 | @Column(name = "PROVIDER_USER_ID") 45 | private String providerUserId; 46 | 47 | private String email; 48 | 49 | @Column(name = "enabled", columnDefinition = "BIT", length = 1) 50 | private boolean enabled; 51 | 52 | @Column(name = "DISPLAY_NAME") 53 | private String displayName; 54 | 55 | @Column(name = "created_date", nullable = false, updatable = false) 56 | @Temporal(TemporalType.TIMESTAMP) 57 | protected Date createdDate; 58 | 59 | @Temporal(TemporalType.TIMESTAMP) 60 | protected Date modifiedDate; 61 | 62 | private String password; 63 | 64 | private String provider; 65 | 66 | @Column(name = "USING_2FA") 67 | private boolean using2FA; 68 | 69 | private String secret; 70 | 71 | // bi-directional many-to-many association to Role 72 | @JsonIgnore 73 | @ManyToMany 74 | @JoinTable(name = "user_role", joinColumns = {@JoinColumn(name = "USER_ID")}, inverseJoinColumns = {@JoinColumn(name = "ROLE_ID")}) 75 | private Set roles; 76 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/repo/RoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.repo; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.javachinna.model.Role; 7 | 8 | @Repository 9 | public interface RoleRepository extends JpaRepository { 10 | 11 | Role findByName(String name); 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/repo/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.repo; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.javachinna.model.User; 7 | 8 | @Repository 9 | public interface UserRepository extends JpaRepository { 10 | 11 | User findByEmail(String email); 12 | 13 | boolean existsByEmail(String email); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/jwt/TokenAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.jwt; 2 | 3 | import java.io.IOException; 4 | import java.util.Collection; 5 | import java.util.List; 6 | 7 | import javax.servlet.FilterChain; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 16 | import org.springframework.security.core.GrantedAuthority; 17 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 18 | import org.springframework.security.core.context.SecurityContextHolder; 19 | import org.springframework.security.core.userdetails.UserDetails; 20 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 21 | import org.springframework.util.StringUtils; 22 | import org.springframework.web.filter.OncePerRequestFilter; 23 | 24 | import com.javachinna.model.Role; 25 | import com.javachinna.service.LocalUserDetailService; 26 | 27 | public class TokenAuthenticationFilter extends OncePerRequestFilter { 28 | 29 | @Autowired 30 | private TokenProvider tokenProvider; 31 | 32 | @Autowired 33 | private LocalUserDetailService customUserDetailsService; 34 | 35 | private static final Logger logger = LoggerFactory.getLogger(TokenAuthenticationFilter.class); 36 | 37 | @Override 38 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { 39 | try { 40 | String jwt = getJwtFromRequest(request); 41 | 42 | if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) { 43 | Long userId = tokenProvider.getUserIdFromToken(jwt); 44 | 45 | UserDetails userDetails = customUserDetailsService.loadUserById(userId); 46 | Collection authorities = tokenProvider.isAuthenticated(jwt) 47 | ? userDetails.getAuthorities() 48 | : List.of(new SimpleGrantedAuthority(Role.ROLE_PRE_VERIFICATION_USER)); 49 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, authorities); 50 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); 51 | 52 | SecurityContextHolder.getContext().setAuthentication(authentication); 53 | } 54 | } catch (Exception ex) { 55 | logger.error("Could not set user authentication in security context", ex); 56 | } 57 | 58 | filterChain.doFilter(request, response); 59 | } 60 | 61 | private String getJwtFromRequest(HttpServletRequest request) { 62 | String bearerToken = request.getHeader("Authorization"); 63 | if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { 64 | return bearerToken.substring(7, bearerToken.length()); 65 | } 66 | return null; 67 | } 68 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/jwt/TokenProvider.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.jwt; 2 | 3 | import java.util.Date; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.stereotype.Service; 8 | 9 | import com.javachinna.config.AppProperties; 10 | import com.javachinna.dto.LocalUser; 11 | 12 | import io.jsonwebtoken.Claims; 13 | import io.jsonwebtoken.ExpiredJwtException; 14 | import io.jsonwebtoken.Jwts; 15 | import io.jsonwebtoken.MalformedJwtException; 16 | import io.jsonwebtoken.SignatureAlgorithm; 17 | import io.jsonwebtoken.SignatureException; 18 | import io.jsonwebtoken.UnsupportedJwtException; 19 | 20 | @Service 21 | public class TokenProvider { 22 | 23 | private static final String AUTHENTICATED = "authenticated"; 24 | 25 | private static final Logger logger = LoggerFactory.getLogger(TokenProvider.class); 26 | 27 | public static final long TEMP_TOKEN_VALIDITY_IN_MILLIS = 300000; 28 | 29 | private AppProperties appProperties; 30 | 31 | public TokenProvider(AppProperties appProperties) { 32 | this.appProperties = appProperties; 33 | } 34 | 35 | public String createToken(LocalUser userPrincipal, boolean authenticated) { 36 | Date now = new Date(); 37 | Date expiryDate = new Date(now.getTime() + (authenticated ? appProperties.getAuth().getTokenExpirationMsec() : TEMP_TOKEN_VALIDITY_IN_MILLIS)); 38 | 39 | return Jwts.builder().setSubject(Long.toString(userPrincipal.getUser().getId())).claim(AUTHENTICATED, authenticated).setIssuedAt(new Date()).setExpiration(expiryDate) 40 | .signWith(SignatureAlgorithm.HS512, appProperties.getAuth().getTokenSecret()).compact(); 41 | } 42 | 43 | public Long getUserIdFromToken(String token) { 44 | Claims claims = Jwts.parser().setSigningKey(appProperties.getAuth().getTokenSecret()).parseClaimsJws(token).getBody(); 45 | 46 | return Long.parseLong(claims.getSubject()); 47 | } 48 | 49 | public Boolean isAuthenticated(String token) { 50 | Claims claims = Jwts.parser().setSigningKey(appProperties.getAuth().getTokenSecret()).parseClaimsJws(token).getBody(); 51 | return claims.get(AUTHENTICATED, Boolean.class); 52 | } 53 | 54 | public boolean validateToken(String authToken) { 55 | try { 56 | Jwts.parser().setSigningKey(appProperties.getAuth().getTokenSecret()).parseClaimsJws(authToken); 57 | return true; 58 | } catch (SignatureException ex) { 59 | logger.error("Invalid JWT signature"); 60 | } catch (MalformedJwtException ex) { 61 | logger.error("Invalid JWT token"); 62 | } catch (ExpiredJwtException ex) { 63 | logger.error("Expired JWT token"); 64 | } catch (UnsupportedJwtException ex) { 65 | logger.error("Unsupported JWT token"); 66 | } catch (IllegalArgumentException ex) { 67 | logger.error("JWT claims string is empty."); 68 | } 69 | return false; 70 | } 71 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/CustomOAuth2UserService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.core.env.Environment; 9 | import org.springframework.http.HttpEntity; 10 | import org.springframework.http.HttpHeaders; 11 | import org.springframework.http.HttpMethod; 12 | import org.springframework.http.ResponseEntity; 13 | import org.springframework.security.core.AuthenticationException; 14 | import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; 15 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; 16 | import org.springframework.security.oauth2.core.OAuth2AuthenticationException; 17 | import org.springframework.security.oauth2.core.user.OAuth2User; 18 | import org.springframework.stereotype.Service; 19 | import org.springframework.util.Assert; 20 | import org.springframework.web.client.RestTemplate; 21 | 22 | import com.javachinna.dto.SocialProvider; 23 | import com.javachinna.exception.OAuth2AuthenticationProcessingException; 24 | import com.javachinna.service.UserService; 25 | 26 | @Service 27 | public class CustomOAuth2UserService extends DefaultOAuth2UserService { 28 | 29 | @Autowired 30 | private UserService userService; 31 | 32 | @Autowired 33 | private Environment env; 34 | 35 | @Override 36 | public OAuth2User loadUser(OAuth2UserRequest oAuth2UserRequest) throws OAuth2AuthenticationException { 37 | OAuth2User oAuth2User = super.loadUser(oAuth2UserRequest); 38 | try { 39 | Map attributes = new HashMap<>(oAuth2User.getAttributes()); 40 | String provider = oAuth2UserRequest.getClientRegistration().getRegistrationId(); 41 | if (provider.equals(SocialProvider.LINKEDIN.getProviderType())) { 42 | populateEmailAddressFromLinkedIn(oAuth2UserRequest, attributes); 43 | } 44 | return userService.processUserRegistration(provider, attributes, null, null); 45 | } catch (AuthenticationException ex) { 46 | throw ex; 47 | } catch (Exception ex) { 48 | ex.printStackTrace(); 49 | // Throwing an instance of AuthenticationException will trigger the 50 | // OAuth2AuthenticationFailureHandler 51 | throw new OAuth2AuthenticationProcessingException(ex.getMessage(), ex.getCause()); 52 | } 53 | } 54 | 55 | @SuppressWarnings({ "rawtypes", "unchecked" }) 56 | public void populateEmailAddressFromLinkedIn(OAuth2UserRequest oAuth2UserRequest, Map attributes) throws OAuth2AuthenticationException { 57 | String emailEndpointUri = env.getProperty("linkedin.email-address-uri"); 58 | Assert.notNull(emailEndpointUri, "LinkedIn email address end point required"); 59 | RestTemplate restTemplate = new RestTemplate(); 60 | HttpHeaders headers = new HttpHeaders(); 61 | headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + oAuth2UserRequest.getAccessToken().getTokenValue()); 62 | HttpEntity entity = new HttpEntity<>("", headers); 63 | ResponseEntity response = restTemplate.exchange(emailEndpointUri, HttpMethod.GET, entity, Map.class); 64 | List list = (List) response.getBody().get("elements"); 65 | Map map = (Map) ((Map) list.get(0)).get("handle~"); 66 | attributes.putAll(map); 67 | } 68 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/CustomOidcUserService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.core.AuthenticationException; 5 | import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest; 6 | import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService; 7 | import org.springframework.security.oauth2.core.OAuth2AuthenticationException; 8 | import org.springframework.security.oauth2.core.oidc.user.OidcUser; 9 | import org.springframework.stereotype.Service; 10 | 11 | import com.javachinna.exception.OAuth2AuthenticationProcessingException; 12 | import com.javachinna.service.UserService; 13 | 14 | @Service 15 | public class CustomOidcUserService extends OidcUserService { 16 | 17 | @Autowired 18 | private UserService userService; 19 | 20 | @Override 21 | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { 22 | OidcUser oidcUser = super.loadUser(userRequest); 23 | try { 24 | return userService.processUserRegistration(userRequest.getClientRegistration().getRegistrationId(), oidcUser.getAttributes(), oidcUser.getIdToken(), 25 | oidcUser.getUserInfo()); 26 | } catch (AuthenticationException ex) { 27 | throw ex; 28 | } catch (Exception ex) { 29 | ex.printStackTrace(); 30 | // Throwing an instance of AuthenticationException will trigger the 31 | // OAuth2AuthenticationFailureHandler 32 | throw new OAuth2AuthenticationProcessingException(ex.getMessage(), ex.getCause()); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import javax.servlet.http.HttpServletResponse; 5 | 6 | import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository; 7 | import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; 8 | import org.springframework.stereotype.Component; 9 | 10 | import com.javachinna.util.CookieUtils; 11 | import com.nimbusds.oauth2.sdk.util.StringUtils; 12 | 13 | @Component 14 | public class HttpCookieOAuth2AuthorizationRequestRepository implements AuthorizationRequestRepository { 15 | public static final String OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME = "oauth2_auth_request"; 16 | public static final String REDIRECT_URI_PARAM_COOKIE_NAME = "redirect_uri"; 17 | private static final int cookieExpireSeconds = 180; 18 | 19 | @Override 20 | public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) { 21 | return CookieUtils.getCookie(request, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME).map(cookie -> CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class)) 22 | .orElse(null); 23 | } 24 | 25 | @Override 26 | public void saveAuthorizationRequest(OAuth2AuthorizationRequest authorizationRequest, HttpServletRequest request, HttpServletResponse response) { 27 | if (authorizationRequest == null) { 28 | CookieUtils.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME); 29 | CookieUtils.deleteCookie(request, response, REDIRECT_URI_PARAM_COOKIE_NAME); 30 | return; 31 | } 32 | 33 | CookieUtils.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtils.serialize(authorizationRequest), cookieExpireSeconds); 34 | String redirectUriAfterLogin = request.getParameter(REDIRECT_URI_PARAM_COOKIE_NAME); 35 | if (StringUtils.isNotBlank(redirectUriAfterLogin)) { 36 | CookieUtils.addCookie(response, REDIRECT_URI_PARAM_COOKIE_NAME, redirectUriAfterLogin, cookieExpireSeconds); 37 | } 38 | } 39 | 40 | @Override 41 | public OAuth2AuthorizationRequest removeAuthorizationRequest(HttpServletRequest request) { 42 | return this.loadAuthorizationRequest(request); 43 | } 44 | 45 | public void removeAuthorizationRequestCookies(HttpServletRequest request, HttpServletResponse response) { 46 | CookieUtils.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME); 47 | CookieUtils.deleteCookie(request, response, REDIRECT_URI_PARAM_COOKIE_NAME); 48 | } 49 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/OAuth2AccessTokenResponseConverterWithDefaults.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.LinkedHashMap; 6 | import java.util.Map; 7 | import java.util.Set; 8 | import java.util.stream.Collectors; 9 | import java.util.stream.Stream; 10 | 11 | import org.springframework.core.convert.converter.Converter; 12 | import org.springframework.security.oauth2.core.OAuth2AccessToken; 13 | import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; 14 | import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; 15 | import org.springframework.util.Assert; 16 | import org.springframework.util.StringUtils; 17 | 18 | /** 19 | * @author Joe Grandja 20 | */ 21 | public class OAuth2AccessTokenResponseConverterWithDefaults implements Converter, OAuth2AccessTokenResponse> { 22 | private static final Set TOKEN_RESPONSE_PARAMETER_NAMES = Stream 23 | .of(OAuth2ParameterNames.ACCESS_TOKEN, OAuth2ParameterNames.TOKEN_TYPE, OAuth2ParameterNames.EXPIRES_IN, OAuth2ParameterNames.REFRESH_TOKEN, OAuth2ParameterNames.SCOPE) 24 | .collect(Collectors.toSet()); 25 | 26 | private OAuth2AccessToken.TokenType defaultAccessTokenType = OAuth2AccessToken.TokenType.BEARER; 27 | 28 | @Override 29 | public OAuth2AccessTokenResponse convert(Map tokenResponseParameters) { 30 | String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN); 31 | 32 | OAuth2AccessToken.TokenType accessTokenType = this.defaultAccessTokenType; 33 | if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(tokenResponseParameters.get(OAuth2ParameterNames.TOKEN_TYPE))) { 34 | accessTokenType = OAuth2AccessToken.TokenType.BEARER; 35 | } 36 | 37 | long expiresIn = 0; 38 | if (tokenResponseParameters.containsKey(OAuth2ParameterNames.EXPIRES_IN)) { 39 | try { 40 | expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN)); 41 | } catch (NumberFormatException ex) { 42 | } 43 | } 44 | 45 | Set scopes = Collections.emptySet(); 46 | if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) { 47 | String scope = tokenResponseParameters.get(OAuth2ParameterNames.SCOPE); 48 | scopes = Arrays.stream(StringUtils.delimitedListToStringArray(scope, " ")).collect(Collectors.toSet()); 49 | } 50 | 51 | Map additionalParameters = new LinkedHashMap<>(); 52 | tokenResponseParameters.entrySet().stream().filter(e -> !TOKEN_RESPONSE_PARAMETER_NAMES.contains(e.getKey())) 53 | .forEach(e -> additionalParameters.put(e.getKey(), e.getValue())); 54 | 55 | return OAuth2AccessTokenResponse.withToken(accessToken).tokenType(accessTokenType).expiresIn(expiresIn).scopes(scopes).additionalParameters(additionalParameters).build(); 56 | } 57 | 58 | public final void setDefaultAccessTokenType(OAuth2AccessToken.TokenType defaultAccessTokenType) { 59 | Assert.notNull(defaultAccessTokenType, "defaultAccessTokenType cannot be null"); 60 | this.defaultAccessTokenType = defaultAccessTokenType; 61 | } 62 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/OAuth2AuthenticationFailureHandler.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2; 2 | 3 | import static com.javachinna.security.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.REDIRECT_URI_PARAM_COOKIE_NAME; 4 | 5 | import java.io.IOException; 6 | 7 | import javax.servlet.ServletException; 8 | import javax.servlet.http.Cookie; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.security.core.AuthenticationException; 14 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; 15 | import org.springframework.stereotype.Component; 16 | import org.springframework.web.util.UriComponentsBuilder; 17 | 18 | import com.javachinna.util.CookieUtils; 19 | 20 | @Component 21 | public class OAuth2AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { 22 | 23 | @Autowired 24 | HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository; 25 | 26 | @Override 27 | public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { 28 | String targetUrl = CookieUtils.getCookie(request, REDIRECT_URI_PARAM_COOKIE_NAME).map(Cookie::getValue).orElse(("/")); 29 | 30 | targetUrl = UriComponentsBuilder.fromUriString(targetUrl).queryParam("error", exception.getLocalizedMessage()).build().toUriString(); 31 | 32 | httpCookieOAuth2AuthorizationRequestRepository.removeAuthorizationRequestCookies(request, response); 33 | 34 | getRedirectStrategy().sendRedirect(request, response, targetUrl); 35 | } 36 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/OAuth2AuthenticationSuccessHandler.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2; 2 | 3 | import static com.javachinna.security.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.REDIRECT_URI_PARAM_COOKIE_NAME; 4 | 5 | import java.io.IOException; 6 | import java.net.URI; 7 | import java.util.Optional; 8 | 9 | import javax.servlet.ServletException; 10 | import javax.servlet.http.Cookie; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.security.core.Authentication; 16 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; 17 | import org.springframework.stereotype.Component; 18 | import org.springframework.web.util.UriComponentsBuilder; 19 | 20 | import com.javachinna.config.AppProperties; 21 | import com.javachinna.dto.LocalUser; 22 | import com.javachinna.exception.BadRequestException; 23 | import com.javachinna.security.jwt.TokenProvider; 24 | import com.javachinna.util.CookieUtils; 25 | 26 | @Component 27 | public class OAuth2AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { 28 | 29 | private TokenProvider tokenProvider; 30 | 31 | private AppProperties appProperties; 32 | 33 | private HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository; 34 | 35 | @Autowired 36 | OAuth2AuthenticationSuccessHandler(TokenProvider tokenProvider, AppProperties appProperties, 37 | HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository) { 38 | this.tokenProvider = tokenProvider; 39 | this.appProperties = appProperties; 40 | this.httpCookieOAuth2AuthorizationRequestRepository = httpCookieOAuth2AuthorizationRequestRepository; 41 | } 42 | 43 | @Override 44 | public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { 45 | String targetUrl = determineTargetUrl(request, response, authentication); 46 | 47 | if (response.isCommitted()) { 48 | logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); 49 | return; 50 | } 51 | 52 | clearAuthenticationAttributes(request, response); 53 | getRedirectStrategy().sendRedirect(request, response, targetUrl); 54 | } 55 | 56 | @Override 57 | protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { 58 | Optional redirectUri = CookieUtils.getCookie(request, REDIRECT_URI_PARAM_COOKIE_NAME).map(Cookie::getValue); 59 | 60 | if (redirectUri.isPresent() && !isAuthorizedRedirectUri(redirectUri.get())) { 61 | throw new BadRequestException("Sorry! We've got an Unauthorized Redirect URI and can't proceed with the authentication"); 62 | } 63 | 64 | String targetUrl = redirectUri.orElse(getDefaultTargetUrl()); 65 | LocalUser user = (LocalUser) authentication.getPrincipal(); 66 | String token = tokenProvider.createToken(user, true); 67 | 68 | return UriComponentsBuilder.fromUriString(targetUrl).queryParam("token", token).build().toUriString(); 69 | } 70 | 71 | protected void clearAuthenticationAttributes(HttpServletRequest request, HttpServletResponse response) { 72 | super.clearAuthenticationAttributes(request); 73 | httpCookieOAuth2AuthorizationRequestRepository.removeAuthorizationRequestCookies(request, response); 74 | } 75 | 76 | private boolean isAuthorizedRedirectUri(String uri) { 77 | URI clientRedirectUri = URI.create(uri); 78 | 79 | return appProperties.getOauth2().getAuthorizedRedirectUris().stream().anyMatch(authorizedRedirectUri -> { 80 | // Only validate host and port. Let the clients use different paths 81 | // if they want 82 | // to 83 | URI authorizedURI = URI.create(authorizedRedirectUri); 84 | if (authorizedURI.getHost().equalsIgnoreCase(clientRedirectUri.getHost()) && authorizedURI.getPort() == clientRedirectUri.getPort()) { 85 | return true; 86 | } 87 | return false; 88 | }); 89 | } 90 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/user/FacebookOAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public class FacebookOAuth2UserInfo extends OAuth2UserInfo { 6 | public FacebookOAuth2UserInfo(Map attributes) { 7 | super(attributes); 8 | } 9 | 10 | @Override 11 | public String getId() { 12 | return (String) attributes.get("id"); 13 | } 14 | 15 | @Override 16 | public String getName() { 17 | return (String) attributes.get("name"); 18 | } 19 | 20 | @Override 21 | public String getEmail() { 22 | return (String) attributes.get("email"); 23 | } 24 | 25 | @Override 26 | @SuppressWarnings("unchecked") 27 | public String getImageUrl() { 28 | if (attributes.containsKey("picture")) { 29 | Map pictureObj = (Map) attributes.get("picture"); 30 | if (pictureObj.containsKey("data")) { 31 | Map dataObj = (Map) pictureObj.get("data"); 32 | if (dataObj.containsKey("url")) { 33 | return (String) dataObj.get("url"); 34 | } 35 | } 36 | } 37 | return null; 38 | } 39 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/user/GithubOAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public class GithubOAuth2UserInfo extends OAuth2UserInfo { 6 | 7 | public GithubOAuth2UserInfo(Map attributes) { 8 | super(attributes); 9 | } 10 | 11 | @Override 12 | public String getId() { 13 | return ((Integer) attributes.get("id")).toString(); 14 | } 15 | 16 | @Override 17 | public String getName() { 18 | return (String) attributes.get("name"); 19 | } 20 | 21 | @Override 22 | public String getEmail() { 23 | return (String) attributes.get("email"); 24 | } 25 | 26 | @Override 27 | public String getImageUrl() { 28 | return (String) attributes.get("avatar_url"); 29 | } 30 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/user/GoogleOAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public class GoogleOAuth2UserInfo extends OAuth2UserInfo { 6 | 7 | public GoogleOAuth2UserInfo(Map attributes) { 8 | super(attributes); 9 | } 10 | 11 | @Override 12 | public String getId() { 13 | return (String) attributes.get("sub"); 14 | } 15 | 16 | @Override 17 | public String getName() { 18 | return (String) attributes.get("name"); 19 | } 20 | 21 | @Override 22 | public String getEmail() { 23 | return (String) attributes.get("email"); 24 | } 25 | 26 | @Override 27 | public String getImageUrl() { 28 | return (String) attributes.get("picture"); 29 | } 30 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/user/LinkedinOAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public class LinkedinOAuth2UserInfo extends OAuth2UserInfo { 6 | 7 | public LinkedinOAuth2UserInfo(Map attributes) { 8 | super(attributes); 9 | } 10 | 11 | @Override 12 | public String getId() { 13 | return (String) attributes.get("id"); 14 | } 15 | 16 | @Override 17 | public String getName() { 18 | return ((String) attributes.get("localizedFirstName")).concat(" ").concat((String) attributes.get("localizedLastName")); 19 | } 20 | 21 | @Override 22 | public String getEmail() { 23 | return (String) attributes.get("emailAddress"); 24 | } 25 | 26 | @Override 27 | public String getImageUrl() { 28 | return (String) attributes.get("pictureUrl"); 29 | } 30 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/user/OAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public abstract class OAuth2UserInfo { 6 | protected Map attributes; 7 | 8 | public OAuth2UserInfo(Map attributes) { 9 | this.attributes = attributes; 10 | } 11 | 12 | public Map getAttributes() { 13 | return attributes; 14 | } 15 | 16 | public abstract String getId(); 17 | 18 | public abstract String getName(); 19 | 20 | public abstract String getEmail(); 21 | 22 | public abstract String getImageUrl(); 23 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/user/OAuth2UserInfoFactory.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | import com.javachinna.dto.SocialProvider; 6 | import com.javachinna.exception.OAuth2AuthenticationProcessingException; 7 | 8 | public class OAuth2UserInfoFactory { 9 | public static OAuth2UserInfo getOAuth2UserInfo(String registrationId, Map attributes) { 10 | if (registrationId.equalsIgnoreCase(SocialProvider.GOOGLE.getProviderType())) { 11 | return new GoogleOAuth2UserInfo(attributes); 12 | } else if (registrationId.equalsIgnoreCase(SocialProvider.FACEBOOK.getProviderType())) { 13 | return new FacebookOAuth2UserInfo(attributes); 14 | } else if (registrationId.equalsIgnoreCase(SocialProvider.GITHUB.getProviderType())) { 15 | return new GithubOAuth2UserInfo(attributes); 16 | } else if (registrationId.equalsIgnoreCase(SocialProvider.LINKEDIN.getProviderType())) { 17 | return new LinkedinOAuth2UserInfo(attributes); 18 | } else if (registrationId.equalsIgnoreCase(SocialProvider.TWITTER.getProviderType())) { 19 | return new GithubOAuth2UserInfo(attributes); 20 | } else { 21 | throw new OAuth2AuthenticationProcessingException("Sorry! Login with " + registrationId + " is not supported yet."); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/service/LocalUserDetailService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.core.userdetails.UserDetailsService; 5 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import com.javachinna.dto.LocalUser; 10 | import com.javachinna.exception.ResourceNotFoundException; 11 | import com.javachinna.model.User; 12 | import com.javachinna.util.GeneralUtils; 13 | 14 | /** 15 | * 16 | * @author Chinna 17 | * 18 | */ 19 | @Service("localUserDetailService") 20 | public class LocalUserDetailService implements UserDetailsService { 21 | 22 | @Autowired 23 | private UserService userService; 24 | 25 | @Override 26 | @Transactional 27 | public LocalUser loadUserByUsername(final String email) throws UsernameNotFoundException { 28 | User user = userService.findUserByEmail(email); 29 | if (user == null) { 30 | throw new UsernameNotFoundException("User " + email + " was not found in the database"); 31 | } 32 | return createLocalUser(user); 33 | } 34 | 35 | @Transactional 36 | public LocalUser loadUserById(Long id) { 37 | User user = userService.findUserById(id).orElseThrow(() -> new ResourceNotFoundException("User", "id", id)); 38 | return createLocalUser(user); 39 | } 40 | 41 | /** 42 | * @param user 43 | * @return 44 | */ 45 | private LocalUser createLocalUser(User user) { 46 | return new LocalUser(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, GeneralUtils.buildSimpleGrantedAuthorities(user.getRoles()), user); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.service; 2 | 3 | import java.util.Map; 4 | import java.util.Optional; 5 | 6 | import org.springframework.security.oauth2.core.oidc.OidcIdToken; 7 | import org.springframework.security.oauth2.core.oidc.OidcUserInfo; 8 | 9 | import com.javachinna.dto.LocalUser; 10 | import com.javachinna.dto.SignUpRequest; 11 | import com.javachinna.exception.UserAlreadyExistAuthenticationException; 12 | import com.javachinna.model.User; 13 | 14 | /** 15 | * @author Chinna 16 | * @since 26/3/18 17 | */ 18 | public interface UserService { 19 | 20 | public User registerNewUser(SignUpRequest signUpRequest) throws UserAlreadyExistAuthenticationException; 21 | 22 | User findUserByEmail(String email); 23 | 24 | Optional findUserById(Long id); 25 | 26 | LocalUser processUserRegistration(String registrationId, Map attributes, OidcIdToken idToken, OidcUserInfo userInfo); 27 | } 28 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/service/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.service; 2 | 3 | import java.util.Calendar; 4 | import java.util.Date; 5 | import java.util.HashSet; 6 | import java.util.Map; 7 | import java.util.Optional; 8 | 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.security.crypto.password.PasswordEncoder; 11 | import org.springframework.security.oauth2.core.oidc.OidcIdToken; 12 | import org.springframework.security.oauth2.core.oidc.OidcUserInfo; 13 | import org.springframework.stereotype.Service; 14 | import org.springframework.transaction.annotation.Transactional; 15 | import org.springframework.util.StringUtils; 16 | 17 | import com.javachinna.dto.LocalUser; 18 | import com.javachinna.dto.SignUpRequest; 19 | import com.javachinna.dto.SocialProvider; 20 | import com.javachinna.exception.OAuth2AuthenticationProcessingException; 21 | import com.javachinna.exception.UserAlreadyExistAuthenticationException; 22 | import com.javachinna.model.Role; 23 | import com.javachinna.model.User; 24 | import com.javachinna.repo.RoleRepository; 25 | import com.javachinna.repo.UserRepository; 26 | import com.javachinna.security.oauth2.user.OAuth2UserInfo; 27 | import com.javachinna.security.oauth2.user.OAuth2UserInfoFactory; 28 | import com.javachinna.util.GeneralUtils; 29 | 30 | import dev.samstevens.totp.secret.SecretGenerator; 31 | 32 | /** 33 | * @author Chinna 34 | * @since 26/3/18 35 | */ 36 | @Service 37 | public class UserServiceImpl implements UserService { 38 | 39 | @Autowired 40 | private UserRepository userRepository; 41 | 42 | @Autowired 43 | private RoleRepository roleRepository; 44 | 45 | @Autowired 46 | private PasswordEncoder passwordEncoder; 47 | 48 | @Autowired 49 | private SecretGenerator secretGenerator; 50 | 51 | @Override 52 | @Transactional(value = "transactionManager") 53 | public User registerNewUser(final SignUpRequest signUpRequest) throws UserAlreadyExistAuthenticationException { 54 | if (signUpRequest.getUserID() != null && userRepository.existsById(signUpRequest.getUserID())) { 55 | throw new UserAlreadyExistAuthenticationException("User with User id " + signUpRequest.getUserID() + " already exist"); 56 | } else if (userRepository.existsByEmail(signUpRequest.getEmail())) { 57 | throw new UserAlreadyExistAuthenticationException("User with email id " + signUpRequest.getEmail() + " already exist"); 58 | } 59 | User user = buildUser(signUpRequest); 60 | Date now = Calendar.getInstance().getTime(); 61 | user.setCreatedDate(now); 62 | user.setModifiedDate(now); 63 | user = userRepository.save(user); 64 | userRepository.flush(); 65 | return user; 66 | } 67 | 68 | private User buildUser(final SignUpRequest formDTO) { 69 | User user = new User(); 70 | user.setDisplayName(formDTO.getDisplayName()); 71 | user.setEmail(formDTO.getEmail()); 72 | user.setPassword(passwordEncoder.encode(formDTO.getPassword())); 73 | final HashSet roles = new HashSet(); 74 | roles.add(roleRepository.findByName(Role.ROLE_USER)); 75 | user.setRoles(roles); 76 | user.setProvider(formDTO.getSocialProvider().getProviderType()); 77 | user.setEnabled(true); 78 | user.setProviderUserId(formDTO.getProviderUserId()); 79 | if (formDTO.isUsing2FA()) { 80 | user.setUsing2FA(true); 81 | user.setSecret(secretGenerator.generate()); 82 | } 83 | return user; 84 | } 85 | 86 | @Override 87 | public User findUserByEmail(final String email) { 88 | return userRepository.findByEmail(email); 89 | } 90 | 91 | @Override 92 | @Transactional 93 | public LocalUser processUserRegistration(String registrationId, Map attributes, OidcIdToken idToken, OidcUserInfo userInfo) { 94 | OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(registrationId, attributes); 95 | if (StringUtils.isEmpty(oAuth2UserInfo.getName())) { 96 | throw new OAuth2AuthenticationProcessingException("Name not found from OAuth2 provider"); 97 | } else if (StringUtils.isEmpty(oAuth2UserInfo.getEmail())) { 98 | throw new OAuth2AuthenticationProcessingException("Email not found from OAuth2 provider"); 99 | } 100 | SignUpRequest userDetails = toUserRegistrationObject(registrationId, oAuth2UserInfo); 101 | User user = findUserByEmail(oAuth2UserInfo.getEmail()); 102 | if (user != null) { 103 | if (!user.getProvider().equals(registrationId) && !user.getProvider().equals(SocialProvider.LOCAL.getProviderType())) { 104 | throw new OAuth2AuthenticationProcessingException( 105 | "Looks like you're signed up with " + user.getProvider() + " account. Please use your " + user.getProvider() + " account to login."); 106 | } 107 | user = updateExistingUser(user, oAuth2UserInfo); 108 | } else { 109 | user = registerNewUser(userDetails); 110 | } 111 | 112 | return LocalUser.create(user, attributes, idToken, userInfo); 113 | } 114 | 115 | private User updateExistingUser(User existingUser, OAuth2UserInfo oAuth2UserInfo) { 116 | existingUser.setDisplayName(oAuth2UserInfo.getName()); 117 | return userRepository.save(existingUser); 118 | } 119 | 120 | private SignUpRequest toUserRegistrationObject(String registrationId, OAuth2UserInfo oAuth2UserInfo) { 121 | return SignUpRequest.getBuilder().addProviderUserID(oAuth2UserInfo.getId()).addDisplayName(oAuth2UserInfo.getName()).addEmail(oAuth2UserInfo.getEmail()) 122 | .addSocialProvider(GeneralUtils.toSocialProvider(registrationId)).addPassword("changeit").build(); 123 | } 124 | 125 | @Override 126 | public Optional findUserById(Long id) { 127 | return userRepository.findById(id); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/util/CookieUtils.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.util; 2 | 3 | import java.util.Base64; 4 | import java.util.Optional; 5 | 6 | import javax.servlet.http.Cookie; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | import org.springframework.util.SerializationUtils; 11 | 12 | public class CookieUtils { 13 | 14 | public static Optional getCookie(HttpServletRequest request, String name) { 15 | Cookie[] cookies = request.getCookies(); 16 | 17 | if (cookies != null && cookies.length > 0) { 18 | for (Cookie cookie : cookies) { 19 | if (cookie.getName().equals(name)) { 20 | return Optional.of(cookie); 21 | } 22 | } 23 | } 24 | 25 | return Optional.empty(); 26 | } 27 | 28 | public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) { 29 | Cookie cookie = new Cookie(name, value); 30 | cookie.setPath("/"); 31 | cookie.setHttpOnly(true); 32 | cookie.setMaxAge(maxAge); 33 | response.addCookie(cookie); 34 | } 35 | 36 | public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String name) { 37 | Cookie[] cookies = request.getCookies(); 38 | if (cookies != null && cookies.length > 0) { 39 | for (Cookie cookie : cookies) { 40 | if (cookie.getName().equals(name)) { 41 | cookie.setValue(""); 42 | cookie.setPath("/"); 43 | cookie.setMaxAge(0); 44 | response.addCookie(cookie); 45 | } 46 | } 47 | } 48 | } 49 | 50 | public static String serialize(Object object) { 51 | return Base64.getUrlEncoder().encodeToString(SerializationUtils.serialize(object)); 52 | } 53 | 54 | public static T deserialize(Cookie cookie, Class cls) { 55 | return cls.cast(SerializationUtils.deserialize(Base64.getUrlDecoder().decode(cookie.getValue()))); 56 | } 57 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/util/GeneralUtils.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.util; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Set; 6 | import java.util.stream.Collectors; 7 | 8 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 9 | 10 | import com.javachinna.dto.LocalUser; 11 | import com.javachinna.dto.SocialProvider; 12 | import com.javachinna.dto.UserInfo; 13 | import com.javachinna.model.Role; 14 | import com.javachinna.model.User; 15 | 16 | /** 17 | * 18 | * @author Chinna 19 | * 20 | */ 21 | public class GeneralUtils { 22 | 23 | public static List buildSimpleGrantedAuthorities(final Set roles) { 24 | List authorities = new ArrayList<>(); 25 | for (Role role : roles) { 26 | authorities.add(new SimpleGrantedAuthority(role.getName())); 27 | } 28 | return authorities; 29 | } 30 | 31 | public static SocialProvider toSocialProvider(String providerId) { 32 | for (SocialProvider socialProvider : SocialProvider.values()) { 33 | if (socialProvider.getProviderType().equals(providerId)) { 34 | return socialProvider; 35 | } 36 | } 37 | return SocialProvider.LOCAL; 38 | } 39 | 40 | public static UserInfo buildUserInfo(LocalUser localUser) { 41 | List roles = localUser.getAuthorities().stream().map(item -> item.getAuthority()).collect(Collectors.toList()); 42 | User user = localUser.getUser(); 43 | return new UserInfo(user.getId().toString(), user.getDisplayName(), user.getEmail(), roles); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/validator/PasswordMatches.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.validator; 2 | 3 | import static java.lang.annotation.ElementType.ANNOTATION_TYPE; 4 | import static java.lang.annotation.ElementType.TYPE; 5 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 6 | 7 | import java.lang.annotation.Documented; 8 | import java.lang.annotation.Retention; 9 | import java.lang.annotation.Target; 10 | 11 | import javax.validation.Constraint; 12 | import javax.validation.Payload; 13 | 14 | @Target({ TYPE, ANNOTATION_TYPE }) 15 | @Retention(RUNTIME) 16 | @Constraint(validatedBy = PasswordMatchesValidator.class) 17 | @Documented 18 | public @interface PasswordMatches { 19 | 20 | String message() default "Passwords don't match"; 21 | 22 | Class[] groups() default {}; 23 | 24 | Class[] payload() default {}; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/validator/PasswordMatchesValidator.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.validator; 2 | 3 | import javax.validation.ConstraintValidator; 4 | import javax.validation.ConstraintValidatorContext; 5 | 6 | import com.javachinna.dto.SignUpRequest; 7 | 8 | public class PasswordMatchesValidator implements ConstraintValidator { 9 | 10 | @Override 11 | public boolean isValid(final SignUpRequest user, final ConstraintValidatorContext context) { 12 | return user.getPassword().equals(user.getMatchingPassword()); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # Database configuration props 2 | spring.datasource.url=jdbc:mysql://localhost:3306/demo?createDatabaseIfNotExist=true 3 | spring.datasource.username=root 4 | spring.datasource.password=secret 5 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 6 | 7 | # Hibernate props 8 | spring.jpa.show-sql=true 9 | #spring.jpa.hibernate.ddl-auto=none 10 | spring.jpa.hibernate.ddl-auto=create 11 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect 12 | 13 | # Social login provider props 14 | spring.security.oauth2.client.registration.google.clientId= 15 | spring.security.oauth2.client.registration.google.clientSecret= 16 | spring.security.oauth2.client.registration.facebook.clientId= 17 | spring.security.oauth2.client.registration.facebook.clientSecret= 18 | spring.security.oauth2.client.provider.facebook.user-info-uri=https://graph.facebook.com/me?fields=id,name,email,picture 19 | spring.security.oauth2.client.registration.github.clientId= 20 | spring.security.oauth2.client.registration.github.clientSecret= 21 | spring.security.oauth2.client.registration.linkedin.clientId= 22 | spring.security.oauth2.client.registration.linkedin.clientSecret= 23 | spring.security.oauth2.client.registration.linkedin.client-authentication-method=post 24 | spring.security.oauth2.client.registration.linkedin.authorization-grant-type=authorization_code 25 | spring.security.oauth2.client.registration.linkedin.scope=r_liteprofile, r_emailaddress 26 | spring.security.oauth2.client.registration.linkedin.redirect-uri={baseUrl}/login/oauth2/code/{registrationId} 27 | spring.security.oauth2.client.registration.linkedin.client-name=Linkedin 28 | spring.security.oauth2.client.registration.linkedin.provider=linkedin 29 | spring.security.oauth2.client.provider.linkedin.authorization-uri=https://www.linkedin.com/oauth/v2/authorization 30 | spring.security.oauth2.client.provider.linkedin.token-uri=https://www.linkedin.com/oauth/v2/accessToken 31 | spring.security.oauth2.client.provider.linkedin.user-info-uri=https://api.linkedin.com/v2/me 32 | spring.security.oauth2.client.provider.linkedin.user-name-attribute=id 33 | linkedin.email-address-uri=https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~)) 34 | 35 | app.auth.tokenSecret=926D96C90030DD58429D2751AC1BDBBC 36 | app.auth.tokenExpirationMsec=864000000 37 | # After successfully authenticating with the OAuth2 Provider, 38 | # we'll be generating an auth token for the user and sending the token to the 39 | # redirectUri mentioned by the frontend client in the /oauth2/authorization request. 40 | # We're not using cookies because they won't work well in mobile clients. 41 | app.oauth2.authorizedRedirectUris=https://client.javachinna.xyz/oauth2/redirect,myandroidapp://oauth2/redirect,myiosapp://oauth2/redirect 42 | # For detailed logging during development 43 | #logging.level.com=TRACE 44 | logging.level.org.springframework=INFO 45 | #logging.level.org.hibernate.SQL=TRACE 46 | #logging.level.org.hibernate.type=TRACE 47 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/resources/messages_en.properties: -------------------------------------------------------------------------------- 1 | NotEmpty=This field is required. 2 | Size.userDto.password=Try one with at least 6 characters. 3 | --------------------------------------------------------------------------------