[
  {
    "path": ".gitignore",
    "content": "*.env\ntarget/\n!.mvn/wrapper/maven-wrapper.jar\n!**/src/main/**/target/\n!**/src/test/**/target/\n\n### STS ###\n.apt_generated\n.classpath\n.factorypath\n.project\n.settings\n.springBeans\n.sts4-cache\n\n### IntelliJ IDEA ###\n.idea\n*.iws\n*.iml\n*.ipr\n\n### NetBeans ###\n/nbproject/private/\n/nbbuild/\n/dist/\n/nbdist/\n/.nb-gradle/\nbuild/\n!**/src/main/**/build/\n!**/src/test/**/build/\n\n### VS Code ###\n.vscode/\n"
  },
  {
    "path": ".mvn/wrapper/maven-wrapper.properties",
    "content": "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip\nwrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar\n"
  },
  {
    "path": "HELP.md",
    "content": "# Getting Started\n\n### Reference Documentation\nFor further reference, please consider the following sections:\n\n* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html)\n* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/3.0.6/maven-plugin/reference/html/)\n* [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.0.6/maven-plugin/reference/html/#build-image)\n* [Spring Data JPA](https://docs.spring.io/spring-boot/docs/3.0.6/reference/htmlsingle/#data.sql.jpa-and-spring-data)\n* [Spring Web](https://docs.spring.io/spring-boot/docs/3.0.6/reference/htmlsingle/#web)\n\n### Guides\nThe following guides illustrate how to use some features concretely:\n\n* [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/)\n* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/)\n* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/)\n* [Building REST services with Spring](https://spring.io/guides/tutorials/rest/)\n\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2018-Present Okta, Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# JUG Tours with Spring Boot and React\n \nThis example app shows how to create a Spring Boot API and CRUD (create, read, update, and delete) its data with a React app.\n\nPlease read [Use React and Spring Boot to Build a Simple CRUD App](https://developer.okta.com/blog/2022/06/17/simple-crud-react-and-spring-boot) to see how this app was created.\n\n**Prerequisites:** [Java 17](http://sdkman.io) and [Node.js 18+](https://nodejs.org/)\n\n> [Okta](https://developer.okta.com/) has Authentication and User Management APIs that reduce development time with instant-on, scalable user infrastructure. Okta's intuitive API and expert support make it easy for developers to authenticate, manage, and secure users and roles in any application.\n\n* [Getting Started](#getting-started)\n* [Links](#links)\n* [Help](#help)\n* [License](#license)\n\n## Getting Started\n\nTo install this example application, run the following commands:\n\n```bash\ngit clone https://github.com/oktadev/okta-spring-boot-react-crud-example.git spring-react\ncd spring-react\n```\n\nThis will get a copy of the project installed locally. \n\n### Create an Application in Okta\n\nBefore you begin, you'll need a free Okta developer account. Install the [Okta CLI](https://cli.okta.com) and run `okta register` to sign up for a new account. If you already have an account, run `okta login`.\n\nThen, run `okta apps create`. Select the default app name, or change it as you see fit. Choose **Web** and press **Enter**.\n\nSelect **Okta Spring Boot Starter**. Accept the default Redirect URI of `http://localhost:8080/login/oauth2/code/okta` and use `http://localhost:3000,http://localhost:8080` for the Logout Redirect URI.\n\nThe Okta CLI will create an OIDC Web App in your Okta Org. It will add the redirect URIs you specified and grant access to the `Everyone` group. You will see output like the following when it's finished:\n\n```shell\nOkta application configuration has been written to:\n  /path/to/app/src/main/resources/application.properties\n```\n\nOpen `src/main/resources/application.properties` to see the issuer and credentials for your app.\n\n```properties\nokta.oauth2.issuer=https://dev-133337.okta.com/oauth2/default\nokta.oauth2.client-id=0oab8eb55Kb9jdMIr5d6\nokta.oauth2.client-secret=NEVER-SHOW-SECRETS\n```\n\nNOTE: You can also use the Okta Admin Console to create your app. See [Create a Spring Boot App](https://developer.okta.com/docs/guides/sign-into-web-app-redirect/spring-boot/main/#create-an-okta-integration-for-your-app) for more information.\n\nRun `./mvnw spring-boot:run -Pprod` and log in to your app at `http://localhost:8080`.\n\n### Use Auth0 for OpenID Connect\n\nIf you'd rather use Auth0, that's possible too! First, you'll need to checkout the `auth0` branch of this repository.\n\n```bash\ngit clone -b auth0 https://github.com/oktadev/okta-spring-boot-react-crud-example.git spring-react\ncd spring-react\n```\n\nThen, install the [Auth0 CLI](https://github.com/auth0/auth0-cli) and run `auth0 login` in a terminal.\n\nNext, run `auth0 apps create` and specify the appropriate URLs:\n\n```bash\nauth0 apps create \\\n  --name \"Spring Boot + React\" \\\n  --description \"Spring Boot OIDC App\" \\\n  --type regular \\\n  --callbacks http://localhost:8080/login/oauth2/code/okta \\\n  --logout-urls http://localhost:3000,http://localhost:8080 \\\n  --reveal-secrets\n```\n\nModify your `src/main/resources/application.properties` to include your Auth0 issuer, client ID, and client secret. \n\n```properties\n# make sure to include the trailing slash for the Auth0 issuer\nokta.oauth2.issuer=https://<your-auth0-domain>/\nokta.oauth2.issuer.client-id=<your-client-id>\nokta.oauth2.issuer.client-secret=<your-client-secret>\n```\n\nNOTE: You can also use your [Auth0 dashboard](https://manage.auth0.com) to configure your application. Just make sure to use the same URLs specified above.\n\nRun `./mvnw spring-boot:run -Pprod` and log in to your app at `http://localhost:8080`.\n\n## Links\n\nThis example uses the following open source libraries:\n\n* [React](https://reactjs.org/)\n* [Spring Boot](https://spring.io/projects/spring-boot)\n* [Spring Security](https://spring.io/projects/spring-security)\n\n## Help\n\nPlease post any questions as comments on the [blog post](https://developer.okta.com/blog/2022/06/17/simple-crud-react-and-spring-boot), or visit our [Okta Developer Forums](https://devforum.okta.com/).\n\n## License\n\nApache 2.0, see [LICENSE](LICENSE).\n"
  },
  {
    "path": "app/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pnp\n.pnp.js\n\n# testing\n/coverage\n\n# production\n/build\n/node\n\n# misc\n.DS_Store\n.env.local\n.env.development.local\n.env.test.local\n.env.production.local\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n"
  },
  {
    "path": "app/README.md",
    "content": "# Getting Started with Create React App\n\nThis project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).\n\n## Available Scripts\n\nIn the project directory, you can run:\n\n### `npm start`\n\nRuns the app in the development mode.\\\nOpen [http://localhost:3000](http://localhost:3000) to view it in your browser.\n\nThe page will reload when you make changes.\\\nYou may also see any lint errors in the console.\n\n### `npm test`\n\nLaunches the test runner in the interactive watch mode.\\\nSee the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.\n\n### `npm run build`\n\nBuilds the app for production to the `build` folder.\\\nIt correctly bundles React in production mode and optimizes the build for the best performance.\n\nThe build is minified and the filenames include the hashes.\\\nYour app is ready to be deployed!\n\nSee the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.\n\n### `npm run eject`\n\n**Note: this is a one-way operation. Once you `eject`, you can't go back!**\n\nIf you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.\n\nInstead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.\n\nYou don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.\n\n## Learn More\n\nYou can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).\n\nTo learn React, check out the [React documentation](https://reactjs.org/).\n\n### Code Splitting\n\nThis section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)\n\n### Analyzing the Bundle Size\n\nThis section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)\n\n### Making a Progressive Web App\n\nThis section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)\n\n### Advanced Configuration\n\nThis section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)\n\n### Deployment\n\nThis section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)\n\n### `npm run build` fails to minify\n\nThis section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)\n"
  },
  {
    "path": "app/package.json",
    "content": "{\n  \"name\": \"app\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"@testing-library/jest-dom\": \"^5.16.5\",\n    \"@testing-library/react\": \"^13.4.0\",\n    \"@testing-library/user-event\": \"^13.5.0\",\n    \"bootstrap\": \"^5.2.3\",\n    \"react\": \"^18.2.0\",\n    \"react-cookie\": \"^4.1.1\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-router-dom\": \"^6.10.0\",\n    \"react-scripts\": \"5.0.1\",\n    \"reactstrap\": \"^9.1.9\",\n    \"web-vitals\": \"^2.1.4\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"test\": \"react-scripts test\",\n    \"eject\": \"react-scripts eject\"\n  },\n  \"proxy\": \"http://localhost:8080\",\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\",\n      \"react-app/jest\"\n    ]\n  },\n  \"browserslist\": {\n    \"production\": [\n      \">0.2%\",\n      \"not dead\",\n      \"not op_mini all\"\n    ],\n    \"development\": [\n      \"last 1 chrome version\",\n      \"last 1 firefox version\",\n      \"last 1 safari version\"\n    ]\n  }\n}\n"
  },
  {
    "path": "app/public/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "app/public/manifest.json",
    "content": "{\n  \"short_name\": \"React App\",\n  \"name\": \"Create React App Sample\",\n  \"icons\": [\n    {\n      \"src\": \"favicon.ico\",\n      \"sizes\": \"64x64 32x32 24x24 16x16\",\n      \"type\": \"image/x-icon\"\n    },\n    {\n      \"src\": \"logo192.png\",\n      \"type\": \"image/png\",\n      \"sizes\": \"192x192\"\n    },\n    {\n      \"src\": \"logo512.png\",\n      \"type\": \"image/png\",\n      \"sizes\": \"512x512\"\n    }\n  ],\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "app/public/robots.txt",
    "content": "# https://www.robotstxt.org/robotstxt.html\nUser-agent: *\nDisallow:\n"
  },
  {
    "path": "app/src/App.css",
    "content": ".App {\n  text-align: center;\n}\n\n.App-logo {\n  height: 40vmin;\n  pointer-events: none;\n}\n\n@media (prefers-reduced-motion: no-preference) {\n  .App-logo {\n    animation: App-logo-spin infinite 20s linear;\n  }\n}\n\n.App-header {\n  background-color: #282c34;\n  min-height: 100vh;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  font-size: calc(10px + 2vmin);\n  color: white;\n}\n\n.App-link {\n  color: #61dafb;\n}\n\n@keyframes App-logo-spin {\n  from {\n    transform: rotate(0deg);\n  }\n  to {\n    transform: rotate(360deg);\n  }\n}\n\nnav + .container, nav + .container-fluid {\n  margin-top: 20px;\n}\n"
  },
  {
    "path": "app/src/App.js",
    "content": "import React from 'react';\nimport './App.css';\nimport Home from './Home';\nimport { BrowserRouter as Router, Route, Routes } from 'react-router-dom';\nimport GroupList from './GroupList';\nimport GroupEdit from './GroupEdit';\n\nconst App = () => {\n  return (\n    <Router>\n      <Routes>\n        <Route exact path=\"/\" element={<Home/>}/>\n        <Route path=\"/groups\" exact={true} element={<GroupList/>}/>\n        <Route path=\"/groups/:id\" exact={true} element={<GroupEdit/>}/>\n      </Routes>\n    </Router>\n  )\n}\n\nexport default App;\n"
  },
  {
    "path": "app/src/App.test.js",
    "content": "import { render, screen } from '@testing-library/react';\nimport App from './App';\n\ntest('renders loading...', () => {\n  render(<App />);\n  const linkElement = screen.getByText(/loading/i);\n  expect(linkElement).toBeInTheDocument();\n});\n"
  },
  {
    "path": "app/src/AppNavbar.js",
    "content": "import React, { useState } from 'react';\nimport { Collapse, Nav, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap';\nimport { Link } from 'react-router-dom';\n\nconst AppNavbar = () => {\n\n  const [isOpen, setIsOpen] = useState(false);\n\n  return (\n    <Navbar color=\"dark\" dark expand=\"md\">\n      <NavbarBrand tag={Link} to=\"/\">Home</NavbarBrand>\n      <NavbarToggler onClick={() => {\n        setIsOpen(!isOpen)\n      }}/>\n      <Collapse isOpen={isOpen} navbar>\n        <Nav className=\"justify-content-end\" style={{ width: \"100%\" }} navbar>\n          <NavItem>\n            <NavLink href=\"https://twitter.com/oktadev\">@oktadev</NavLink>\n          </NavItem>\n          <NavItem>\n            <NavLink href=\"https://github.com/oktadev/okta-spring-boot-react-crud-example\">GitHub</NavLink>\n          </NavItem>\n        </Nav>\n      </Collapse>\n    </Navbar>\n  );\n};\n\nexport default AppNavbar;\n"
  },
  {
    "path": "app/src/GroupEdit.js",
    "content": "import React, { useEffect, useState } from 'react';\nimport { Link, useNavigate, useParams } from 'react-router-dom';\nimport { Button, Container, Form, FormGroup, Input, Label } from 'reactstrap';\nimport AppNavbar from './AppNavbar';\nimport { useCookies } from 'react-cookie';\n\nconst GroupEdit = () => {\n  const initialFormState = {\n    name: '',\n    address: '',\n    city: '',\n    stateOrProvince: '',\n    country: '',\n    postalCode: ''\n  };\n  const [group, setGroup] = useState(initialFormState);\n  const navigate = useNavigate();\n  const { id } = useParams();\n  const [cookies] = useCookies(['XSRF-TOKEN']);\n\n  useEffect(() => {\n    if (id !== 'new') {\n      fetch(`/api/group/${id}`)\n        .then(response => response.json())\n        .then(data => setGroup(data));\n    }\n  }, [id, setGroup]);\n\n  const handleChange = (event) => {\n    const { name, value } = event.target\n\n    setGroup({ ...group, [name]: value })\n  }\n\n  const handleSubmit = async (event) => {\n    event.preventDefault();\n\n    await fetch(`/api/group${group.id ? `/${group.id}` : ''}`, {\n      method: (group.id) ? 'PUT' : 'POST',\n      headers: {\n        'X-XSRF-TOKEN': cookies['XSRF-TOKEN'],\n        'Accept': 'application/json',\n        'Content-Type': 'application/json'\n      },\n      body: JSON.stringify(group),\n      credentials: 'include'\n    });\n    setGroup(initialFormState);\n    navigate('/groups');\n  }\n\n  const title = <h2>{group.id ? 'Edit Group' : 'Add Group'}</h2>;\n\n  return (<div>\n      <AppNavbar/>\n      <Container>\n        {title}\n        <Form onSubmit={handleSubmit}>\n          <FormGroup>\n            <Label for=\"name\">Name</Label>\n            <Input type=\"text\" name=\"name\" id=\"name\" value={group.name || ''}\n                   onChange={handleChange} autoComplete=\"name\"/>\n          </FormGroup>\n          <FormGroup>\n            <Label for=\"address\">Address</Label>\n            <Input type=\"text\" name=\"address\" id=\"address\" value={group.address || ''}\n                   onChange={handleChange} autoComplete=\"address-level1\"/>\n          </FormGroup>\n          <FormGroup>\n            <Label for=\"city\">City</Label>\n            <Input type=\"text\" name=\"city\" id=\"city\" value={group.city || ''}\n                   onChange={handleChange} autoComplete=\"address-level1\"/>\n          </FormGroup>\n          <div className=\"row\">\n            <FormGroup className=\"col-md-4 mb-3\">\n              <Label for=\"stateOrProvince\">State/Province</Label>\n              <Input type=\"text\" name=\"stateOrProvince\" id=\"stateOrProvince\" value={group.stateOrProvince || ''}\n                     onChange={handleChange} autoComplete=\"address-level1\"/>\n            </FormGroup>\n            <FormGroup className=\"col-md-5 mb-3\">\n              <Label for=\"country\">Country</Label>\n              <Input type=\"text\" name=\"country\" id=\"country\" value={group.country || ''}\n                     onChange={handleChange} autoComplete=\"address-level1\"/>\n            </FormGroup>\n            <FormGroup className=\"col-md-3 mb-3\">\n              <Label for=\"country\">Postal Code</Label>\n              <Input type=\"text\" name=\"postalCode\" id=\"postalCode\" value={group.postalCode || ''}\n                     onChange={handleChange} autoComplete=\"address-level1\"/>\n            </FormGroup>\n          </div>\n          <FormGroup>\n            <Button color=\"primary\" type=\"submit\">Save</Button>{' '}\n            <Button color=\"secondary\" tag={Link} to=\"/groups\">Cancel</Button>\n          </FormGroup>\n        </Form>\n      </Container>\n    </div>\n  )\n};\n\nexport default GroupEdit;\n"
  },
  {
    "path": "app/src/GroupList.js",
    "content": "import React, { useEffect, useState } from 'react';\nimport { Button, ButtonGroup, Container, Table } from 'reactstrap';\nimport AppNavbar from './AppNavbar';\nimport { Link } from 'react-router-dom';\nimport { useCookies } from 'react-cookie';\n\nconst GroupList = () => {\n\n  const [groups, setGroups] = useState([]);\n  const [loading, setLoading] = useState(false);\n  const [cookies] = useCookies(['XSRF-TOKEN']);\n\n  useEffect(() => {\n    setLoading(true);\n\n    fetch('api/groups')\n      .then(response => response.json())\n      .then(data => {\n        setGroups(data);\n        setLoading(false);\n      })\n  }, []);\n\n  const remove = async (id) => {\n    await fetch(`/api/group/${id}`, {\n      method: 'DELETE',\n      headers: {\n        'X-XSRF-TOKEN': cookies['XSRF-TOKEN'],\n        'Accept': 'application/json',\n        'Content-Type': 'application/json'\n      },\n      credentials: 'include'\n    }).then(() => {\n      let updatedGroups = [...groups].filter(i => i.id !== id);\n      setGroups(updatedGroups);\n    });\n  }\n\n  if (loading) {\n    return <p>Loading...</p>;\n  }\n\n  const groupList = groups.map(group => {\n    const address = `${group.address || ''} ${group.city || ''} ${group.stateOrProvince || ''}`;\n    return <tr key={group.id}>\n      <td style={{ whiteSpace: 'nowrap' }}>{group.name}</td>\n      <td>{address}</td>\n      <td>{group.events.map(event => {\n        return <div key={event.id}>{new Intl.DateTimeFormat('en-US', {\n          year: 'numeric',\n          month: 'long',\n          day: '2-digit'\n        }).format(new Date(event.date))}: {event.title}</div>\n      })}</td>\n      <td>\n        <ButtonGroup>\n          <Button size=\"sm\" color=\"primary\" tag={Link} to={\"/groups/\" + group.id}>Edit</Button>\n          <Button size=\"sm\" color=\"danger\" onClick={() => remove(group.id)}>Delete</Button>\n        </ButtonGroup>\n      </td>\n    </tr>\n  });\n\n  return (\n    <div>\n      <AppNavbar/>\n      <Container fluid>\n        <div className=\"float-end\">\n          <Button color=\"success\" tag={Link} to=\"/groups/new\">Add Group</Button>\n        </div>\n        <h3>My JUG Tour</h3>\n        <Table className=\"mt-4\">\n          <thead>\n          <tr>\n            <th width=\"20%\">Name</th>\n            <th width=\"20%\">Location</th>\n            <th>Events</th>\n            <th width=\"10%\">Actions</th>\n          </tr>\n          </thead>\n          <tbody>\n          {groupList}\n          </tbody>\n        </Table>\n      </Container>\n    </div>\n  );\n};\n\nexport default GroupList;\n"
  },
  {
    "path": "app/src/Home.js",
    "content": "import React, { useEffect, useState } from 'react';\nimport './App.css';\nimport AppNavbar from './AppNavbar';\nimport { Link } from 'react-router-dom';\nimport { Button, Container } from 'reactstrap';\nimport { useCookies } from 'react-cookie';\n\nconst Home = () => {\n\n  const [authenticated, setAuthenticated] = useState(false);\n  const [loading, setLoading] = useState(false);\n  const [user, setUser] = useState(undefined);\n  const [cookies] = useCookies(['XSRF-TOKEN']); // <.>\n\n  useEffect(() => {\n    setLoading(true);\n    fetch('api/user', { credentials: 'include' }) // <.>\n      .then(response => response.text())\n      .then(body => {\n        if (body === '') {\n          setAuthenticated(false);\n        } else {\n          setUser(JSON.parse(body));\n          setAuthenticated(true);\n        }\n        setLoading(false);\n      });\n  }, [setAuthenticated, setLoading, setUser])\n\n  const login = () => {\n    let port = (window.location.port ? ':' + window.location.port : '');\n    if (port === ':3000') {\n      port = ':8080';\n    }\n    window.location.href = `//${window.location.hostname}${port}/api/private`;\n  }\n\n  const logout = () => {\n    fetch('/api/logout', {\n      method: 'POST', credentials: 'include',\n      headers: { 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'] } // <.>\n    })\n      .then(res => res.json())\n      .then(response => {\n        window.location.href = `${response.logoutUrl}?id_token_hint=${response.idToken}`\n          + `&post_logout_redirect_uri=${window.location.origin}`;\n      });\n  }\n\n  const message = user ?\n    <h2>Welcome, {user.name}!</h2> :\n    <p>Please log in to manage your JUG Tour.</p>;\n\n  const button = authenticated ?\n    <div>\n      <Button color=\"link\"><Link to=\"/groups\">Manage JUG Tour</Link></Button>\n      <br/>\n      <Button color=\"link\" onClick={logout}>Logout</Button>\n    </div> :\n    <Button color=\"primary\" onClick={login}>Login</Button>;\n\n  if (loading) {\n    return <p>Loading...</p>;\n  }\n\n  return (\n    <div>\n      <AppNavbar/>\n      <Container fluid>\n        {message}\n        {button}\n      </Container>\n    </div>\n  );\n}\n\nexport default Home;\n"
  },
  {
    "path": "app/src/index.css",
    "content": "body {\n  margin: 0;\n  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',\n    sans-serif;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n    monospace;\n}\n"
  },
  {
    "path": "app/src/index.js",
    "content": "import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport './index.css';\nimport App from './App';\nimport reportWebVitals from './reportWebVitals';\nimport 'bootstrap/dist/css/bootstrap.min.css';\nimport { CookiesProvider } from 'react-cookie';\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(\n  <React.StrictMode>\n    <CookiesProvider>\n      <App/>\n    </CookiesProvider>\n  </React.StrictMode>\n);\n\n// If you want to start measuring performance in your app, pass a function\n// to log results (for example: reportWebVitals(console.log))\n// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals\nreportWebVitals();\n"
  },
  {
    "path": "app/src/reportWebVitals.js",
    "content": "const reportWebVitals = onPerfEntry => {\n  if (onPerfEntry && onPerfEntry instanceof Function) {\n    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {\n      getCLS(onPerfEntry);\n      getFID(onPerfEntry);\n      getFCP(onPerfEntry);\n      getLCP(onPerfEntry);\n      getTTFB(onPerfEntry);\n    });\n  }\n};\n\nexport default reportWebVitals;\n"
  },
  {
    "path": "app/src/setupTests.js",
    "content": "// jest-dom adds custom jest matchers for asserting on DOM nodes.\n// allows you to do things like:\n// expect(element).toHaveTextContent(/react/i)\n// learn more: https://github.com/testing-library/jest-dom\nimport '@testing-library/jest-dom';\n"
  },
  {
    "path": "demo.adoc",
    "content": ":experimental:\n:commandkey: &#8984;\n:toc: macro\n:source-highlighter: highlight.js\n\n= Use React and Spring Boot to Build a Simple CRUD App\n\nToday, I'll show you how to create a basic CRUD app with Spring Boot and React. In this demo, I'll use the OAuth 2.0 Authorization Code flow and package the React app in the Spring Boot app for production. At the same time, I'll show you how to keep React's productive workflow for developing locally.\n\n**Prerequisites**:\n\n- http://sdkman.io[Java 17]\n- https://nodejs.org/[Node 16]\n- https://github.com/okta/okta-cli[Okta CLI]\n\nTIP: The brackets at the end of some steps indicate the IntelliJ Live Templates to use. You can find the template definitions at https://github.com/mraible/idea-live-templates[mraible/idea-live-templates].\n\ntoc::[]\n\n== Create an API app with Spring Boot\n\n. Navigate to https://start.spring.io[start.spring.io] and make the following selections:\n\n* **Project:** `Maven Project`\n* **Group:** `com.okta.developer`\n* **Artifact:** `jugtours`\n* **Dependencies**: `JPA`, `H2`, `Web`, `Lombok`\n\n. Click **Generate Project**, expand `jugtours.zip` after downloading, and open the project in your favorite IDE.\n\n=== Add a JPA domain model\n\n. Create a `src/main/java/com/okta/developer/jugtours/model` directory and a `Group.java` class in it. [`sbr-group`]\n+\n.`Group.java`\n[%collapsible]\n====\n[source,java]\n----\npackage com.okta.developer.jugtours.model;\n\nimport lombok.Data;\nimport lombok.NoArgsConstructor;\nimport lombok.NonNull;\nimport lombok.RequiredArgsConstructor;\n\nimport jakarta.persistence.*;\nimport java.util.Set;\n\n@Data\n@NoArgsConstructor\n@RequiredArgsConstructor\n@Entity\n@Table(name = \"user_group\")\npublic class Group {\n\n    @Id\n    @GeneratedValue\n    private Long id;\n    @NonNull\n    private String name;\n    private String address;\n    private String city;\n    private String stateOrProvince;\n    private String country;\n    private String postalCode;\n    @ManyToOne(cascade=CascadeType.PERSIST)\n    private User user;\n\n    @OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL)\n    private Set<Event> events;\n}\n----\n====\n\n. Create an `Event.java` class in the same package. [`sbr-event`]\n+\n.`Event.java`\n[%collapsible]\n====\n[source,java]\n----\npackage com.okta.developer.jugtours.model;\n\nimport lombok.AllArgsConstructor;\nimport lombok.Builder;\nimport lombok.Data;\nimport lombok.NoArgsConstructor;\n\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.GeneratedValue;\nimport jakarta.persistence.Id;\nimport jakarta.persistence.ManyToMany;\nimport java.time.Instant;\nimport java.util.Set;\n\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Entity\npublic class Event {\n\n    @Id\n    @GeneratedValue\n    private Long id;\n    private Instant date;\n    private String title;\n    private String description;\n    @ManyToMany\n    private Set<User> attendees;\n}\n----\n====\n\n. And a `User.java` class. [`sbr-user`]\n+\n.`User.java`\n[%collapsible]\n====\n[source,java]\n----\npackage com.okta.developer.jugtours.model;\n\nimport lombok.AllArgsConstructor;\nimport lombok.Data;\nimport lombok.NoArgsConstructor;\n\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.Id;\nimport jakarta.persistence.Table;\n\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"users\")\npublic class User {\n\n    @Id\n    private String id;\n    private String name;\n    private String email;\n}\n----\n====\n\n. Create a `GroupRepository.java` to manage the group entity. [`sbr-group-repo`]\n+\n.`GroupRepository.java`\n[%collapsible]\n====\n[source,java]\n----\npackage com.okta.developer.jugtours.model;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\n\nimport java.util.List;\n\npublic interface GroupRepository extends JpaRepository<Group, Long> {\n    Group findByName(String name);\n}\n----\n====\n\n. To load some default data, create an `Initializer.java` class in the `com.okta.developer.jugtours` package. [`sbr-init`]\n+\n.`Initializer.java`\n[%collapsible]\n====\n[source,java]\n----\npackage com.okta.developer.jugtours;\n\nimport com.okta.developer.jugtours.model.Event;\nimport com.okta.developer.jugtours.model.Group;\nimport com.okta.developer.jugtours.model.GroupRepository;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.stereotype.Component;\n\nimport java.time.Instant;\nimport java.util.Collections;\nimport java.util.stream.Stream;\n\n@Component\nclass Initializer implements CommandLineRunner {\n\n    private final GroupRepository repository;\n\n    public Initializer(GroupRepository repository) {\n        this.repository = repository;\n    }\n\n    @Override\n    public void run(String... strings) {\n        Stream.of(\"Seattle JUG\", \"Denver JUG\", \"Dublin JUG\",\n                \"London JUG\").forEach(name ->\n                repository.save(new Group(name))\n        );\n\n        Group djug = repository.findByName(\"Seattle JUG\");\n        Event e = Event.builder().title(\"Micro Frontends for Java Developers\")\n                .description(\"JHipster now has microfrontend support!\")\n                .date(Instant.parse(\"2022-09-13T17:00:00.000Z\"))\n                .build();\n        djug.setEvents(Collections.singleton(e));\n        repository.save(djug);\n\n        repository.findAll().forEach(System.out::println);\n    }\n}\n----\n====\n+\nTIP: If your IDE has issues with `Event.builder()`, you need to turn on annotation processing and/or install the Lombok plugin. I had to uninstall/reinstall the Lombok plugin in IntelliJ IDEA to get things to work.\n+\n. Start your app with `mvn spring-boot:run` and you should see groups and events being created.\n\n. Add a `GroupController.java` class (in `src/main/java/.../jugtours/web`) that allows you to CRUD groups. [`sbr-group-controller`]\n+\n.`GroupController.java`\n[%collapsible]\n====\n[source,java]\n----\npackage com.okta.developer.jugtours.web;\n\nimport com.okta.developer.jugtours.model.Group;\nimport com.okta.developer.jugtours.model.GroupRepository;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.*;\n\nimport jakarta.validation.Valid;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.Collection;\nimport java.util.Optional;\n\n@RestController\n@RequestMapping(\"/api\")\nclass GroupController {\n\n    private final Logger log = LoggerFactory.getLogger(GroupController.class);\n    private GroupRepository groupRepository;\n\n    public GroupController(GroupRepository groupRepository) {\n        this.groupRepository = groupRepository;\n    }\n\n    @GetMapping(\"/groups\")\n    Collection<Group> groups() {\n        return groupRepository.findAll();\n    }\n\n    @GetMapping(\"/group/{id}\")\n    ResponseEntity<?> getGroup(@PathVariable Long id) {\n        Optional<Group> group = groupRepository.findById(id);\n        return group.map(response -> ResponseEntity.ok().body(response))\n                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));\n    }\n\n    @PostMapping(\"/group\")\n    ResponseEntity<Group> createGroup(@Valid @RequestBody Group group) throws URISyntaxException {\n        log.info(\"Request to create group: {}\", group);\n        Group result = groupRepository.save(group);\n        return ResponseEntity.created(new URI(\"/api/group/\" + result.getId()))\n                .body(result);\n    }\n\n    @PutMapping(\"/group/{id}\")\n    ResponseEntity<Group> updateGroup(@Valid @RequestBody Group group) {\n        log.info(\"Request to update group: {}\", group);\n        Group result = groupRepository.save(group);\n        return ResponseEntity.ok().body(result);\n    }\n\n    @DeleteMapping(\"/group/{id}\")\n    public ResponseEntity<?> deleteGroup(@PathVariable Long id) {\n        log.info(\"Request to delete group: {}\", id);\n        groupRepository.deleteById(id);\n        return ResponseEntity.ok().build();\n    }\n}\n----\n====\n\n. Add the following dependency to your `pom.xml` to fix compilation errors:\n+\n[source,xml]\n----\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-validation</artifactId>\n</dependency>\n----\n\n. Restart the app and hit `http://localhost:8080/api/groups` with https://httpie.org[HTTPie] and you should see the list of groups.\n\n    http :8080/api/groups\n\n. You can create, read, update, and delete groups with the following commands.\n+\n[source,shell]\n----\nhttp POST :8080/api/group name='Utah JUG' city='Salt Lake City' country=USA\nhttp :8080/api/group/5\nhttp PUT :8080/api/group/5 id=6 name='Utah JUG' address='On the slopes'\nhttp DELETE :8080/api/group/5\n----\n\n== Create a React UI with Create React App\n\n. Create a new project in the root directory with `npx` and Create React App.\n+\n[source,shell]\n----\nnpx create-react-app@5 app\n----\n\n. After the app creation process completes, navigate into the `app` directory and install Bootstrap, cookie support for React, React Router, and Reactstrap.\n+\n[source,shell]\n----\ncd app\nnpm i bootstrap@5 react-cookie@4 react-router-dom@6 reactstrap@9\n----\n\n. Add Bootstrap's CSS file as an import in `app/src/index.js`.\n+\n[source,js]\n----\nimport 'bootstrap/dist/css/bootstrap.min.css';\n----\n\n== Call your Spring Boot API and display the results\n\n. Modify `App.js` to use the following code that calls `/api/groups` and displays the list in the UI. [`sbr-app`]\n+\n.`app/src/App.js`\n[%collapsible]\n====\n[source,jsx]\n----\nimport React, { useEffect, useState } from 'react';\nimport logo from './logo.svg';\nimport './App.css';\n\nconst App = () => {\n\n  const [groups, setGroups] = useState([]);\n  const [loading, setLoading] = useState(false);\n\n  useEffect(() => {\n    setLoading(true);\n\n    fetch('api/groups')\n      .then(response => response.json())\n      .then(data => {\n        setGroups(data);\n        setLoading(false);\n      })\n  }, []);\n\n  if (loading) {\n    return <p>Loading...</p>;\n  }\n\n  return (\n    <div className=\"App\">\n      <header className=\"App-header\">\n        <img src={logo} className=\"App-logo\" alt=\"logo\" />\n        <div className=\"App-intro\">\n          <h2>JUG List</h2>\n          {groups.map(group =>\n            <div key={group.id}>\n              {group.name}\n            </div>\n          )}\n        </div>\n      </header>\n    </div>\n  );\n}\n\nexport default App;\n----\n====\n\n. To proxy from `/api` to `http://localhost:8080/api`, add a proxy setting to `app/package.json`.\n+\n[source,json]\n----\n\"scripts\": {...},\n\"proxy\": \"http://localhost:8080\",\n----\n\n. Make sure Spring Boot is running, then run `npm start` in your `app` directory. You should see the list of default groups.\n\n== Build a React `GroupList` component\n\n. React is all about components, and you don't want to render everything in your main `App`, so create `GroupList.js` and populate it with the following JavaScript. [`sbr-group-list`]\n+\n.`src/app/GroupList.js`\n[%collapsible]\n====\n[source,jsx]\n----\nimport React, { useEffect, useState } from 'react';\nimport { Button, ButtonGroup, Container, Table } from 'reactstrap';\nimport AppNavbar from './AppNavbar';\nimport { Link } from 'react-router-dom';\n\nconst GroupList = () => {\n\n  const [groups, setGroups] = useState([]);\n  const [loading, setLoading] = useState(false);\n\n  useEffect(() => {\n    setLoading(true);\n\n    fetch('api/groups')\n      .then(response => response.json())\n      .then(data => {\n        setGroups(data);\n        setLoading(false);\n      })\n  }, []);\n\n  const remove = async (id) => {\n    await fetch(`/api/group/${id}`, {\n      method: 'DELETE',\n      headers: {\n        'Accept': 'application/json',\n        'Content-Type': 'application/json'\n      }\n    }).then(() => {\n      let updatedGroups = [...groups].filter(i => i.id !== id);\n      setGroups(updatedGroups);\n    });\n  }\n\n  if (loading) {\n    return <p>Loading...</p>;\n  }\n\n  const groupList = groups.map(group => {\n    const address = `${group.address || ''} ${group.city || ''} ${group.stateOrProvince || ''}`;\n    return <tr key={group.id}>\n      <td style={{whiteSpace: 'nowrap'}}>{group.name}</td>\n      <td>{address}</td>\n      <td>{group.events.map(event => {\n        return <div key={event.id}>{new Intl.DateTimeFormat('en-US', {\n          year: 'numeric',\n          month: 'long',\n          day: '2-digit'\n        }).format(new Date(event.date))}: {event.title}</div>\n      })}</td>\n      <td>\n        <ButtonGroup>\n          <Button size=\"sm\" color=\"primary\" tag={Link} to={\"/groups/\" + group.id}>Edit</Button>\n          <Button size=\"sm\" color=\"danger\" onClick={() => remove(group.id)}>Delete</Button>\n        </ButtonGroup>\n      </td>\n    </tr>\n  });\n\n  return (\n    <div>\n      <AppNavbar/>\n      <Container fluid>\n        <div className=\"float-end\">\n          <Button color=\"success\" tag={Link} to=\"/groups/new\">Add Group</Button>\n        </div>\n        <h3>My JUG Tour</h3>\n        <Table className=\"mt-4\">\n          <thead>\n          <tr>\n            <th width=\"20%\">Name</th>\n            <th width=\"20%\">Location</th>\n            <th>Events</th>\n            <th width=\"10%\">Actions</th>\n          </tr>\n          </thead>\n          <tbody>\n          {groupList}\n          </tbody>\n        </Table>\n      </Container>\n    </div>\n  );\n};\n\nexport default GroupList;\n----\n====\n\n. Create `AppNavbar.js` in the same directory to establish a common UI feature between components. [`sbr-navbar`]\n+\n.`src/app/AppNavbar.js`\n[%collapsible]\n====\n[source,jsx]\n----\nimport React, { useState } from 'react';\nimport { Collapse, Nav, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap';\nimport { Link } from 'react-router-dom';\n\nconst AppNavbar = () => {\n\n  const [isOpen, setIsOpen] = useState(false);\n\n  return (\n    <Navbar color=\"dark\" dark expand=\"md\">\n      <NavbarBrand tag={Link} to=\"/\">Home</NavbarBrand>\n      <NavbarToggler onClick={() => { setIsOpen(!isOpen) }}/>\n      <Collapse isOpen={isOpen} navbar>\n        <Nav className=\"justify-content-end\" style={{width: \"100%\"}} navbar>\n          <NavItem>\n            <NavLink href=\"https://twitter.com/oktadev\">@oktadev</NavLink>\n          </NavItem>\n          <NavItem>\n            <NavLink href=\"https://github.com/oktadev/okta-spring-boot-react-crud-example\">GitHub</NavLink>\n          </NavItem>\n        </Nav>\n      </Collapse>\n    </Navbar>\n  );\n};\n\nexport default AppNavbar;\n----\n====\n\n. Create `Home.js` to serve as the landing page for your app. [`sbr-home`]\n+\n.`src/app/Home.js`\n[%collapsible]\n====\n[source,jsx]\n----\nimport React from 'react';\nimport './App.css';\nimport AppNavbar from './AppNavbar';\nimport { Link } from 'react-router-dom';\nimport { Button, Container } from 'reactstrap';\n\nconst Home = () => {\n  return (\n    <div>\n      <AppNavbar/>\n      <Container fluid>\n        <Button color=\"link\"><Link to=\"/groups\">Manage JUG Tour</Link></Button>\n      </Container>\n    </div>\n  );\n}\n\nexport default Home;\n----\n====\n\n. Also, change `App.js` to use React Router to navigate between components. [`sbr-app-router`]\n+\n.`src/app/App.js`\n[%collapsible]\n====\n[source,jsx]\n----\nimport React from 'react';\nimport './App.css';\nimport Home from './Home';\nimport { BrowserRouter as Router, Route, Routes } from 'react-router-dom';\nimport GroupList from './GroupList';\n\nconst App = () => {\n  return (\n    <Router>\n      <Routes>\n        <Route exact path=\"/\" element={<Home/>}/>\n        <Route path=\"/groups\" exact={true} element={<GroupList/>}/>\n      </Routes>\n    </Router>\n  )\n}\n\nexport default App;\n----\n====\n\n. To make your UI a bit more spacious, add a top margin to Bootstrap's container classes in `App.css`.\n+\n[source,css]\n----\nnav + .container, nav + .container-fluid {\n  margin-top: 20px;\n}\n----\n\n. Your React app should update itself as you make changes at `http://localhost:3000`.\n\n. Click on **Manage JUG Tour** and you should see a list of the default groups.\n\n== Add a React `GroupEdit` component\n\n. Create `GroupEdit.js` and use `useEffect()` to fetch the group resource with the ID from the URL. [`sbr-group-edit`]\n+\n.`app/src/GroupEdit.js`\n[%collapsible]\n====\n[source,jsx]\n----\nimport React, { useEffect, useState } from 'react';\nimport { Link, useNavigate, useParams } from 'react-router-dom';\nimport { Button, Container, Form, FormGroup, Input, Label } from 'reactstrap';\nimport AppNavbar from './AppNavbar';\n\nconst GroupEdit = () => {\n  const initialFormState = {\n    name: '',\n    address: '',\n    city: '',\n    stateOrProvince: '',\n    country: '',\n    postalCode: ''\n  };\n  const [group, setGroup] = useState(initialFormState);\n  const navigate = useNavigate();\n  const { id } = useParams();\n\n  useEffect(() => {\n    if (id !== 'new') {\n      fetch(`/api/group/${id}`)\n        .then(response => response.json())\n        .then(data => setGroup(data));\n    }\n  }, [id, setGroup]);\n\n  const handleChange = (event) => {\n    const { name, value } = event.target\n\n    setGroup({ ...group, [name]: value })\n  }\n\n  const handleSubmit = async (event) => {\n    event.preventDefault();\n\n    await fetch('/api/group' + (group.id ? '/' + group.id : ''), {\n      method: (group.id) ? 'PUT' : 'POST',\n      headers: {\n        'Accept': 'application/json',\n        'Content-Type': 'application/json'\n      },\n      body: JSON.stringify(group)\n    });\n    setGroup(initialFormState);\n    navigate('/groups');\n  }\n\n  const title = <h2>{group.id ? 'Edit Group' : 'Add Group'}</h2>;\n\n  return (<div>\n      <AppNavbar/>\n      <Container>\n        {title}\n        <Form onSubmit={handleSubmit}>\n          <FormGroup>\n            <Label for=\"name\">Name</Label>\n            <Input type=\"text\" name=\"name\" id=\"name\" value={group.name || ''}\n                   onChange={handleChange} autoComplete=\"name\"/>\n          </FormGroup>\n          <FormGroup>\n            <Label for=\"address\">Address</Label>\n            <Input type=\"text\" name=\"address\" id=\"address\" value={group.address || ''}\n                   onChange={handleChange} autoComplete=\"address-level1\"/>\n          </FormGroup>\n          <FormGroup>\n            <Label for=\"city\">City</Label>\n            <Input type=\"text\" name=\"city\" id=\"city\" value={group.city || ''}\n                   onChange={handleChange} autoComplete=\"address-level1\"/>\n          </FormGroup>\n          <div className=\"row\">\n            <FormGroup className=\"col-md-4 mb-3\">\n              <Label for=\"stateOrProvince\">State/Province</Label>\n              <Input type=\"text\" name=\"stateOrProvince\" id=\"stateOrProvince\" value={group.stateOrProvince || ''}\n                     onChange={handleChange} autoComplete=\"address-level1\"/>\n            </FormGroup>\n            <FormGroup className=\"col-md-5 mb-3\">\n              <Label for=\"country\">Country</Label>\n              <Input type=\"text\" name=\"country\" id=\"country\" value={group.country || ''}\n                     onChange={handleChange} autoComplete=\"address-level1\"/>\n            </FormGroup>\n            <FormGroup className=\"col-md-3 mb-3\">\n              <Label for=\"country\">Postal Code</Label>\n              <Input type=\"text\" name=\"postalCode\" id=\"postalCode\" value={group.postalCode || ''}\n                     onChange={handleChange} autoComplete=\"address-level1\"/>\n            </FormGroup>\n          </div>\n          <FormGroup>\n            <Button color=\"primary\" type=\"submit\">Save</Button>{' '}\n            <Button color=\"secondary\" tag={Link} to=\"/groups\">Cancel</Button>\n          </FormGroup>\n        </Form>\n      </Container>\n    </div>\n  )\n};\n\nexport default GroupEdit;\n----\n====\n\n. Modify `App.js` to import `GroupEdit` and specify a path to it.\n+\n[source,jsx]\n----\nimport GroupEdit from './GroupEdit';\n\nconst App = () => {\n  return (\n    <Router>\n      <Routes>\n        ...\n        <Route path=\"/groups/:id\" element={<GroupEdit/>}/>\n      </Routes>\n    </Router>\n  )\n}\n----\n\nNow you should be able to add and edit groups!\n\n== Add Authentication with Auth0\n\n. Add the necessary Spring Security dependencies to do OIDC authentication. [`sbr-spring-oauth`]\n+\n[source,xml]\n----\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-security</artifactId>\n</dependency>\n<dependency>\n    <groupId>org.springframework.security</groupId>\n    <artifactId>spring-security-config</artifactId>\n</dependency>\n<dependency>\n    <groupId>org.springframework.security</groupId>\n    <artifactId>spring-security-oauth2-client</artifactId>\n</dependency>\n<dependency>\n    <groupId>org.springframework.security</groupId>\n    <artifactId>spring-security-oauth2-jose</artifactId>\n</dependency>\n----\n+\nNOTE: We hope to make the Okta Spring Boot starter https://github.com/okta/okta-spring-boot/issues/358[work with Auth0] in the future.\n\n. Install the https://github.com/auth0/auth0-cli[Auth0 CLI] and run `auth0 login` in a terminal.\n\n. Run `auth0 apps create`, provide a memorable name, and select **Regular Web Application**. Specify `\\http://localhost:8080/login/oauth2/code/auth0` for the **Callback URLs** and `\\http://localhost:3000,http://localhost:8080` for the **Allowed Logout URLs**.\n\n. Modify your `src/main/resources/application.properties` to include your Auth0 issuer, client ID, and client secret. You will have to run `auth0 apps open` and select the app you created to copy your client secret. [`sbr-auth0`]\n+\n[source,properties]\n----\n# make sure to include the trailing slash for the Auth0 issuer\nspring.security.oauth2.client.provider.auth0.issuer-uri=https://<your-auth0-domain>/\nspring.security.oauth2.client.registration.auth0.client-id=<your-client-id>\nspring.security.oauth2.client.registration.auth0.client-secret=<your-client-secret>\nspring.security.oauth2.client.registration.auth0.scope=openid,profile,email\n----\n+\nOf course, you can also use your https://manage.auth0.com[Auth0 dashboard] to configure your application. Just make sure to use the same URLs specified above.\n\n== Add Authentication with Okta\n\n. Add the Okta Spring Boot starter to do OIDC authentication.\n+\n[source,xml]\n----\n<dependency>\n    <groupId>com.okta.spring</groupId>\n    <artifactId>okta-spring-boot-starter</artifactId>\n    <version>2.1.6</version>\n</dependency>\n----\n\n. Install the https://cli.okta.com/[Okta CLI] and run `okta login`. Then, run `okta apps create`. Select the default app name, or change it as you see fit. Choose **Web** and press **Enter**.\n+\nSelect **Okta Spring Boot Starter**. Accept the default Redirect URI and use `\\http://localhost:3000,http://localhost:8080` for the Logout Redirect URI.\n\n. After configuring Spring Security in the section below, update `UserController.java` to use `okta` in its constructor:\n+\n[source,java]\n----\npublic UserController(ClientRegistrationRepository registrations) {\n    this.registration = registrations.findByRegistrationId(\"okta\");\n}\n----\n\n. And update the `logout()` method to work with Okta:\n+\n[source,java]\n----\n@PostMapping(\"/api/logout\")\npublic ResponseEntity<?> logout(HttpServletRequest request,\n                                @AuthenticationPrincipal(expression = \"idToken\") OidcIdToken idToken) {\n    // send logout URL to client so they can initiate logout\n    String logoutUrl = this.registration.getProviderDetails()\n            .getConfigurationMetadata().get(\"end_session_endpoint\").toString();\n\n    Map<String, String> logoutDetails = new HashMap<>();\n    logoutDetails.put(\"logoutUrl\", logoutUrl);\n    logoutDetails.put(\"idToken\", idToken.getTokenValue());\n    request.getSession(false).invalidate();\n    return ResponseEntity.ok().body(logoutDetails);\n}\n----\n\n. Update `Home.js` in the React project to use different parameters for the logout redirect:\n+\n[source,js]\n----\nwindow.location.href = `${response.logoutUrl}?id_token_hint=${response.idToken}`\n  + `&post_logout_redirect_uri=${window.location.origin}`;\n----\n\nTIP: You can see all the differences between Okta and Auth0 by https://github.com/oktadev/okta-spring-boot-react-crud-example/compare/main\\...auth0[comparing their branches on GitHub].\n\n== Configure Spring Security for React and user identity\n\n. To make Spring Security React-friendly, create a `SecurityConfiguration.java` file in `src/main/java/.../jugtours/config`. [`sbr-security-config`]\n+\n====\n[source,java]\n----\npackage com.okta.developer.jugtours.config;\n\nimport com.okta.developer.jugtours.web.CookieCsrfFilter;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.web.SecurityFilterChain;\nimport org.springframework.security.web.authentication.www.BasicAuthenticationFilter;\nimport org.springframework.security.web.context.SecurityContextHolderFilter;\nimport org.springframework.security.web.csrf.CookieCsrfTokenRepository;\nimport org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler;\nimport org.springframework.security.web.savedrequest.HttpSessionRequestCache;\nimport org.springframework.security.web.savedrequest.RequestCache;\nimport org.springframework.security.web.savedrequest.SimpleSavedRequest;\n\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\n\nimport java.util.Enumeration;\n\nimport static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher;\n\n@Configuration\npublic class SecurityConfiguration {\n\n    @Bean\n    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {\n        http\n            .authorizeHttpRequests((authz) -> authz\n                .requestMatchers(\"/\", \"/index.html\", \"/static/**\",\n                    \"/*.ico\", \"/*.json\", \"/*.png\", \"/api/user\").permitAll() // <.>\n                .anyRequest().authenticated()\n            )\n            .csrf((csrf) -> csrf\n                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) // <.>\n                // https://stackoverflow.com/a/74521360/65681\n                .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler())\n            )\n            .addFilterAfter(new CookieCsrfFilter(), BasicAuthenticationFilter.class) // <.>\n            .oauth2Login();\n        return http.build();\n    }\n\n    @Bean\n    public RequestCache refererRequestCache() { // <.>\n        return new HttpSessionRequestCache() {\n            @Override\n            public void saveRequest(HttpServletRequest request, HttpServletResponse response) {\n                String referrer = request.getHeader(\"referer\"); // <.>\n                if (referrer == null) {\n                    referrer = request.getRequestURL().toString();\n                }\n                request.getSession().setAttribute(\"SPRING_SECURITY_SAVED_REQUEST\",\n                    new SimpleSavedRequest(referrer));\n\n            }\n        };\n    }\n}\n----\n. Define what URLs are allowed for anonymous users.\n. `CookieCsrfTokenRepository.withHttpOnlyFalse()` means that the `XSRF-TOKEN` cookie won't be marked HTTP-only, so React can read it and send it back when it tries to manipulate data.\n. Spring Security 6 no longer sets a CSRF cookie for you. Add a filter to do it.\n. The `RequestCache` bean overrides the default request cache.\n. It saves the referrer header (misspelled `referer` in real life), so Spring Security can redirect back to it after authentication.\n====\n\n. Create `src/main/java/.../jugtours/web/CookieCsrfFilter.java` to set a CSRF cookie. [`sbr-csrf`]\n+\n.`CookieCsrfFilter.java`\n[%collapsible]\n====\n[source,java]\n----\npackage com.okta.developer.jugtours.web;\n\nimport jakarta.servlet.FilterChain;\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\nimport org.springframework.security.web.csrf.CsrfToken;\nimport org.springframework.web.filter.OncePerRequestFilter;\n\nimport java.io.IOException;\n\n/**\n * Spring Security 6 doesn't set a XSRF-TOKEN cookie by default.\n * This solution is\n * <a href=\"https://github.com/spring-projects/spring-security/issues/12141#issuecomment-1321345077\">\n * recommended by Spring Security.</a>\n */\npublic class CookieCsrfFilter extends OncePerRequestFilter {\n\n    /**\n     * {@inheritDoc}\n     */\n    @Override\n    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,\n                                    FilterChain filterChain) throws ServletException, IOException {\n        CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());\n        response.setHeader(csrfToken.getHeaderName(), csrfToken.getToken());\n        filterChain.doFilter(request, response);\n    }\n}\n----\n====\n\n. Create `src/main/java/.../jugtours/web/UserController.java` and populate it with the following code. This API will be used by React to 1) find out if a user is authenticated, and 2) perform global logout. [`sbr-user-controller`]\n+\n.`UserController.java`\n[%collapsible]\n====\n[source,java]\n----\npackage com.okta.developer.jugtours.web;\n\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.core.annotation.AuthenticationPrincipal;\nimport org.springframework.security.oauth2.client.registration.ClientRegistration;\nimport org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;\nimport org.springframework.security.oauth2.core.user.OAuth2User;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport jakarta.servlet.http.HttpServletRequest;\nimport java.util.HashMap;\nimport java.util.Map;\n\n@RestController\npublic class UserController {\n    private ClientRegistration registration;\n\n    public UserController(ClientRegistrationRepository registrations) {\n        this.registration = registrations.findByRegistrationId(\"auth0\");\n    }\n\n    @GetMapping(\"/api/user\")\n    public ResponseEntity<?> getUser(@AuthenticationPrincipal OAuth2User user) {\n        if (user == null) {\n            return new ResponseEntity<>(\"\", HttpStatus.OK);\n        } else {\n            return ResponseEntity.ok().body(user.getAttributes());\n        }\n    }\n\n    @PostMapping(\"/api/logout\")\n    public ResponseEntity<?> logout(HttpServletRequest request) {\n        // send logout URL to client so they can initiate logout\n        StringBuilder logoutUrl = new StringBuilder();\n        String issuerUri = this.registration.getProviderDetails().getIssuerUri();\n        logoutUrl.append(issuerUri.endsWith(\"/\") ? issuerUri + \"v2/logout\" : issuerUri + \"/v2/logout\");\n        logoutUrl.append(\"?client_id=\").append(this.registration.getClientId());\n\n        Map<String, String> logoutDetails = new HashMap<>();\n        logoutDetails.put(\"logoutUrl\", logoutUrl.toString());\n        request.getSession(false).invalidate();\n        return ResponseEntity.ok().body(logoutDetails);\n    }\n}\n----\n====\n\n. You'll also want to add user information when creating groups so that you can filter by _your_ JUG tour. Add a `UserRepository.java` in the same directory as `GroupRepository.java`.\n+\n[source,java]\n----\npackage com.okta.developer.jugtours.model;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\n\npublic interface UserRepository extends JpaRepository<User, String> {\n}\n----\n\n. Add a new `findAllByUserId(String id)` method to `GroupRepository.java`.\n+\n[source,java]\n----\nList<Group> findAllByUserId(String id);\n----\n\n. Then inject `UserRepository` into `GroupController.java` and use it to create (or grab an existing user) when adding a new group. While you're there, modify the `groups()` method to filter by user.\n+\n[source,java]\n----\nimport org.springframework.security.core.annotation.AuthenticationPrincipal;\n...\n\n@GetMapping(\"/groups\")\nCollection<Group> groups(Principal principal) {\n    return groupRepository.findAllByUserId(principal.getName());\n}\n...\n\n@PostMapping(\"/group\")\nResponseEntity<Group> createGroup(@Valid @RequestBody Group group,\n                                  @AuthenticationPrincipal OAuth2User principal) throws URISyntaxException {\n    log.info(\"Request to create group: {}\", group);\n    Map<String, Object> details = principal.getAttributes();\n    String userId = details.get(\"sub\").toString();\n\n    // check to see if user already exists\n    Optional<User> user = userRepository.findById(userId);\n    group.setUser(user.orElse(new User(userId,\n                    details.get(\"name\").toString(), details.get(\"email\").toString())));\n\n    Group result = groupRepository.save(group);\n    return ResponseEntity.created(new URI(\"/api/group/\" + result.getId()))\n            .body(result);\n}\n----\n\n== Modify React to handle CSRF and be identity-aware\n\nYou'll need to make a few changes to your React components to make them identity-aware.\n\n. Modify `index.js` to wrap everything in a `CookieProvider`. This component allows you to read the CSRF cookie and send it back as a header.\n+\n[source,jsx]\n----\nimport { CookiesProvider } from 'react-cookie';\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(\n  <React.StrictMode>\n    <CookiesProvider>\n      <App />\n    </CookiesProvider>\n  </React.StrictMode>\n);\n----\n\n. Modify `Home.js` to call `/api/user` to see if the user is logged in. If they're not, show a `Login` button. [`sbr-home-auth`]\n+\n====\n[source,jsx]\n----\nimport React, { useEffect, useState } from 'react';\nimport './App.css';\nimport AppNavbar from './AppNavbar';\nimport { Link } from 'react-router-dom';\nimport { Button, Container } from 'reactstrap';\nimport { useCookies } from 'react-cookie';\n\nconst Home = () => {\n\n  const [authenticated, setAuthenticated] = useState(false);\n  const [loading, setLoading] = useState(false);\n  const [user, setUser] = useState(undefined);\n  const [cookies] = useCookies(['XSRF-TOKEN']); // <.>\n\n  useEffect(() => {\n    setLoading(true);\n    fetch('api/user', { credentials: 'include' }) // <.>\n      .then(response => response.text())\n      .then(body => {\n        if (body === '') {\n          setAuthenticated(false);\n        } else {\n          setUser(JSON.parse(body));\n          setAuthenticated(true);\n        }\n        setLoading(false);\n      });\n  }, [setAuthenticated, setLoading, setUser])\n\n  const login = () => {\n    let port = (window.location.port ? ':' + window.location.port : '');\n    if (port === ':3000') {\n      port = ':8080';\n    }\n    // redirect to a protected URL to trigger authentication\n    window.location.href = `//${window.location.hostname}${port}/api/private`;\n  }\n\n  const logout = () => {\n    fetch('/api/logout', {\n      method: 'POST', credentials: 'include',\n      headers: { 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'] } // <.>\n    })\n      .then(res => res.json())\n      .then(response => {\n        window.location.href = `${response.logoutUrl}&returnTo=${window.location.origin}`;\n      });\n  }\n\n  const message = user ?\n    <h2>Welcome, {user.name}!</h2> :\n    <p>Please log in to manage your JUG Tour.</p>;\n\n  const button = authenticated ?\n    <div>\n      <Button color=\"link\"><Link to=\"/groups\">Manage JUG Tour</Link></Button>\n      <br/>\n      <Button color=\"link\" onClick={logout}>Logout</Button>\n    </div> :\n    <Button color=\"primary\" onClick={login}>Login</Button>;\n\n  if (loading) {\n    return <p>Loading...</p>;\n  }\n\n  return (\n    <div>\n      <AppNavbar/>\n      <Container fluid>\n        {message}\n        {button}\n      </Container>\n    </div>\n  );\n}\n\nexport default Home;\n----\n. `useCookies()` is used for access to cookies. Then you can fetch a cookie with `cookies['XSRF-TOKEN']`.\n. When using `fetch()`, you need to include `{credentials: 'include'}` to transfer cookies. You will get a 403 Forbidden if you do not include this option.\n. The CSRF cookie from Spring Security has a different name than the header you need to send back. The cookie name is `XSRF-TOKEN`, while the header name is `X-XSRF-TOKEN`.\n====\n\n. Update `GroupList.js` to have similar changes.\n+\n[source,jsx]\n----\nimport { useCookies } from 'react-cookie';\n\nconst GroupList = () => {\n\n  ...\n  const [cookies] = useCookies(['XSRF-TOKEN']);\n\n  ...\n  const remove = async (id) => {\n    await fetch(`/api/group/${id}`, {\n      method: 'DELETE',\n      headers: {\n        'X-XSRF-TOKEN': cookies['XSRF-TOKEN'],\n        'Accept': 'application/json',\n        'Content-Type': 'application/json'\n      },\n      credentials: 'include'\n    }).then(() => {\n      let updatedGroups = [...groups].filter(i => i.id !== id);\n      setGroups(updatedGroups);\n    });\n  }\n  ...\n\n  return (...)\n}\n\nexport default GroupList;\n----\n\n. Update `GroupEdit.js` too.\n+\n[source,jsx]\n----\nimport { useCookies } from 'react-cookie';\n\nconst GroupEdit = () => {\n\n  ...\n  const [cookies] = useCookies(['XSRF-TOKEN']);\n\n  ...\n  const handleSubmit = async (event) => {\n    event.preventDefault();\n\n    await fetch(`/api/group${group.id ? `/${group.id}` : ''}`, {\n      method: group.id ? 'PUT' : 'POST',\n      headers: {\n        'X-XSRF-TOKEN': cookies['XSRF-TOKEN'],\n        'Accept': 'application/json',\n        'Content-Type': 'application/json'\n      },\n      body: JSON.stringify(group),\n      credentials: 'include'\n    });\n    setGroup(initialFormState);\n    navigate('/groups');\n  }\n\n  ...\n\n  return (...)\n}\n\nexport default GroupEdit;\n----\n\nAfter all these changes, you should be able to restart both Spring Boot and React and witness the glory of planning your very own JUG Tour!\n\n== Configure Maven to build and package React with Spring Boot\n\nTo build and package your React app with Maven, you can use the https://github.com/eirslett/frontend-maven-plugin[frontend-maven-plugin] and Maven's profiles to activate it.\n\n. Add properties for versions and a `<profiles>` section to your `pom.xml`. [`sbr-properties` and `sbr-profiles`]\n+\n.`pom.xml`\n[%collapsible]\n====\n[source,xml]\n----\n<properties>\n    ...\n    <frontend-maven-plugin.version>1.12.1</frontend-maven-plugin.version>\n    <node.version>v16.18.1</node.version>\n    <npm.version>v8.19.2</npm.version>\n</properties>\n\n<profiles>\n    <profile>\n        <id>dev</id>\n        <activation>\n            <activeByDefault>true</activeByDefault>\n        </activation>\n        <properties>\n            <spring.profiles.active>dev</spring.profiles.active>\n        </properties>\n    </profile>\n    <profile>\n        <id>prod</id>\n        <build>\n            <plugins>\n                <plugin>\n                    <artifactId>maven-resources-plugin</artifactId>\n                    <executions>\n                        <execution>\n                            <id>copy-resources</id>\n                            <phase>process-classes</phase>\n                            <goals>\n                                <goal>copy-resources</goal>\n                            </goals>\n                            <configuration>\n                                <outputDirectory>${basedir}/target/classes/static</outputDirectory>\n                                <resources>\n                                    <resource>\n                                        <directory>app/build</directory>\n                                    </resource>\n                                </resources>\n                            </configuration>\n                        </execution>\n                    </executions>\n                </plugin>\n                <plugin>\n                    <groupId>com.github.eirslett</groupId>\n                    <artifactId>frontend-maven-plugin</artifactId>\n                    <version>${frontend-maven-plugin.version}</version>\n                    <configuration>\n                        <workingDirectory>app</workingDirectory>\n                    </configuration>\n                    <executions>\n                        <execution>\n                            <id>install node</id>\n                            <goals>\n                                <goal>install-node-and-npm</goal>\n                            </goals>\n                            <configuration>\n                                <nodeVersion>${node.version}</nodeVersion>\n                                <npmVersion>${npm.version}</npmVersion>\n                            </configuration>\n                        </execution>\n                        <execution>\n                            <id>npm install</id>\n                            <goals>\n                                <goal>npm</goal>\n                            </goals>\n                            <phase>generate-resources</phase>\n                        </execution>\n                        <execution>\n                            <id>npm test</id>\n                            <goals>\n                                <goal>test</goal>\n                            </goals>\n                            <phase>test</phase>\n                            <configuration>\n                                <arguments>test</arguments>\n                                <environmentVariables>\n                                    <CI>true</CI>\n                                </environmentVariables>\n                            </configuration>\n                        </execution>\n                        <execution>\n                            <id>npm build</id>\n                            <goals>\n                                <goal>npm</goal>\n                            </goals>\n                            <phase>compile</phase>\n                            <configuration>\n                                <arguments>run build</arguments>\n                            </configuration>\n                        </execution>\n                    </executions>\n                </plugin>\n            </plugins>\n        </build>\n        <properties>\n            <spring.profiles.active>prod</spring.profiles.active>\n        </properties>\n    </profile>\n</profiles>\n----\n====\n+\nAdd the active profile setting to `src/main/resources/application.properties`:\n+\n[source,properties]\n----\nspring.profiles.active=@spring.profiles.active@\n----\n\n. After adding this, you should be able to run `./mvnw spring-boot:run -Pprod` and see your app running on `http://localhost:8080`.\n\n. Everything will work just fine if you start at the root, since React will handle routing. However, if you refresh the page when you're at `http://localhost:8080/groups`, you'll get a 404 error since Spring Boot doesn't have a route for `/groups`. To fix this, add a `SpaWebFilter` that conditionally forwards to the React app. [`sbr-spa`]\n+\n.`SpaWebFilter.java`\n[%collapsible]\n====\n[source,java]\n----\npackage com.okta.developer.jugtours.web;\n\nimport jakarta.servlet.FilterChain;\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.oauth2.core.user.OAuth2User;\nimport org.springframework.web.filter.OncePerRequestFilter;\n\nimport java.io.IOException;\nimport java.security.Principal;\n\npublic class SpaWebFilter extends OncePerRequestFilter {\n\n    @Override\n    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,\n                                    FilterChain filterChain) throws ServletException, IOException {\n        String path = request.getRequestURI();\n        Authentication user = SecurityContextHolder.getContext().getAuthentication();\n        if (user != null && !path.startsWith(\"/api\") &&\n            !path.contains(\".\") && path.matches(\"/(.*)\")) {\n            request.getRequestDispatcher(\"/\").forward(request, response);\n            return;\n        }\n\n        filterChain.doFilter(request, response);\n    }\n}\n----\n====\n\n. And add it to `SecurityConfiguration.java`:\n+\n[source,java]\n----\n.addFilterAfter(new SpaWebFilter(), BasicAuthenticationFilter.class)\n----\n\n. Now, if you restart and reload the page, everything will work as expected. 🤗\n\n== Giddyup with React and Spring Boot!\n\nI hope you enjoyed this screencast, and it helped you understand how to integrate React and Spring Boot securely.\n\n⚛️ Find the code on GitHub: https://github.com/oktadev/okta-spring-boot-react-crud-example[@oktadev/okta-spring-boot-react-crud-example]\n\n🍃 Read the blog post: https://developer.okta.com/blog/2022/06/17/simple-crud-react-and-spring-boot[Use React and Spring Boot to Build a Simple CRUD App]\n"
  },
  {
    "path": "mvnw",
    "content": "#!/bin/sh\n# ----------------------------------------------------------------------------\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#    https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# ----------------------------------------------------------------------------\n\n# ----------------------------------------------------------------------------\n# Maven Start Up Batch script\n#\n# Required ENV vars:\n# ------------------\n#   JAVA_HOME - location of a JDK home dir\n#\n# Optional ENV vars\n# -----------------\n#   M2_HOME - location of maven2's installed home dir\n#   MAVEN_OPTS - parameters passed to the Java VM when running Maven\n#     e.g. to debug Maven itself, use\n#       set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000\n#   MAVEN_SKIP_RC - flag to disable loading of mavenrc files\n# ----------------------------------------------------------------------------\n\nif [ -z \"$MAVEN_SKIP_RC\" ] ; then\n\n  if [ -f /usr/local/etc/mavenrc ] ; then\n    . /usr/local/etc/mavenrc\n  fi\n\n  if [ -f /etc/mavenrc ] ; then\n    . /etc/mavenrc\n  fi\n\n  if [ -f \"$HOME/.mavenrc\" ] ; then\n    . \"$HOME/.mavenrc\"\n  fi\n\nfi\n\n# OS specific support.  $var _must_ be set to either true or false.\ncygwin=false;\ndarwin=false;\nmingw=false\ncase \"`uname`\" in\n  CYGWIN*) cygwin=true ;;\n  MINGW*) mingw=true;;\n  Darwin*) darwin=true\n    # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home\n    # See https://developer.apple.com/library/mac/qa/qa1170/_index.html\n    if [ -z \"$JAVA_HOME\" ]; then\n      if [ -x \"/usr/libexec/java_home\" ]; then\n        export JAVA_HOME=\"`/usr/libexec/java_home`\"\n      else\n        export JAVA_HOME=\"/Library/Java/Home\"\n      fi\n    fi\n    ;;\nesac\n\nif [ -z \"$JAVA_HOME\" ] ; then\n  if [ -r /etc/gentoo-release ] ; then\n    JAVA_HOME=`java-config --jre-home`\n  fi\nfi\n\nif [ -z \"$M2_HOME\" ] ; then\n  ## resolve links - $0 may be a link to maven's home\n  PRG=\"$0\"\n\n  # need this for relative symlinks\n  while [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n      PRG=\"$link\"\n    else\n      PRG=\"`dirname \"$PRG\"`/$link\"\n    fi\n  done\n\n  saveddir=`pwd`\n\n  M2_HOME=`dirname \"$PRG\"`/..\n\n  # make it fully qualified\n  M2_HOME=`cd \"$M2_HOME\" && pwd`\n\n  cd \"$saveddir\"\n  # echo Using m2 at $M2_HOME\nfi\n\n# For Cygwin, ensure paths are in UNIX format before anything is touched\nif $cygwin ; then\n  [ -n \"$M2_HOME\" ] &&\n    M2_HOME=`cygpath --unix \"$M2_HOME\"`\n  [ -n \"$JAVA_HOME\" ] &&\n    JAVA_HOME=`cygpath --unix \"$JAVA_HOME\"`\n  [ -n \"$CLASSPATH\" ] &&\n    CLASSPATH=`cygpath --path --unix \"$CLASSPATH\"`\nfi\n\n# For Mingw, ensure paths are in UNIX format before anything is touched\nif $mingw ; then\n  [ -n \"$M2_HOME\" ] &&\n    M2_HOME=\"`(cd \"$M2_HOME\"; pwd)`\"\n  [ -n \"$JAVA_HOME\" ] &&\n    JAVA_HOME=\"`(cd \"$JAVA_HOME\"; pwd)`\"\nfi\n\nif [ -z \"$JAVA_HOME\" ]; then\n  javaExecutable=\"`which javac`\"\n  if [ -n \"$javaExecutable\" ] && ! [ \"`expr \\\"$javaExecutable\\\" : '\\([^ ]*\\)'`\" = \"no\" ]; then\n    # readlink(1) is not available as standard on Solaris 10.\n    readLink=`which readlink`\n    if [ ! `expr \"$readLink\" : '\\([^ ]*\\)'` = \"no\" ]; then\n      if $darwin ; then\n        javaHome=\"`dirname \\\"$javaExecutable\\\"`\"\n        javaExecutable=\"`cd \\\"$javaHome\\\" && pwd -P`/javac\"\n      else\n        javaExecutable=\"`readlink -f \\\"$javaExecutable\\\"`\"\n      fi\n      javaHome=\"`dirname \\\"$javaExecutable\\\"`\"\n      javaHome=`expr \"$javaHome\" : '\\(.*\\)/bin'`\n      JAVA_HOME=\"$javaHome\"\n      export JAVA_HOME\n    fi\n  fi\nfi\n\nif [ -z \"$JAVACMD\" ] ; then\n  if [ -n \"$JAVA_HOME\"  ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n      # IBM's JDK on AIX uses strange locations for the executables\n      JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n      JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n  else\n    JAVACMD=\"`\\\\unset -f command; \\\\command -v java`\"\n  fi\nfi\n\nif [ ! -x \"$JAVACMD\" ] ; then\n  echo \"Error: JAVA_HOME is not defined correctly.\" >&2\n  echo \"  We cannot execute $JAVACMD\" >&2\n  exit 1\nfi\n\nif [ -z \"$JAVA_HOME\" ] ; then\n  echo \"Warning: JAVA_HOME environment variable is not set.\"\nfi\n\nCLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher\n\n# traverses directory structure from process work directory to filesystem root\n# first directory with .mvn subdirectory is considered project base directory\nfind_maven_basedir() {\n\n  if [ -z \"$1\" ]\n  then\n    echo \"Path not specified to find_maven_basedir\"\n    return 1\n  fi\n\n  basedir=\"$1\"\n  wdir=\"$1\"\n  while [ \"$wdir\" != '/' ] ; do\n    if [ -d \"$wdir\"/.mvn ] ; then\n      basedir=$wdir\n      break\n    fi\n    # workaround for JBEAP-8937 (on Solaris 10/Sparc)\n    if [ -d \"${wdir}\" ]; then\n      wdir=`cd \"$wdir/..\"; pwd`\n    fi\n    # end of workaround\n  done\n  echo \"${basedir}\"\n}\n\n# concatenates all lines of a file\nconcat_lines() {\n  if [ -f \"$1\" ]; then\n    echo \"$(tr -s '\\n' ' ' < \"$1\")\"\n  fi\n}\n\nBASE_DIR=`find_maven_basedir \"$(pwd)\"`\nif [ -z \"$BASE_DIR\" ]; then\n  exit 1;\nfi\n\n##########################################################################################\n# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central\n# This allows using the maven wrapper in projects that prohibit checking in binary data.\n##########################################################################################\nif [ -r \"$BASE_DIR/.mvn/wrapper/maven-wrapper.jar\" ]; then\n    if [ \"$MVNW_VERBOSE\" = true ]; then\n      echo \"Found .mvn/wrapper/maven-wrapper.jar\"\n    fi\nelse\n    if [ \"$MVNW_VERBOSE\" = true ]; then\n      echo \"Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ...\"\n    fi\n    if [ -n \"$MVNW_REPOURL\" ]; then\n      jarUrl=\"$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar\"\n    else\n      jarUrl=\"https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar\"\n    fi\n    while IFS=\"=\" read key value; do\n      case \"$key\" in (wrapperUrl) jarUrl=\"$value\"; break ;;\n      esac\n    done < \"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties\"\n    if [ \"$MVNW_VERBOSE\" = true ]; then\n      echo \"Downloading from: $jarUrl\"\n    fi\n    wrapperJarPath=\"$BASE_DIR/.mvn/wrapper/maven-wrapper.jar\"\n    if $cygwin; then\n      wrapperJarPath=`cygpath --path --windows \"$wrapperJarPath\"`\n    fi\n\n    if command -v wget > /dev/null; then\n        if [ \"$MVNW_VERBOSE\" = true ]; then\n          echo \"Found wget ... using wget\"\n        fi\n        if [ -z \"$MVNW_USERNAME\" ] || [ -z \"$MVNW_PASSWORD\" ]; then\n            wget \"$jarUrl\" -O \"$wrapperJarPath\" || rm -f \"$wrapperJarPath\"\n        else\n            wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD \"$jarUrl\" -O \"$wrapperJarPath\" || rm -f \"$wrapperJarPath\"\n        fi\n    elif command -v curl > /dev/null; then\n        if [ \"$MVNW_VERBOSE\" = true ]; then\n          echo \"Found curl ... using curl\"\n        fi\n        if [ -z \"$MVNW_USERNAME\" ] || [ -z \"$MVNW_PASSWORD\" ]; then\n            curl -o \"$wrapperJarPath\" \"$jarUrl\" -f\n        else\n            curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o \"$wrapperJarPath\" \"$jarUrl\" -f\n        fi\n\n    else\n        if [ \"$MVNW_VERBOSE\" = true ]; then\n          echo \"Falling back to using Java to download\"\n        fi\n        javaClass=\"$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java\"\n        # For Cygwin, switch paths to Windows format before running javac\n        if $cygwin; then\n          javaClass=`cygpath --path --windows \"$javaClass\"`\n        fi\n        if [ -e \"$javaClass\" ]; then\n            if [ ! -e \"$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class\" ]; then\n                if [ \"$MVNW_VERBOSE\" = true ]; then\n                  echo \" - Compiling MavenWrapperDownloader.java ...\"\n                fi\n                # Compiling the Java class\n                (\"$JAVA_HOME/bin/javac\" \"$javaClass\")\n            fi\n            if [ -e \"$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class\" ]; then\n                # Running the downloader\n                if [ \"$MVNW_VERBOSE\" = true ]; then\n                  echo \" - Running MavenWrapperDownloader.java ...\"\n                fi\n                (\"$JAVA_HOME/bin/java\" -cp .mvn/wrapper MavenWrapperDownloader \"$MAVEN_PROJECTBASEDIR\")\n            fi\n        fi\n    fi\nfi\n##########################################################################################\n# End of extension\n##########################################################################################\n\nexport MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-\"$BASE_DIR\"}\nif [ \"$MVNW_VERBOSE\" = true ]; then\n  echo $MAVEN_PROJECTBASEDIR\nfi\nMAVEN_OPTS=\"$(concat_lines \"$MAVEN_PROJECTBASEDIR/.mvn/jvm.config\") $MAVEN_OPTS\"\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin; then\n  [ -n \"$M2_HOME\" ] &&\n    M2_HOME=`cygpath --path --windows \"$M2_HOME\"`\n  [ -n \"$JAVA_HOME\" ] &&\n    JAVA_HOME=`cygpath --path --windows \"$JAVA_HOME\"`\n  [ -n \"$CLASSPATH\" ] &&\n    CLASSPATH=`cygpath --path --windows \"$CLASSPATH\"`\n  [ -n \"$MAVEN_PROJECTBASEDIR\" ] &&\n    MAVEN_PROJECTBASEDIR=`cygpath --path --windows \"$MAVEN_PROJECTBASEDIR\"`\nfi\n\n# Provide a \"standardized\" way to retrieve the CLI args that will\n# work with both Windows and non-Windows executions.\nMAVEN_CMD_LINE_ARGS=\"$MAVEN_CONFIG $@\"\nexport MAVEN_CMD_LINE_ARGS\n\nWRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain\n\nexec \"$JAVACMD\" \\\n  $MAVEN_OPTS \\\n  $MAVEN_DEBUG_OPTS \\\n  -classpath \"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar\" \\\n  \"-Dmaven.home=${M2_HOME}\" \\\n  \"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}\" \\\n  ${WRAPPER_LAUNCHER} $MAVEN_CONFIG \"$@\"\n"
  },
  {
    "path": "mvnw.cmd",
    "content": "@REM ----------------------------------------------------------------------------\n@REM Licensed to the Apache Software Foundation (ASF) under one\n@REM or more contributor license agreements.  See the NOTICE file\n@REM distributed with this work for additional information\n@REM regarding copyright ownership.  The ASF licenses this file\n@REM to you under the Apache License, Version 2.0 (the\n@REM \"License\"); you may not use this file except in compliance\n@REM with the License.  You may obtain a copy of the License at\n@REM\n@REM    https://www.apache.org/licenses/LICENSE-2.0\n@REM\n@REM Unless required by applicable law or agreed to in writing,\n@REM software distributed under the License is distributed on an\n@REM \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n@REM KIND, either express or implied.  See the License for the\n@REM specific language governing permissions and limitations\n@REM under the License.\n@REM ----------------------------------------------------------------------------\n\n@REM ----------------------------------------------------------------------------\n@REM Maven Start Up Batch script\n@REM\n@REM Required ENV vars:\n@REM JAVA_HOME - location of a JDK home dir\n@REM\n@REM Optional ENV vars\n@REM M2_HOME - location of maven2's installed home dir\n@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands\n@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending\n@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven\n@REM     e.g. to debug Maven itself, use\n@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000\n@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files\n@REM ----------------------------------------------------------------------------\n\n@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'\n@echo off\n@REM set title of command window\ntitle %0\n@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'\n@if \"%MAVEN_BATCH_ECHO%\" == \"on\"  echo %MAVEN_BATCH_ECHO%\n\n@REM set %HOME% to equivalent of $HOME\nif \"%HOME%\" == \"\" (set \"HOME=%HOMEDRIVE%%HOMEPATH%\")\n\n@REM Execute a user defined script before this one\nif not \"%MAVEN_SKIP_RC%\" == \"\" goto skipRcPre\n@REM check for pre script, once with legacy .bat ending and once with .cmd ending\nif exist \"%USERPROFILE%\\mavenrc_pre.bat\" call \"%USERPROFILE%\\mavenrc_pre.bat\" %*\nif exist \"%USERPROFILE%\\mavenrc_pre.cmd\" call \"%USERPROFILE%\\mavenrc_pre.cmd\" %*\n:skipRcPre\n\n@setlocal\n\nset ERROR_CODE=0\n\n@REM To isolate internal variables from possible post scripts, we use another setlocal\n@setlocal\n\n@REM ==== START VALIDATION ====\nif not \"%JAVA_HOME%\" == \"\" goto OkJHome\n\necho.\necho Error: JAVA_HOME not found in your environment. >&2\necho Please set the JAVA_HOME variable in your environment to match the >&2\necho location of your Java installation. >&2\necho.\ngoto error\n\n:OkJHome\nif exist \"%JAVA_HOME%\\bin\\java.exe\" goto init\n\necho.\necho Error: JAVA_HOME is set to an invalid directory. >&2\necho JAVA_HOME = \"%JAVA_HOME%\" >&2\necho Please set the JAVA_HOME variable in your environment to match the >&2\necho location of your Java installation. >&2\necho.\ngoto error\n\n@REM ==== END VALIDATION ====\n\n:init\n\n@REM Find the project base dir, i.e. the directory that contains the folder \".mvn\".\n@REM Fallback to current working directory if not found.\n\nset MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%\nIF NOT \"%MAVEN_PROJECTBASEDIR%\"==\"\" goto endDetectBaseDir\n\nset EXEC_DIR=%CD%\nset WDIR=%EXEC_DIR%\n:findBaseDir\nIF EXIST \"%WDIR%\"\\.mvn goto baseDirFound\ncd ..\nIF \"%WDIR%\"==\"%CD%\" goto baseDirNotFound\nset WDIR=%CD%\ngoto findBaseDir\n\n:baseDirFound\nset MAVEN_PROJECTBASEDIR=%WDIR%\ncd \"%EXEC_DIR%\"\ngoto endDetectBaseDir\n\n:baseDirNotFound\nset MAVEN_PROJECTBASEDIR=%EXEC_DIR%\ncd \"%EXEC_DIR%\"\n\n:endDetectBaseDir\n\nIF NOT EXIST \"%MAVEN_PROJECTBASEDIR%\\.mvn\\jvm.config\" goto endReadAdditionalConfig\n\n@setlocal EnableExtensions EnableDelayedExpansion\nfor /F \"usebackq delims=\" %%a in (\"%MAVEN_PROJECTBASEDIR%\\.mvn\\jvm.config\") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a\n@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%\n\n:endReadAdditionalConfig\n\nSET MAVEN_JAVA_EXE=\"%JAVA_HOME%\\bin\\java.exe\"\nset WRAPPER_JAR=\"%MAVEN_PROJECTBASEDIR%\\.mvn\\wrapper\\maven-wrapper.jar\"\nset WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain\n\nset DOWNLOAD_URL=\"https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar\"\n\nFOR /F \"usebackq tokens=1,2 delims==\" %%A IN (\"%MAVEN_PROJECTBASEDIR%\\.mvn\\wrapper\\maven-wrapper.properties\") DO (\n    IF \"%%A\"==\"wrapperUrl\" SET DOWNLOAD_URL=%%B\n)\n\n@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central\n@REM This allows using the maven wrapper in projects that prohibit checking in binary data.\nif exist %WRAPPER_JAR% (\n    if \"%MVNW_VERBOSE%\" == \"true\" (\n        echo Found %WRAPPER_JAR%\n    )\n) else (\n    if not \"%MVNW_REPOURL%\" == \"\" (\n        SET DOWNLOAD_URL=\"%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar\"\n    )\n    if \"%MVNW_VERBOSE%\" == \"true\" (\n        echo Couldn't find %WRAPPER_JAR%, downloading it ...\n        echo Downloading from: %DOWNLOAD_URL%\n    )\n\n    powershell -Command \"&{\"^\n\t\t\"$webclient = new-object System.Net.WebClient;\"^\n\t\t\"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {\"^\n\t\t\"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');\"^\n\t\t\"}\"^\n\t\t\"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')\"^\n\t\t\"}\"\n    if \"%MVNW_VERBOSE%\" == \"true\" (\n        echo Finished downloading %WRAPPER_JAR%\n    )\n)\n@REM End of extension\n\n@REM Provide a \"standardized\" way to retrieve the CLI args that will\n@REM work with both Windows and non-Windows executions.\nset MAVEN_CMD_LINE_ARGS=%*\n\n%MAVEN_JAVA_EXE% ^\n  %JVM_CONFIG_MAVEN_PROPS% ^\n  %MAVEN_OPTS% ^\n  %MAVEN_DEBUG_OPTS% ^\n  -classpath %WRAPPER_JAR% ^\n  \"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%\" ^\n  %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*\nif ERRORLEVEL 1 goto error\ngoto end\n\n:error\nset ERROR_CODE=1\n\n:end\n@endlocal & set ERROR_CODE=%ERROR_CODE%\n\nif not \"%MAVEN_SKIP_RC%\"==\"\" goto skipRcPost\n@REM check for post script, once with legacy .bat ending and once with .cmd ending\nif exist \"%USERPROFILE%\\mavenrc_post.bat\" call \"%USERPROFILE%\\mavenrc_post.bat\"\nif exist \"%USERPROFILE%\\mavenrc_post.cmd\" call \"%USERPROFILE%\\mavenrc_post.cmd\"\n:skipRcPost\n\n@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'\nif \"%MAVEN_BATCH_PAUSE%\"==\"on\" pause\n\nif \"%MAVEN_TERMINATE_CMD%\"==\"on\" exit %ERROR_CODE%\n\ncmd /C exit /B %ERROR_CODE%\n"
  },
  {
    "path": "pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n    <parent>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-starter-parent</artifactId>\n        <version>3.0.6</version>\n        <relativePath/> <!-- lookup parent from repository -->\n    </parent>\n    <groupId>com.okta.developer</groupId>\n    <artifactId>jugtours</artifactId>\n    <version>0.0.1-SNAPSHOT</version>\n    <name>jugtours</name>\n    <description>Demo project for Spring Boot</description>\n    <properties>\n        <java.version>17</java.version>\n        <frontend-maven-plugin.version>1.12.1</frontend-maven-plugin.version>\n        <node.version>v18.16.0</node.version>\n        <npm.version>9.6.5</npm.version>\n    </properties>\n    <dependencies>\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-data-jpa</artifactId>\n        </dependency>\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-web</artifactId>\n        </dependency>\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-validation</artifactId>\n        </dependency>\n        <dependency>\n            <groupId>com.okta.spring</groupId>\n            <artifactId>okta-spring-boot-starter</artifactId>\n            <version>3.0.3</version>\n        </dependency>\n        <dependency>\n            <groupId>com.h2database</groupId>\n            <artifactId>h2</artifactId>\n            <scope>runtime</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.projectlombok</groupId>\n            <artifactId>lombok</artifactId>\n            <optional>true</optional>\n        </dependency>\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-test</artifactId>\n            <scope>test</scope>\n        </dependency>\n    </dependencies>\n\n    <build>\n        <defaultGoal>spring-boot:run</defaultGoal>\n        <plugins>\n            <plugin>\n                <groupId>org.springframework.boot</groupId>\n                <artifactId>spring-boot-maven-plugin</artifactId>\n                <configuration>\n                    <excludes>\n                        <exclude>\n                            <groupId>org.projectlombok</groupId>\n                            <artifactId>lombok</artifactId>\n                        </exclude>\n                    </excludes>\n                </configuration>\n            </plugin>\n        </plugins>\n    </build>\n\n    <profiles>\n        <profile>\n            <id>dev</id>\n            <activation>\n                <activeByDefault>true</activeByDefault>\n            </activation>\n            <properties>\n                <spring.profiles.active>dev</spring.profiles.active>\n            </properties>\n        </profile>\n        <profile>\n            <id>prod</id>\n            <build>\n                <plugins>\n                    <plugin>\n                        <artifactId>maven-resources-plugin</artifactId>\n                        <executions>\n                            <execution>\n                                <id>copy-resources</id>\n                                <phase>process-classes</phase>\n                                <goals>\n                                    <goal>copy-resources</goal>\n                                </goals>\n                                <configuration>\n                                    <outputDirectory>${basedir}/target/classes/static</outputDirectory>\n                                    <resources>\n                                        <resource>\n                                            <directory>app/build</directory>\n                                        </resource>\n                                    </resources>\n                                </configuration>\n                            </execution>\n                        </executions>\n                    </plugin>\n                    <plugin>\n                        <groupId>com.github.eirslett</groupId>\n                        <artifactId>frontend-maven-plugin</artifactId>\n                        <version>${frontend-maven-plugin.version}</version>\n                        <configuration>\n                            <workingDirectory>app</workingDirectory>\n                        </configuration>\n                        <executions>\n                            <execution>\n                                <id>install node</id>\n                                <goals>\n                                    <goal>install-node-and-npm</goal>\n                                </goals>\n                                <configuration>\n                                    <nodeVersion>${node.version}</nodeVersion>\n                                    <npmVersion>${npm.version}</npmVersion>\n                                </configuration>\n                            </execution>\n                            <execution>\n                                <id>npm install</id>\n                                <goals>\n                                    <goal>npm</goal>\n                                </goals>\n                                <phase>generate-resources</phase>\n                            </execution>\n                            <execution>\n                                <id>npm test</id>\n                                <goals>\n                                    <goal>npm</goal>\n                                </goals>\n                                <phase>test</phase>\n                                <configuration>\n                                    <arguments>test</arguments>\n                                    <environmentVariables>\n                                        <CI>true</CI>\n                                    </environmentVariables>\n                                </configuration>\n                            </execution>\n                            <execution>\n                                <id>npm build</id>\n                                <goals>\n                                    <goal>npm</goal>\n                                </goals>\n                                <phase>compile</phase>\n                                <configuration>\n                                    <arguments>run build</arguments>\n                                </configuration>\n                            </execution>\n                        </executions>\n                    </plugin>\n                </plugins>\n            </build>\n            <properties>\n                <spring.profiles.active>prod</spring.profiles.active>\n            </properties>\n        </profile>\n    </profiles>\n</project>\n"
  },
  {
    "path": "src/main/java/com/okta/developer/jugtours/Initializer.java",
    "content": "package com.okta.developer.jugtours;\n\nimport com.okta.developer.jugtours.model.Event;\nimport com.okta.developer.jugtours.model.Group;\nimport com.okta.developer.jugtours.model.GroupRepository;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.stereotype.Component;\n\nimport java.time.Instant;\nimport java.util.Collections;\nimport java.util.stream.Stream;\n\n@Component\nclass Initializer implements CommandLineRunner {\n\n    private final GroupRepository repository;\n\n    public Initializer(GroupRepository repository) {\n        this.repository = repository;\n    }\n\n    @Override\n    public void run(String... strings) {\n        Stream.of(\"Seattle JUG\", \"Denver JUG\", \"Dublin JUG\",\n            \"London JUG\").forEach(name ->\n            repository.save(new Group(name))\n        );\n\n        Group djug = repository.findByName(\"Seattle JUG\");\n        Event e = Event.builder().title(\"Micro Frontends for Java Developers\")\n            .description(\"JHipster now has microfrontend support!\")\n            .date(Instant.parse(\"2022-09-13T17:00:00.000Z\"))\n            .build();\n        djug.setEvents(Collections.singleton(e));\n        repository.save(djug);\n\n        repository.findAll().forEach(System.out::println);\n    }\n}\n"
  },
  {
    "path": "src/main/java/com/okta/developer/jugtours/JugtoursApplication.java",
    "content": "package com.okta.developer.jugtours;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class JugtoursApplication {\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(JugtoursApplication.class, args);\n\t}\n\n}\n"
  },
  {
    "path": "src/main/java/com/okta/developer/jugtours/config/SecurityConfiguration.java",
    "content": "package com.okta.developer.jugtours.config;\n\nimport com.okta.developer.jugtours.web.CookieCsrfFilter;\nimport com.okta.developer.jugtours.web.SpaWebFilter;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.web.SecurityFilterChain;\nimport org.springframework.security.web.authentication.www.BasicAuthenticationFilter;\nimport org.springframework.security.web.csrf.CookieCsrfTokenRepository;\nimport org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler;\nimport org.springframework.security.web.savedrequest.HttpSessionRequestCache;\nimport org.springframework.security.web.savedrequest.RequestCache;\nimport org.springframework.security.web.savedrequest.SimpleSavedRequest;\n\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\n\n@Configuration\npublic class SecurityConfiguration {\n\n    @Bean\n    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {\n        http\n            .authorizeHttpRequests((authz) -> authz\n                .requestMatchers(\"/\", \"/index.html\", \"/static/**\",\n                    \"/*.ico\", \"/*.json\", \"/*.png\", \"/api/user\").permitAll()\n                .anyRequest().authenticated()\n            )\n            .csrf((csrf) -> csrf\n                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())\n                // https://stackoverflow.com/a/74521360/65681\n                .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler())\n            )\n            .addFilterAfter(new CookieCsrfFilter(), BasicAuthenticationFilter.class)\n            .addFilterAfter(new SpaWebFilter(), BasicAuthenticationFilter.class)\n            .oauth2Login();\n        return http.build();\n    }\n\n    @Bean\n    public RequestCache refererRequestCache() {\n        return new HttpSessionRequestCache() {\n            @Override\n            public void saveRequest(HttpServletRequest request, HttpServletResponse response) {\n                String referrer = request.getHeader(\"referer\");\n                if (referrer == null) {\n                    referrer = request.getRequestURL().toString();\n                }\n                request.getSession().setAttribute(\"SPRING_SECURITY_SAVED_REQUEST\",\n                    new SimpleSavedRequest(referrer));\n\n            }\n        };\n    }\n}\n"
  },
  {
    "path": "src/main/java/com/okta/developer/jugtours/model/Event.java",
    "content": "package com.okta.developer.jugtours.model;\n\nimport lombok.AllArgsConstructor;\nimport lombok.Builder;\nimport lombok.Data;\nimport lombok.NoArgsConstructor;\n\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.GeneratedValue;\nimport jakarta.persistence.Id;\nimport jakarta.persistence.ManyToMany;\n\nimport java.time.Instant;\nimport java.util.Set;\n\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Entity\npublic class Event {\n\n    @Id\n    @GeneratedValue\n    private Long id;\n    private Instant date;\n    private String title;\n    private String description;\n    @ManyToMany\n    private Set<User> attendees;\n}\n"
  },
  {
    "path": "src/main/java/com/okta/developer/jugtours/model/Group.java",
    "content": "package com.okta.developer.jugtours.model;\n\nimport lombok.Data;\nimport lombok.NoArgsConstructor;\nimport lombok.NonNull;\nimport lombok.RequiredArgsConstructor;\n\nimport jakarta.persistence.*;\n\nimport java.util.Set;\n\n@Data\n@NoArgsConstructor\n@RequiredArgsConstructor\n@Entity\n@Table(name = \"user_group\")\npublic class Group {\n\n    @Id\n    @GeneratedValue\n    private Long id;\n    @NonNull\n    private String name;\n    private String address;\n    private String city;\n    private String stateOrProvince;\n    private String country;\n    private String postalCode;\n    @ManyToOne(cascade = CascadeType.PERSIST)\n    private User user;\n\n    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)\n    private Set<Event> events;\n}\n"
  },
  {
    "path": "src/main/java/com/okta/developer/jugtours/model/GroupRepository.java",
    "content": "package com.okta.developer.jugtours.model;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\n\nimport java.util.List;\n\npublic interface GroupRepository extends JpaRepository<Group, Long> {\n    Group findByName(String name);\n\n    List<Group> findAllByUserId(String id);\n}\n"
  },
  {
    "path": "src/main/java/com/okta/developer/jugtours/model/User.java",
    "content": "package com.okta.developer.jugtours.model;\n\nimport lombok.AllArgsConstructor;\nimport lombok.Data;\nimport lombok.NoArgsConstructor;\n\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.Id;\nimport jakarta.persistence.Table;\n\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"users\")\npublic class User {\n\n    @Id\n    private String id;\n    private String name;\n    private String email;\n}\n"
  },
  {
    "path": "src/main/java/com/okta/developer/jugtours/model/UserRepository.java",
    "content": "package com.okta.developer.jugtours.model;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\n\npublic interface UserRepository extends JpaRepository<User, String> {\n}\n"
  },
  {
    "path": "src/main/java/com/okta/developer/jugtours/web/CookieCsrfFilter.java",
    "content": "package com.okta.developer.jugtours.web;\n\nimport jakarta.servlet.FilterChain;\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\nimport org.springframework.security.web.csrf.CsrfToken;\nimport org.springframework.web.filter.OncePerRequestFilter;\n\nimport java.io.IOException;\n\n/**\n * Spring Security 6 doesn't set a XSRF-TOKEN cookie by default.\n * This solution is\n * <a href=\"https://github.com/spring-projects/spring-security/issues/12141#issuecomment-1321345077\">\n * recommended by Spring Security.</a>\n */\npublic class CookieCsrfFilter extends OncePerRequestFilter {\n\n    /**\n     * {@inheritDoc}\n     */\n    @Override\n    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,\n                                    FilterChain filterChain) throws ServletException, IOException {\n        CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());\n        response.setHeader(csrfToken.getHeaderName(), csrfToken.getToken());\n        filterChain.doFilter(request, response);\n    }\n}\n"
  },
  {
    "path": "src/main/java/com/okta/developer/jugtours/web/GroupController.java",
    "content": "package com.okta.developer.jugtours.web;\n\nimport com.okta.developer.jugtours.model.Group;\nimport com.okta.developer.jugtours.model.GroupRepository;\nimport com.okta.developer.jugtours.model.User;\nimport com.okta.developer.jugtours.model.UserRepository;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.core.annotation.AuthenticationPrincipal;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.oauth2.core.user.OAuth2User;\nimport org.springframework.web.bind.annotation.*;\n\nimport jakarta.validation.Valid;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.security.Principal;\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Optional;\n\n@RestController\n@RequestMapping(\"/api\")\nclass GroupController {\n\n    private final Logger log = LoggerFactory.getLogger(GroupController.class);\n    private GroupRepository groupRepository;\n    private UserRepository userRepository;\n\n    public GroupController(GroupRepository groupRepository, UserRepository userRepository) {\n        this.groupRepository = groupRepository;\n        this.userRepository = userRepository;\n    }\n\n    @GetMapping(\"/groups\")\n    Collection<Group> groups(Principal principal) {\n        return groupRepository.findAllByUserId(principal.getName());\n    }\n\n    @GetMapping(\"/group/{id}\")\n    ResponseEntity<?> getGroup(@PathVariable Long id) {\n        Optional<Group> group = groupRepository.findById(id);\n        return group.map(response -> ResponseEntity.ok().body(response))\n            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));\n    }\n\n    @PostMapping(\"/group\")\n    ResponseEntity<Group> createGroup(@Valid @RequestBody Group group,\n                                      @AuthenticationPrincipal OAuth2User principal) throws URISyntaxException {\n        log.info(\"Request to create group: {}\", group);\n        Map<String, Object> details = principal.getAttributes();\n        String userId = details.get(\"sub\").toString();\n\n        // check to see if user already exists\n        Optional<User> user = userRepository.findById(userId);\n        group.setUser(user.orElse(new User(userId,\n            details.get(\"name\").toString(), details.get(\"email\").toString())));\n\n        Group result = groupRepository.save(group);\n        return ResponseEntity.created(new URI(\"/api/group/\" + result.getId()))\n            .body(result);\n    }\n\n    @PutMapping(\"/group/{id}\")\n    ResponseEntity<Group> updateGroup(@Valid @RequestBody Group group) {\n        log.info(\"Request to update group: {}\", group);\n        Group result = groupRepository.save(group);\n        return ResponseEntity.ok().body(result);\n    }\n\n    @DeleteMapping(\"/group/{id}\")\n    public ResponseEntity<?> deleteGroup(@PathVariable Long id) {\n        log.info(\"Request to delete group: {}\", id);\n        groupRepository.deleteById(id);\n        return ResponseEntity.ok().build();\n    }\n}\n"
  },
  {
    "path": "src/main/java/com/okta/developer/jugtours/web/SpaWebFilter.java",
    "content": "package com.okta.developer.jugtours.web;\n\nimport jakarta.servlet.FilterChain;\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.oauth2.core.user.OAuth2User;\nimport org.springframework.web.filter.OncePerRequestFilter;\n\nimport java.io.IOException;\nimport java.security.Principal;\n\npublic class SpaWebFilter extends OncePerRequestFilter {\n\n    @Override\n    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,\n                                    FilterChain filterChain) throws ServletException, IOException {\n        String path = request.getRequestURI();\n        Authentication user = SecurityContextHolder.getContext().getAuthentication();\n        if (user != null && !path.startsWith(\"/api\") && !path.contains(\".\") && path.matches(\"/(.*)\")) {\n            request.getRequestDispatcher(\"/\").forward(request, response);\n            return;\n        }\n\n        filterChain.doFilter(request, response);\n    }\n}\n"
  },
  {
    "path": "src/main/java/com/okta/developer/jugtours/web/UserController.java",
    "content": "package com.okta.developer.jugtours.web;\n\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.core.annotation.AuthenticationPrincipal;\nimport org.springframework.security.oauth2.client.registration.ClientRegistration;\nimport org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;\nimport org.springframework.security.oauth2.core.oidc.OidcIdToken;\nimport org.springframework.security.oauth2.core.user.OAuth2User;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport jakarta.servlet.http.HttpServletRequest;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n@RestController\npublic class UserController {\n    private final ClientRegistration registration;\n\n    public UserController(ClientRegistrationRepository registrations) {\n        this.registration = registrations.findByRegistrationId(\"okta\");\n    }\n\n    @GetMapping(\"/api/user\")\n    public ResponseEntity<?> getUser(@AuthenticationPrincipal OAuth2User user) {\n        if (user == null) {\n            return new ResponseEntity<>(\"\", HttpStatus.OK);\n        } else {\n            return ResponseEntity.ok().body(user.getAttributes());\n        }\n    }\n\n    @PostMapping(\"/api/logout\")\n    public ResponseEntity<?> logout(HttpServletRequest request,\n                                    @AuthenticationPrincipal(expression = \"idToken\") OidcIdToken idToken) {\n        // send logout URL to client so they can initiate logout\n        String logoutUrl = this.registration.getProviderDetails()\n            .getConfigurationMetadata().get(\"end_session_endpoint\").toString();\n\n        Map<String, String> logoutDetails = new HashMap<>();\n        logoutDetails.put(\"logoutUrl\", logoutUrl);\n        logoutDetails.put(\"idToken\", idToken.getTokenValue());\n        request.getSession(false).invalidate();\n        return ResponseEntity.ok().body(logoutDetails);\n    }\n}\n"
  },
  {
    "path": "src/main/resources/application.properties",
    "content": "spring.profiles.active=@spring.profiles.active@\n"
  },
  {
    "path": "src/test/java/com/okta/developer/jugtours/JugtoursApplicationTests.java",
    "content": "package com.okta.developer.jugtours;\n\nimport org.junit.jupiter.api.Test;\nimport org.springframework.boot.test.context.SpringBootTest;\n\n@SpringBootTest\nclass JugtoursApplicationTests {\n\n\t@Test\n\tvoid contextLoads() {\n\t}\n\n}\n"
  }
]