Repository: oktadev/okta-spring-boot-react-crud-example Branch: main Commit: 6d75759b13d0 Files: 41 Total size: 115.6 KB Directory structure: gitextract_wnmria1r/ ├── .gitignore ├── .mvn/ │ └── wrapper/ │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── HELP.md ├── LICENSE ├── README.md ├── app/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ ├── index.html │ │ ├── manifest.json │ │ └── robots.txt │ └── src/ │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── AppNavbar.js │ ├── GroupEdit.js │ ├── GroupList.js │ ├── Home.js │ ├── index.css │ ├── index.js │ ├── reportWebVitals.js │ └── setupTests.js ├── demo.adoc ├── mvnw ├── mvnw.cmd ├── pom.xml └── src/ ├── main/ │ ├── java/ │ │ └── com/ │ │ └── okta/ │ │ └── developer/ │ │ └── jugtours/ │ │ ├── Initializer.java │ │ ├── JugtoursApplication.java │ │ ├── config/ │ │ │ └── SecurityConfiguration.java │ │ ├── model/ │ │ │ ├── Event.java │ │ │ ├── Group.java │ │ │ ├── GroupRepository.java │ │ │ ├── User.java │ │ │ └── UserRepository.java │ │ └── web/ │ │ ├── CookieCsrfFilter.java │ │ ├── GroupController.java │ │ ├── SpaWebFilter.java │ │ └── UserController.java │ └── resources/ │ └── application.properties └── test/ └── java/ └── com/ └── okta/ └── developer/ └── jugtours/ └── JugtoursApplicationTests.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.env target/ !.mvn/wrapper/maven-wrapper.jar !**/src/main/**/target/ !**/src/test/**/target/ ### STS ### .apt_generated .classpath .factorypath .project .settings .springBeans .sts4-cache ### IntelliJ IDEA ### .idea *.iws *.iml *.ipr ### NetBeans ### /nbproject/private/ /nbbuild/ /dist/ /nbdist/ /.nb-gradle/ build/ !**/src/main/**/build/ !**/src/test/**/build/ ### VS Code ### .vscode/ ================================================ FILE: .mvn/wrapper/maven-wrapper.properties ================================================ distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar ================================================ FILE: HELP.md ================================================ # Getting Started ### Reference Documentation For further reference, please consider the following sections: * [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) * [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/3.0.6/maven-plugin/reference/html/) * [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.0.6/maven-plugin/reference/html/#build-image) * [Spring Data JPA](https://docs.spring.io/spring-boot/docs/3.0.6/reference/htmlsingle/#data.sql.jpa-and-spring-data) * [Spring Web](https://docs.spring.io/spring-boot/docs/3.0.6/reference/htmlsingle/#web) ### Guides The following guides illustrate how to use some features concretely: * [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) * [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) * [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) * [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018-Present Okta, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # JUG Tours with Spring Boot and React This example app shows how to create a Spring Boot API and CRUD (create, read, update, and delete) its data with a React app. Please 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. **Prerequisites:** [Java 17](http://sdkman.io) and [Node.js 18+](https://nodejs.org/) > [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. * [Getting Started](#getting-started) * [Links](#links) * [Help](#help) * [License](#license) ## Getting Started To install this example application, run the following commands: ```bash git clone https://github.com/oktadev/okta-spring-boot-react-crud-example.git spring-react cd spring-react ``` This will get a copy of the project installed locally. ### Create an Application in Okta Before 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`. Then, run `okta apps create`. Select the default app name, or change it as you see fit. Choose **Web** and press **Enter**. Select **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. The 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: ```shell Okta application configuration has been written to: /path/to/app/src/main/resources/application.properties ``` Open `src/main/resources/application.properties` to see the issuer and credentials for your app. ```properties okta.oauth2.issuer=https://dev-133337.okta.com/oauth2/default okta.oauth2.client-id=0oab8eb55Kb9jdMIr5d6 okta.oauth2.client-secret=NEVER-SHOW-SECRETS ``` NOTE: 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. Run `./mvnw spring-boot:run -Pprod` and log in to your app at `http://localhost:8080`. ### Use Auth0 for OpenID Connect If you'd rather use Auth0, that's possible too! First, you'll need to checkout the `auth0` branch of this repository. ```bash git clone -b auth0 https://github.com/oktadev/okta-spring-boot-react-crud-example.git spring-react cd spring-react ``` Then, install the [Auth0 CLI](https://github.com/auth0/auth0-cli) and run `auth0 login` in a terminal. Next, run `auth0 apps create` and specify the appropriate URLs: ```bash auth0 apps create \ --name "Spring Boot + React" \ --description "Spring Boot OIDC App" \ --type regular \ --callbacks http://localhost:8080/login/oauth2/code/okta \ --logout-urls http://localhost:3000,http://localhost:8080 \ --reveal-secrets ``` Modify your `src/main/resources/application.properties` to include your Auth0 issuer, client ID, and client secret. ```properties # make sure to include the trailing slash for the Auth0 issuer okta.oauth2.issuer=https:/// okta.oauth2.issuer.client-id= okta.oauth2.issuer.client-secret= ``` NOTE: 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. Run `./mvnw spring-boot:run -Pprod` and log in to your app at `http://localhost:8080`. ## Links This example uses the following open source libraries: * [React](https://reactjs.org/) * [Spring Boot](https://spring.io/projects/spring-boot) * [Spring Security](https://spring.io/projects/spring-security) ## Help Please 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/). ## License Apache 2.0, see [LICENSE](LICENSE). ================================================ FILE: app/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build /node # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: app/README.md ================================================ # Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can't go back!** If 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. Instead, 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. You 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. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This 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) ### Making a Progressive Web App This 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) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify This 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) ================================================ FILE: app/package.json ================================================ { "name": "app", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "bootstrap": "^5.2.3", "react": "^18.2.0", "react-cookie": "^4.1.1", "react-dom": "^18.2.0", "react-router-dom": "^6.10.0", "react-scripts": "5.0.1", "reactstrap": "^9.1.9", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "proxy": "http://localhost:8080", "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: app/public/index.html ================================================ React App
================================================ FILE: app/public/manifest.json ================================================ { "short_name": "React App", "name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" }, { "src": "logo192.png", "type": "image/png", "sizes": "192x192" }, { "src": "logo512.png", "type": "image/png", "sizes": "512x512" } ], "start_url": ".", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" } ================================================ FILE: app/public/robots.txt ================================================ # https://www.robotstxt.org/robotstxt.html User-agent: * Disallow: ================================================ FILE: app/src/App.css ================================================ .App { text-align: center; } .App-logo { height: 40vmin; pointer-events: none; } @media (prefers-reduced-motion: no-preference) { .App-logo { animation: App-logo-spin infinite 20s linear; } } .App-header { background-color: #282c34; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white; } .App-link { color: #61dafb; } @keyframes App-logo-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } nav + .container, nav + .container-fluid { margin-top: 20px; } ================================================ FILE: app/src/App.js ================================================ import React from 'react'; import './App.css'; import Home from './Home'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import GroupList from './GroupList'; import GroupEdit from './GroupEdit'; const App = () => { return ( }/> }/> }/> ) } export default App; ================================================ FILE: app/src/App.test.js ================================================ import { render, screen } from '@testing-library/react'; import App from './App'; test('renders loading...', () => { render(); const linkElement = screen.getByText(/loading/i); expect(linkElement).toBeInTheDocument(); }); ================================================ FILE: app/src/AppNavbar.js ================================================ import React, { useState } from 'react'; import { Collapse, Nav, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap'; import { Link } from 'react-router-dom'; const AppNavbar = () => { const [isOpen, setIsOpen] = useState(false); return ( Home { setIsOpen(!isOpen) }}/> ); }; export default AppNavbar; ================================================ FILE: app/src/GroupEdit.js ================================================ import React, { useEffect, useState } from 'react'; import { Link, useNavigate, useParams } from 'react-router-dom'; import { Button, Container, Form, FormGroup, Input, Label } from 'reactstrap'; import AppNavbar from './AppNavbar'; import { useCookies } from 'react-cookie'; const GroupEdit = () => { const initialFormState = { name: '', address: '', city: '', stateOrProvince: '', country: '', postalCode: '' }; const [group, setGroup] = useState(initialFormState); const navigate = useNavigate(); const { id } = useParams(); const [cookies] = useCookies(['XSRF-TOKEN']); useEffect(() => { if (id !== 'new') { fetch(`/api/group/${id}`) .then(response => response.json()) .then(data => setGroup(data)); } }, [id, setGroup]); const handleChange = (event) => { const { name, value } = event.target setGroup({ ...group, [name]: value }) } const handleSubmit = async (event) => { event.preventDefault(); await fetch(`/api/group${group.id ? `/${group.id}` : ''}`, { method: (group.id) ? 'PUT' : 'POST', headers: { 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'], 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(group), credentials: 'include' }); setGroup(initialFormState); navigate('/groups'); } const title =

{group.id ? 'Edit Group' : 'Add Group'}

; return (
{title}
{' '}
) }; export default GroupEdit; ================================================ FILE: app/src/GroupList.js ================================================ import React, { useEffect, useState } from 'react'; import { Button, ButtonGroup, Container, Table } from 'reactstrap'; import AppNavbar from './AppNavbar'; import { Link } from 'react-router-dom'; import { useCookies } from 'react-cookie'; const GroupList = () => { const [groups, setGroups] = useState([]); const [loading, setLoading] = useState(false); const [cookies] = useCookies(['XSRF-TOKEN']); useEffect(() => { setLoading(true); fetch('api/groups') .then(response => response.json()) .then(data => { setGroups(data); setLoading(false); }) }, []); const remove = async (id) => { await fetch(`/api/group/${id}`, { method: 'DELETE', headers: { 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'], 'Accept': 'application/json', 'Content-Type': 'application/json' }, credentials: 'include' }).then(() => { let updatedGroups = [...groups].filter(i => i.id !== id); setGroups(updatedGroups); }); } if (loading) { return

Loading...

; } const groupList = groups.map(group => { const address = `${group.address || ''} ${group.city || ''} ${group.stateOrProvince || ''}`; return {group.name} {address} {group.events.map(event => { return
{new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'long', day: '2-digit' }).format(new Date(event.date))}: {event.title}
})} }); return (

My JUG Tour

{groupList}
Name Location Events Actions
); }; export default GroupList; ================================================ FILE: app/src/Home.js ================================================ import React, { useEffect, useState } from 'react'; import './App.css'; import AppNavbar from './AppNavbar'; import { Link } from 'react-router-dom'; import { Button, Container } from 'reactstrap'; import { useCookies } from 'react-cookie'; const Home = () => { const [authenticated, setAuthenticated] = useState(false); const [loading, setLoading] = useState(false); const [user, setUser] = useState(undefined); const [cookies] = useCookies(['XSRF-TOKEN']); // <.> useEffect(() => { setLoading(true); fetch('api/user', { credentials: 'include' }) // <.> .then(response => response.text()) .then(body => { if (body === '') { setAuthenticated(false); } else { setUser(JSON.parse(body)); setAuthenticated(true); } setLoading(false); }); }, [setAuthenticated, setLoading, setUser]) const login = () => { let port = (window.location.port ? ':' + window.location.port : ''); if (port === ':3000') { port = ':8080'; } window.location.href = `//${window.location.hostname}${port}/api/private`; } const logout = () => { fetch('/api/logout', { method: 'POST', credentials: 'include', headers: { 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'] } // <.> }) .then(res => res.json()) .then(response => { window.location.href = `${response.logoutUrl}?id_token_hint=${response.idToken}` + `&post_logout_redirect_uri=${window.location.origin}`; }); } const message = user ?

Welcome, {user.name}!

:

Please log in to manage your JUG Tour.

; const button = authenticated ?

: ; if (loading) { return

Loading...

; } return (
{message} {button}
); } export default Home; ================================================ FILE: app/src/index.css ================================================ body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; } ================================================ FILE: app/src/index.js ================================================ import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import 'bootstrap/dist/css/bootstrap.min.css'; import { CookiesProvider } from 'react-cookie'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals(); ================================================ FILE: app/src/reportWebVitals.js ================================================ const reportWebVitals = onPerfEntry => { if (onPerfEntry && onPerfEntry instanceof Function) { import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); getFID(onPerfEntry); getFCP(onPerfEntry); getLCP(onPerfEntry); getTTFB(onPerfEntry); }); } }; export default reportWebVitals; ================================================ FILE: app/src/setupTests.js ================================================ // jest-dom adds custom jest matchers for asserting on DOM nodes. // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import '@testing-library/jest-dom'; ================================================ FILE: demo.adoc ================================================ :experimental: :commandkey: ⌘ :toc: macro :source-highlighter: highlight.js = Use React and Spring Boot to Build a Simple CRUD App Today, 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. **Prerequisites**: - http://sdkman.io[Java 17] - https://nodejs.org/[Node 16] - https://github.com/okta/okta-cli[Okta CLI] TIP: 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]. toc::[] == Create an API app with Spring Boot . Navigate to https://start.spring.io[start.spring.io] and make the following selections: * **Project:** `Maven Project` * **Group:** `com.okta.developer` * **Artifact:** `jugtours` * **Dependencies**: `JPA`, `H2`, `Web`, `Lombok` . Click **Generate Project**, expand `jugtours.zip` after downloading, and open the project in your favorite IDE. === Add a JPA domain model . Create a `src/main/java/com/okta/developer/jugtours/model` directory and a `Group.java` class in it. [`sbr-group`] + .`Group.java` [%collapsible] ==== [source,java] ---- package com.okta.developer.jugtours.model; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import jakarta.persistence.*; import java.util.Set; @Data @NoArgsConstructor @RequiredArgsConstructor @Entity @Table(name = "user_group") public class Group { @Id @GeneratedValue private Long id; @NonNull private String name; private String address; private String city; private String stateOrProvince; private String country; private String postalCode; @ManyToOne(cascade=CascadeType.PERSIST) private User user; @OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL) private Set events; } ---- ==== . Create an `Event.java` class in the same package. [`sbr-event`] + .`Event.java` [%collapsible] ==== [source,java] ---- package com.okta.developer.jugtours.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.ManyToMany; import java.time.Instant; import java.util.Set; @Data @NoArgsConstructor @AllArgsConstructor @Builder @Entity public class Event { @Id @GeneratedValue private Long id; private Instant date; private String title; private String description; @ManyToMany private Set attendees; } ---- ==== . And a `User.java` class. [`sbr-user`] + .`User.java` [%collapsible] ==== [source,java] ---- package com.okta.developer.jugtours.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; @Data @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "users") public class User { @Id private String id; private String name; private String email; } ---- ==== . Create a `GroupRepository.java` to manage the group entity. [`sbr-group-repo`] + .`GroupRepository.java` [%collapsible] ==== [source,java] ---- package com.okta.developer.jugtours.model; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface GroupRepository extends JpaRepository { Group findByName(String name); } ---- ==== . To load some default data, create an `Initializer.java` class in the `com.okta.developer.jugtours` package. [`sbr-init`] + .`Initializer.java` [%collapsible] ==== [source,java] ---- package com.okta.developer.jugtours; import com.okta.developer.jugtours.model.Event; import com.okta.developer.jugtours.model.Group; import com.okta.developer.jugtours.model.GroupRepository; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import java.time.Instant; import java.util.Collections; import java.util.stream.Stream; @Component class Initializer implements CommandLineRunner { private final GroupRepository repository; public Initializer(GroupRepository repository) { this.repository = repository; } @Override public void run(String... strings) { Stream.of("Seattle JUG", "Denver JUG", "Dublin JUG", "London JUG").forEach(name -> repository.save(new Group(name)) ); Group djug = repository.findByName("Seattle JUG"); Event e = Event.builder().title("Micro Frontends for Java Developers") .description("JHipster now has microfrontend support!") .date(Instant.parse("2022-09-13T17:00:00.000Z")) .build(); djug.setEvents(Collections.singleton(e)); repository.save(djug); repository.findAll().forEach(System.out::println); } } ---- ==== + TIP: 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. + . Start your app with `mvn spring-boot:run` and you should see groups and events being created. . Add a `GroupController.java` class (in `src/main/java/.../jugtours/web`) that allows you to CRUD groups. [`sbr-group-controller`] + .`GroupController.java` [%collapsible] ==== [source,java] ---- package com.okta.developer.jugtours.web; import com.okta.developer.jugtours.model.Group; import com.okta.developer.jugtours.model.GroupRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import jakarta.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.Optional; @RestController @RequestMapping("/api") class GroupController { private final Logger log = LoggerFactory.getLogger(GroupController.class); private GroupRepository groupRepository; public GroupController(GroupRepository groupRepository) { this.groupRepository = groupRepository; } @GetMapping("/groups") Collection groups() { return groupRepository.findAll(); } @GetMapping("/group/{id}") ResponseEntity getGroup(@PathVariable Long id) { Optional group = groupRepository.findById(id); return group.map(response -> ResponseEntity.ok().body(response)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); } @PostMapping("/group") ResponseEntity createGroup(@Valid @RequestBody Group group) throws URISyntaxException { log.info("Request to create group: {}", group); Group result = groupRepository.save(group); return ResponseEntity.created(new URI("/api/group/" + result.getId())) .body(result); } @PutMapping("/group/{id}") ResponseEntity updateGroup(@Valid @RequestBody Group group) { log.info("Request to update group: {}", group); Group result = groupRepository.save(group); return ResponseEntity.ok().body(result); } @DeleteMapping("/group/{id}") public ResponseEntity deleteGroup(@PathVariable Long id) { log.info("Request to delete group: {}", id); groupRepository.deleteById(id); return ResponseEntity.ok().build(); } } ---- ==== . Add the following dependency to your `pom.xml` to fix compilation errors: + [source,xml] ---- org.springframework.boot spring-boot-starter-validation ---- . Restart the app and hit `http://localhost:8080/api/groups` with https://httpie.org[HTTPie] and you should see the list of groups. http :8080/api/groups . You can create, read, update, and delete groups with the following commands. + [source,shell] ---- http POST :8080/api/group name='Utah JUG' city='Salt Lake City' country=USA http :8080/api/group/5 http PUT :8080/api/group/5 id=6 name='Utah JUG' address='On the slopes' http DELETE :8080/api/group/5 ---- == Create a React UI with Create React App . Create a new project in the root directory with `npx` and Create React App. + [source,shell] ---- npx create-react-app@5 app ---- . After the app creation process completes, navigate into the `app` directory and install Bootstrap, cookie support for React, React Router, and Reactstrap. + [source,shell] ---- cd app npm i bootstrap@5 react-cookie@4 react-router-dom@6 reactstrap@9 ---- . Add Bootstrap's CSS file as an import in `app/src/index.js`. + [source,js] ---- import 'bootstrap/dist/css/bootstrap.min.css'; ---- == Call your Spring Boot API and display the results . Modify `App.js` to use the following code that calls `/api/groups` and displays the list in the UI. [`sbr-app`] + .`app/src/App.js` [%collapsible] ==== [source,jsx] ---- import React, { useEffect, useState } from 'react'; import logo from './logo.svg'; import './App.css'; const App = () => { const [groups, setGroups] = useState([]); const [loading, setLoading] = useState(false); useEffect(() => { setLoading(true); fetch('api/groups') .then(response => response.json()) .then(data => { setGroups(data); setLoading(false); }) }, []); if (loading) { return

Loading...

; } return (
logo

JUG List

{groups.map(group =>
{group.name}
)}
); } export default App; ---- ==== . To proxy from `/api` to `http://localhost:8080/api`, add a proxy setting to `app/package.json`. + [source,json] ---- "scripts": {...}, "proxy": "http://localhost:8080", ---- . Make sure Spring Boot is running, then run `npm start` in your `app` directory. You should see the list of default groups. == Build a React `GroupList` component . 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`] + .`src/app/GroupList.js` [%collapsible] ==== [source,jsx] ---- import React, { useEffect, useState } from 'react'; import { Button, ButtonGroup, Container, Table } from 'reactstrap'; import AppNavbar from './AppNavbar'; import { Link } from 'react-router-dom'; const GroupList = () => { const [groups, setGroups] = useState([]); const [loading, setLoading] = useState(false); useEffect(() => { setLoading(true); fetch('api/groups') .then(response => response.json()) .then(data => { setGroups(data); setLoading(false); }) }, []); const remove = async (id) => { await fetch(`/api/group/${id}`, { method: 'DELETE', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }).then(() => { let updatedGroups = [...groups].filter(i => i.id !== id); setGroups(updatedGroups); }); } if (loading) { return

Loading...

; } const groupList = groups.map(group => { const address = `${group.address || ''} ${group.city || ''} ${group.stateOrProvince || ''}`; return {group.name} {address} {group.events.map(event => { return
{new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'long', day: '2-digit' }).format(new Date(event.date))}: {event.title}
})} }); return (

My JUG Tour

{groupList}
Name Location Events Actions
); }; export default GroupList; ---- ==== . Create `AppNavbar.js` in the same directory to establish a common UI feature between components. [`sbr-navbar`] + .`src/app/AppNavbar.js` [%collapsible] ==== [source,jsx] ---- import React, { useState } from 'react'; import { Collapse, Nav, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap'; import { Link } from 'react-router-dom'; const AppNavbar = () => { const [isOpen, setIsOpen] = useState(false); return ( Home { setIsOpen(!isOpen) }}/> ); }; export default AppNavbar; ---- ==== . Create `Home.js` to serve as the landing page for your app. [`sbr-home`] + .`src/app/Home.js` [%collapsible] ==== [source,jsx] ---- import React from 'react'; import './App.css'; import AppNavbar from './AppNavbar'; import { Link } from 'react-router-dom'; import { Button, Container } from 'reactstrap'; const Home = () => { return (
); } export default Home; ---- ==== . Also, change `App.js` to use React Router to navigate between components. [`sbr-app-router`] + .`src/app/App.js` [%collapsible] ==== [source,jsx] ---- import React from 'react'; import './App.css'; import Home from './Home'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import GroupList from './GroupList'; const App = () => { return ( }/> }/> ) } export default App; ---- ==== . To make your UI a bit more spacious, add a top margin to Bootstrap's container classes in `App.css`. + [source,css] ---- nav + .container, nav + .container-fluid { margin-top: 20px; } ---- . Your React app should update itself as you make changes at `http://localhost:3000`. . Click on **Manage JUG Tour** and you should see a list of the default groups. == Add a React `GroupEdit` component . Create `GroupEdit.js` and use `useEffect()` to fetch the group resource with the ID from the URL. [`sbr-group-edit`] + .`app/src/GroupEdit.js` [%collapsible] ==== [source,jsx] ---- import React, { useEffect, useState } from 'react'; import { Link, useNavigate, useParams } from 'react-router-dom'; import { Button, Container, Form, FormGroup, Input, Label } from 'reactstrap'; import AppNavbar from './AppNavbar'; const GroupEdit = () => { const initialFormState = { name: '', address: '', city: '', stateOrProvince: '', country: '', postalCode: '' }; const [group, setGroup] = useState(initialFormState); const navigate = useNavigate(); const { id } = useParams(); useEffect(() => { if (id !== 'new') { fetch(`/api/group/${id}`) .then(response => response.json()) .then(data => setGroup(data)); } }, [id, setGroup]); const handleChange = (event) => { const { name, value } = event.target setGroup({ ...group, [name]: value }) } const handleSubmit = async (event) => { event.preventDefault(); await fetch('/api/group' + (group.id ? '/' + group.id : ''), { method: (group.id) ? 'PUT' : 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(group) }); setGroup(initialFormState); navigate('/groups'); } const title =

{group.id ? 'Edit Group' : 'Add Group'}

; return (
{title}
{' '}
) }; export default GroupEdit; ---- ==== . Modify `App.js` to import `GroupEdit` and specify a path to it. + [source,jsx] ---- import GroupEdit from './GroupEdit'; const App = () => { return ( ... }/> ) } ---- Now you should be able to add and edit groups! == Add Authentication with Auth0 . Add the necessary Spring Security dependencies to do OIDC authentication. [`sbr-spring-oauth`] + [source,xml] ---- org.springframework.boot spring-boot-starter-security org.springframework.security spring-security-config org.springframework.security spring-security-oauth2-client org.springframework.security spring-security-oauth2-jose ---- + NOTE: We hope to make the Okta Spring Boot starter https://github.com/okta/okta-spring-boot/issues/358[work with Auth0] in the future. . Install the https://github.com/auth0/auth0-cli[Auth0 CLI] and run `auth0 login` in a terminal. . 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**. . 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`] + [source,properties] ---- # make sure to include the trailing slash for the Auth0 issuer spring.security.oauth2.client.provider.auth0.issuer-uri=https:/// spring.security.oauth2.client.registration.auth0.client-id= spring.security.oauth2.client.registration.auth0.client-secret= spring.security.oauth2.client.registration.auth0.scope=openid,profile,email ---- + Of 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. == Add Authentication with Okta . Add the Okta Spring Boot starter to do OIDC authentication. + [source,xml] ---- com.okta.spring okta-spring-boot-starter 2.1.6 ---- . 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**. + Select **Okta Spring Boot Starter**. Accept the default Redirect URI and use `\http://localhost:3000,http://localhost:8080` for the Logout Redirect URI. . After configuring Spring Security in the section below, update `UserController.java` to use `okta` in its constructor: + [source,java] ---- public UserController(ClientRegistrationRepository registrations) { this.registration = registrations.findByRegistrationId("okta"); } ---- . And update the `logout()` method to work with Okta: + [source,java] ---- @PostMapping("/api/logout") public ResponseEntity logout(HttpServletRequest request, @AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) { // send logout URL to client so they can initiate logout String logoutUrl = this.registration.getProviderDetails() .getConfigurationMetadata().get("end_session_endpoint").toString(); Map logoutDetails = new HashMap<>(); logoutDetails.put("logoutUrl", logoutUrl); logoutDetails.put("idToken", idToken.getTokenValue()); request.getSession(false).invalidate(); return ResponseEntity.ok().body(logoutDetails); } ---- . Update `Home.js` in the React project to use different parameters for the logout redirect: + [source,js] ---- window.location.href = `${response.logoutUrl}?id_token_hint=${response.idToken}` + `&post_logout_redirect_uri=${window.location.origin}`; ---- TIP: 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]. == Configure Spring Security for React and user identity . To make Spring Security React-friendly, create a `SecurityConfiguration.java` file in `src/main/java/.../jugtours/config`. [`sbr-security-config`] + ==== [source,java] ---- package com.okta.developer.jugtours.config; import com.okta.developer.jugtours.web.CookieCsrfFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.security.web.context.SecurityContextHolderFilter; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.SimpleSavedRequest; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.util.Enumeration; import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; @Configuration public class SecurityConfiguration { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authz) -> authz .requestMatchers("/", "/index.html", "/static/**", "/*.ico", "/*.json", "/*.png", "/api/user").permitAll() // <.> .anyRequest().authenticated() ) .csrf((csrf) -> csrf .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) // <.> // https://stackoverflow.com/a/74521360/65681 .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()) ) .addFilterAfter(new CookieCsrfFilter(), BasicAuthenticationFilter.class) // <.> .oauth2Login(); return http.build(); } @Bean public RequestCache refererRequestCache() { // <.> return new HttpSessionRequestCache() { @Override public void saveRequest(HttpServletRequest request, HttpServletResponse response) { String referrer = request.getHeader("referer"); // <.> if (referrer == null) { referrer = request.getRequestURL().toString(); } request.getSession().setAttribute("SPRING_SECURITY_SAVED_REQUEST", new SimpleSavedRequest(referrer)); } }; } } ---- . Define what URLs are allowed for anonymous users. . `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. . Spring Security 6 no longer sets a CSRF cookie for you. Add a filter to do it. . The `RequestCache` bean overrides the default request cache. . It saves the referrer header (misspelled `referer` in real life), so Spring Security can redirect back to it after authentication. ==== . Create `src/main/java/.../jugtours/web/CookieCsrfFilter.java` to set a CSRF cookie. [`sbr-csrf`] + .`CookieCsrfFilter.java` [%collapsible] ==== [source,java] ---- package com.okta.developer.jugtours.web; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; /** * Spring Security 6 doesn't set a XSRF-TOKEN cookie by default. * This solution is * * recommended by Spring Security. */ public class CookieCsrfFilter extends OncePerRequestFilter { /** * {@inheritDoc} */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); response.setHeader(csrfToken.getHeaderName(), csrfToken.getToken()); filterChain.doFilter(request, response); } } ---- ==== . 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`] + .`UserController.java` [%collapsible] ==== [source,java] ---- package com.okta.developer.jugtours.web; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import jakarta.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; @RestController public class UserController { private ClientRegistration registration; public UserController(ClientRegistrationRepository registrations) { this.registration = registrations.findByRegistrationId("auth0"); } @GetMapping("/api/user") public ResponseEntity getUser(@AuthenticationPrincipal OAuth2User user) { if (user == null) { return new ResponseEntity<>("", HttpStatus.OK); } else { return ResponseEntity.ok().body(user.getAttributes()); } } @PostMapping("/api/logout") public ResponseEntity logout(HttpServletRequest request) { // send logout URL to client so they can initiate logout StringBuilder logoutUrl = new StringBuilder(); String issuerUri = this.registration.getProviderDetails().getIssuerUri(); logoutUrl.append(issuerUri.endsWith("/") ? issuerUri + "v2/logout" : issuerUri + "/v2/logout"); logoutUrl.append("?client_id=").append(this.registration.getClientId()); Map logoutDetails = new HashMap<>(); logoutDetails.put("logoutUrl", logoutUrl.toString()); request.getSession(false).invalidate(); return ResponseEntity.ok().body(logoutDetails); } } ---- ==== . 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`. + [source,java] ---- package com.okta.developer.jugtours.model; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { } ---- . Add a new `findAllByUserId(String id)` method to `GroupRepository.java`. + [source,java] ---- List findAllByUserId(String id); ---- . 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. + [source,java] ---- import org.springframework.security.core.annotation.AuthenticationPrincipal; ... @GetMapping("/groups") Collection groups(Principal principal) { return groupRepository.findAllByUserId(principal.getName()); } ... @PostMapping("/group") ResponseEntity createGroup(@Valid @RequestBody Group group, @AuthenticationPrincipal OAuth2User principal) throws URISyntaxException { log.info("Request to create group: {}", group); Map details = principal.getAttributes(); String userId = details.get("sub").toString(); // check to see if user already exists Optional user = userRepository.findById(userId); group.setUser(user.orElse(new User(userId, details.get("name").toString(), details.get("email").toString()))); Group result = groupRepository.save(group); return ResponseEntity.created(new URI("/api/group/" + result.getId())) .body(result); } ---- == Modify React to handle CSRF and be identity-aware You'll need to make a few changes to your React components to make them identity-aware. . 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. + [source,jsx] ---- import { CookiesProvider } from 'react-cookie'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( ); ---- . 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`] + ==== [source,jsx] ---- import React, { useEffect, useState } from 'react'; import './App.css'; import AppNavbar from './AppNavbar'; import { Link } from 'react-router-dom'; import { Button, Container } from 'reactstrap'; import { useCookies } from 'react-cookie'; const Home = () => { const [authenticated, setAuthenticated] = useState(false); const [loading, setLoading] = useState(false); const [user, setUser] = useState(undefined); const [cookies] = useCookies(['XSRF-TOKEN']); // <.> useEffect(() => { setLoading(true); fetch('api/user', { credentials: 'include' }) // <.> .then(response => response.text()) .then(body => { if (body === '') { setAuthenticated(false); } else { setUser(JSON.parse(body)); setAuthenticated(true); } setLoading(false); }); }, [setAuthenticated, setLoading, setUser]) const login = () => { let port = (window.location.port ? ':' + window.location.port : ''); if (port === ':3000') { port = ':8080'; } // redirect to a protected URL to trigger authentication window.location.href = `//${window.location.hostname}${port}/api/private`; } const logout = () => { fetch('/api/logout', { method: 'POST', credentials: 'include', headers: { 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'] } // <.> }) .then(res => res.json()) .then(response => { window.location.href = `${response.logoutUrl}&returnTo=${window.location.origin}`; }); } const message = user ?

Welcome, {user.name}!

:

Please log in to manage your JUG Tour.

; const button = authenticated ?

: ; if (loading) { return

Loading...

; } return (
{message} {button}
); } export default Home; ---- . `useCookies()` is used for access to cookies. Then you can fetch a cookie with `cookies['XSRF-TOKEN']`. . 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. . 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`. ==== . Update `GroupList.js` to have similar changes. + [source,jsx] ---- import { useCookies } from 'react-cookie'; const GroupList = () => { ... const [cookies] = useCookies(['XSRF-TOKEN']); ... const remove = async (id) => { await fetch(`/api/group/${id}`, { method: 'DELETE', headers: { 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'], 'Accept': 'application/json', 'Content-Type': 'application/json' }, credentials: 'include' }).then(() => { let updatedGroups = [...groups].filter(i => i.id !== id); setGroups(updatedGroups); }); } ... return (...) } export default GroupList; ---- . Update `GroupEdit.js` too. + [source,jsx] ---- import { useCookies } from 'react-cookie'; const GroupEdit = () => { ... const [cookies] = useCookies(['XSRF-TOKEN']); ... const handleSubmit = async (event) => { event.preventDefault(); await fetch(`/api/group${group.id ? `/${group.id}` : ''}`, { method: group.id ? 'PUT' : 'POST', headers: { 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'], 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(group), credentials: 'include' }); setGroup(initialFormState); navigate('/groups'); } ... return (...) } export default GroupEdit; ---- After 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! == Configure Maven to build and package React with Spring Boot To 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. . Add properties for versions and a `` section to your `pom.xml`. [`sbr-properties` and `sbr-profiles`] + .`pom.xml` [%collapsible] ==== [source,xml] ---- ... 1.12.1 v16.18.1 v8.19.2 dev true dev prod maven-resources-plugin copy-resources process-classes copy-resources ${basedir}/target/classes/static app/build com.github.eirslett frontend-maven-plugin ${frontend-maven-plugin.version} app install node install-node-and-npm ${node.version} ${npm.version} npm install npm generate-resources npm test test test test true npm build npm compile run build prod ---- ==== + Add the active profile setting to `src/main/resources/application.properties`: + [source,properties] ---- spring.profiles.active=@spring.profiles.active@ ---- . After adding this, you should be able to run `./mvnw spring-boot:run -Pprod` and see your app running on `http://localhost:8080`. . 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`] + .`SpaWebFilter.java` [%collapsible] ==== [source,java] ---- package com.okta.developer.jugtours.web; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; import java.security.Principal; public class SpaWebFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String path = request.getRequestURI(); Authentication user = SecurityContextHolder.getContext().getAuthentication(); if (user != null && !path.startsWith("/api") && !path.contains(".") && path.matches("/(.*)")) { request.getRequestDispatcher("/").forward(request, response); return; } filterChain.doFilter(request, response); } } ---- ==== . And add it to `SecurityConfiguration.java`: + [source,java] ---- .addFilterAfter(new SpaWebFilter(), BasicAuthenticationFilter.class) ---- . Now, if you restart and reload the page, everything will work as expected. 🤗 == Giddyup with React and Spring Boot! I hope you enjoyed this screencast, and it helped you understand how to integrate React and Spring Boot securely. ⚛️ Find the code on GitHub: https://github.com/oktadev/okta-spring-boot-react-crud-example[@oktadev/okta-spring-boot-react-crud-example] 🍃 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] ================================================ FILE: mvnw ================================================ #!/bin/sh # ---------------------------------------------------------------------------- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # Maven Start Up Batch script # # Required ENV vars: # ------------------ # JAVA_HOME - location of a JDK home dir # # Optional ENV vars # ----------------- # M2_HOME - location of maven2's installed home dir # MAVEN_OPTS - parameters passed to the Java VM when running Maven # e.g. to debug Maven itself, use # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 # MAVEN_SKIP_RC - flag to disable loading of mavenrc files # ---------------------------------------------------------------------------- if [ -z "$MAVEN_SKIP_RC" ] ; then if [ -f /usr/local/etc/mavenrc ] ; then . /usr/local/etc/mavenrc fi if [ -f /etc/mavenrc ] ; then . /etc/mavenrc fi if [ -f "$HOME/.mavenrc" ] ; then . "$HOME/.mavenrc" fi fi # OS specific support. $var _must_ be set to either true or false. cygwin=false; darwin=false; mingw=false case "`uname`" in CYGWIN*) cygwin=true ;; MINGW*) mingw=true;; Darwin*) darwin=true # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home # See https://developer.apple.com/library/mac/qa/qa1170/_index.html if [ -z "$JAVA_HOME" ]; then if [ -x "/usr/libexec/java_home" ]; then export JAVA_HOME="`/usr/libexec/java_home`" else export JAVA_HOME="/Library/Java/Home" fi fi ;; esac if [ -z "$JAVA_HOME" ] ; then if [ -r /etc/gentoo-release ] ; then JAVA_HOME=`java-config --jre-home` fi fi if [ -z "$M2_HOME" ] ; then ## resolve links - $0 may be a link to maven's home PRG="$0" # need this for relative symlinks while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG="`dirname "$PRG"`/$link" fi done saveddir=`pwd` M2_HOME=`dirname "$PRG"`/.. # make it fully qualified M2_HOME=`cd "$M2_HOME" && pwd` cd "$saveddir" # echo Using m2 at $M2_HOME fi # For Cygwin, ensure paths are in UNIX format before anything is touched if $cygwin ; then [ -n "$M2_HOME" ] && M2_HOME=`cygpath --unix "$M2_HOME"` [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` [ -n "$CLASSPATH" ] && CLASSPATH=`cygpath --path --unix "$CLASSPATH"` fi # For Mingw, ensure paths are in UNIX format before anything is touched if $mingw ; then [ -n "$M2_HOME" ] && M2_HOME="`(cd "$M2_HOME"; pwd)`" [ -n "$JAVA_HOME" ] && JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" fi if [ -z "$JAVA_HOME" ]; then javaExecutable="`which javac`" if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then # readlink(1) is not available as standard on Solaris 10. readLink=`which readlink` if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then if $darwin ; then javaHome="`dirname \"$javaExecutable\"`" javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" else javaExecutable="`readlink -f \"$javaExecutable\"`" fi javaHome="`dirname \"$javaExecutable\"`" javaHome=`expr "$javaHome" : '\(.*\)/bin'` JAVA_HOME="$javaHome" export JAVA_HOME fi fi fi if [ -z "$JAVACMD" ] ; then if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi else JAVACMD="`\\unset -f command; \\command -v java`" fi fi if [ ! -x "$JAVACMD" ] ; then echo "Error: JAVA_HOME is not defined correctly." >&2 echo " We cannot execute $JAVACMD" >&2 exit 1 fi if [ -z "$JAVA_HOME" ] ; then echo "Warning: JAVA_HOME environment variable is not set." fi CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher # traverses directory structure from process work directory to filesystem root # first directory with .mvn subdirectory is considered project base directory find_maven_basedir() { if [ -z "$1" ] then echo "Path not specified to find_maven_basedir" return 1 fi basedir="$1" wdir="$1" while [ "$wdir" != '/' ] ; do if [ -d "$wdir"/.mvn ] ; then basedir=$wdir break fi # workaround for JBEAP-8937 (on Solaris 10/Sparc) if [ -d "${wdir}" ]; then wdir=`cd "$wdir/.."; pwd` fi # end of workaround done echo "${basedir}" } # concatenates all lines of a file concat_lines() { if [ -f "$1" ]; then echo "$(tr -s '\n' ' ' < "$1")" fi } BASE_DIR=`find_maven_basedir "$(pwd)"` if [ -z "$BASE_DIR" ]; then exit 1; fi ########################################################################################## # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central # This allows using the maven wrapper in projects that prohibit checking in binary data. ########################################################################################## if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then if [ "$MVNW_VERBOSE" = true ]; then echo "Found .mvn/wrapper/maven-wrapper.jar" fi else if [ "$MVNW_VERBOSE" = true ]; then echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." fi if [ -n "$MVNW_REPOURL" ]; then jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" else jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" fi while IFS="=" read key value; do case "$key" in (wrapperUrl) jarUrl="$value"; break ;; esac done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" if [ "$MVNW_VERBOSE" = true ]; then echo "Downloading from: $jarUrl" fi wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" if $cygwin; then wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` fi if command -v wget > /dev/null; then if [ "$MVNW_VERBOSE" = true ]; then echo "Found wget ... using wget" fi if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" else wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" fi elif command -v curl > /dev/null; then if [ "$MVNW_VERBOSE" = true ]; then echo "Found curl ... using curl" fi if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then curl -o "$wrapperJarPath" "$jarUrl" -f else curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f fi else if [ "$MVNW_VERBOSE" = true ]; then echo "Falling back to using Java to download" fi javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" # For Cygwin, switch paths to Windows format before running javac if $cygwin; then javaClass=`cygpath --path --windows "$javaClass"` fi if [ -e "$javaClass" ]; then if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then if [ "$MVNW_VERBOSE" = true ]; then echo " - Compiling MavenWrapperDownloader.java ..." fi # Compiling the Java class ("$JAVA_HOME/bin/javac" "$javaClass") fi if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then # Running the downloader if [ "$MVNW_VERBOSE" = true ]; then echo " - Running MavenWrapperDownloader.java ..." fi ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") fi fi fi fi ########################################################################################## # End of extension ########################################################################################## export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} if [ "$MVNW_VERBOSE" = true ]; then echo $MAVEN_PROJECTBASEDIR fi MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" # For Cygwin, switch paths to Windows format before running java if $cygwin; then [ -n "$M2_HOME" ] && M2_HOME=`cygpath --path --windows "$M2_HOME"` [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` [ -n "$CLASSPATH" ] && CLASSPATH=`cygpath --path --windows "$CLASSPATH"` [ -n "$MAVEN_PROJECTBASEDIR" ] && MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` fi # Provide a "standardized" way to retrieve the CLI args that will # work with both Windows and non-Windows executions. MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" export MAVEN_CMD_LINE_ARGS WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain exec "$JAVACMD" \ $MAVEN_OPTS \ $MAVEN_DEBUG_OPTS \ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ "-Dmaven.home=${M2_HOME}" \ "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" ================================================ FILE: mvnw.cmd ================================================ @REM ---------------------------------------------------------------------------- @REM Licensed to the Apache Software Foundation (ASF) under one @REM or more contributor license agreements. See the NOTICE file @REM distributed with this work for additional information @REM regarding copyright ownership. The ASF licenses this file @REM to you under the Apache License, Version 2.0 (the @REM "License"); you may not use this file except in compliance @REM with the License. You may obtain a copy of the License at @REM @REM https://www.apache.org/licenses/LICENSE-2.0 @REM @REM Unless required by applicable law or agreed to in writing, @REM software distributed under the License is distributed on an @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @REM KIND, either express or implied. See the License for the @REM specific language governing permissions and limitations @REM under the License. @REM ---------------------------------------------------------------------------- @REM ---------------------------------------------------------------------------- @REM Maven Start Up Batch script @REM @REM Required ENV vars: @REM JAVA_HOME - location of a JDK home dir @REM @REM Optional ENV vars @REM M2_HOME - location of maven2's installed home dir @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven @REM e.g. to debug Maven itself, use @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files @REM ---------------------------------------------------------------------------- @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' @echo off @REM set title of command window title %0 @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% @REM set %HOME% to equivalent of $HOME if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") @REM Execute a user defined script before this one if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre @REM check for pre script, once with legacy .bat ending and once with .cmd ending if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* :skipRcPre @setlocal set ERROR_CODE=0 @REM To isolate internal variables from possible post scripts, we use another setlocal @setlocal @REM ==== START VALIDATION ==== if not "%JAVA_HOME%" == "" goto OkJHome echo. echo Error: JAVA_HOME not found in your environment. >&2 echo Please set the JAVA_HOME variable in your environment to match the >&2 echo location of your Java installation. >&2 echo. goto error :OkJHome if exist "%JAVA_HOME%\bin\java.exe" goto init echo. echo Error: JAVA_HOME is set to an invalid directory. >&2 echo JAVA_HOME = "%JAVA_HOME%" >&2 echo Please set the JAVA_HOME variable in your environment to match the >&2 echo location of your Java installation. >&2 echo. goto error @REM ==== END VALIDATION ==== :init @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". @REM Fallback to current working directory if not found. set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir set EXEC_DIR=%CD% set WDIR=%EXEC_DIR% :findBaseDir IF EXIST "%WDIR%"\.mvn goto baseDirFound cd .. IF "%WDIR%"=="%CD%" goto baseDirNotFound set WDIR=%CD% goto findBaseDir :baseDirFound set MAVEN_PROJECTBASEDIR=%WDIR% cd "%EXEC_DIR%" goto endDetectBaseDir :baseDirNotFound set MAVEN_PROJECTBASEDIR=%EXEC_DIR% cd "%EXEC_DIR%" :endDetectBaseDir IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig @setlocal EnableExtensions EnableDelayedExpansion for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% :endReadAdditionalConfig SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B ) @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central @REM This allows using the maven wrapper in projects that prohibit checking in binary data. if exist %WRAPPER_JAR% ( if "%MVNW_VERBOSE%" == "true" ( echo Found %WRAPPER_JAR% ) ) else ( if not "%MVNW_REPOURL%" == "" ( SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" ) if "%MVNW_VERBOSE%" == "true" ( echo Couldn't find %WRAPPER_JAR%, downloading it ... echo Downloading from: %DOWNLOAD_URL% ) powershell -Command "&{"^ "$webclient = new-object System.Net.WebClient;"^ "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ "}"^ "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ "}" if "%MVNW_VERBOSE%" == "true" ( echo Finished downloading %WRAPPER_JAR% ) ) @REM End of extension @REM Provide a "standardized" way to retrieve the CLI args that will @REM work with both Windows and non-Windows executions. set MAVEN_CMD_LINE_ARGS=%* %MAVEN_JAVA_EXE% ^ %JVM_CONFIG_MAVEN_PROPS% ^ %MAVEN_OPTS% ^ %MAVEN_DEBUG_OPTS% ^ -classpath %WRAPPER_JAR% ^ "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* if ERRORLEVEL 1 goto error goto end :error set ERROR_CODE=1 :end @endlocal & set ERROR_CODE=%ERROR_CODE% if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost @REM check for post script, once with legacy .bat ending and once with .cmd ending if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" :skipRcPost @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' if "%MAVEN_BATCH_PAUSE%"=="on" pause if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% cmd /C exit /B %ERROR_CODE% ================================================ FILE: pom.xml ================================================ 4.0.0 org.springframework.boot spring-boot-starter-parent 3.0.6 com.okta.developer jugtours 0.0.1-SNAPSHOT jugtours Demo project for Spring Boot 17 1.12.1 v18.16.0 9.6.5 org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-validation com.okta.spring okta-spring-boot-starter 3.0.3 com.h2database h2 runtime org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test spring-boot:run org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok dev true dev prod maven-resources-plugin copy-resources process-classes copy-resources ${basedir}/target/classes/static app/build com.github.eirslett frontend-maven-plugin ${frontend-maven-plugin.version} app install node install-node-and-npm ${node.version} ${npm.version} npm install npm generate-resources npm test npm test test true npm build npm compile run build prod ================================================ FILE: src/main/java/com/okta/developer/jugtours/Initializer.java ================================================ package com.okta.developer.jugtours; import com.okta.developer.jugtours.model.Event; import com.okta.developer.jugtours.model.Group; import com.okta.developer.jugtours.model.GroupRepository; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import java.time.Instant; import java.util.Collections; import java.util.stream.Stream; @Component class Initializer implements CommandLineRunner { private final GroupRepository repository; public Initializer(GroupRepository repository) { this.repository = repository; } @Override public void run(String... strings) { Stream.of("Seattle JUG", "Denver JUG", "Dublin JUG", "London JUG").forEach(name -> repository.save(new Group(name)) ); Group djug = repository.findByName("Seattle JUG"); Event e = Event.builder().title("Micro Frontends for Java Developers") .description("JHipster now has microfrontend support!") .date(Instant.parse("2022-09-13T17:00:00.000Z")) .build(); djug.setEvents(Collections.singleton(e)); repository.save(djug); repository.findAll().forEach(System.out::println); } } ================================================ FILE: src/main/java/com/okta/developer/jugtours/JugtoursApplication.java ================================================ package com.okta.developer.jugtours; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class JugtoursApplication { public static void main(String[] args) { SpringApplication.run(JugtoursApplication.class, args); } } ================================================ FILE: src/main/java/com/okta/developer/jugtours/config/SecurityConfiguration.java ================================================ package com.okta.developer.jugtours.config; import com.okta.developer.jugtours.web.CookieCsrfFilter; import com.okta.developer.jugtours.web.SpaWebFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.SimpleSavedRequest; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @Configuration public class SecurityConfiguration { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authz) -> authz .requestMatchers("/", "/index.html", "/static/**", "/*.ico", "/*.json", "/*.png", "/api/user").permitAll() .anyRequest().authenticated() ) .csrf((csrf) -> csrf .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) // https://stackoverflow.com/a/74521360/65681 .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()) ) .addFilterAfter(new CookieCsrfFilter(), BasicAuthenticationFilter.class) .addFilterAfter(new SpaWebFilter(), BasicAuthenticationFilter.class) .oauth2Login(); return http.build(); } @Bean public RequestCache refererRequestCache() { return new HttpSessionRequestCache() { @Override public void saveRequest(HttpServletRequest request, HttpServletResponse response) { String referrer = request.getHeader("referer"); if (referrer == null) { referrer = request.getRequestURL().toString(); } request.getSession().setAttribute("SPRING_SECURITY_SAVED_REQUEST", new SimpleSavedRequest(referrer)); } }; } } ================================================ FILE: src/main/java/com/okta/developer/jugtours/model/Event.java ================================================ package com.okta.developer.jugtours.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.ManyToMany; import java.time.Instant; import java.util.Set; @Data @NoArgsConstructor @AllArgsConstructor @Builder @Entity public class Event { @Id @GeneratedValue private Long id; private Instant date; private String title; private String description; @ManyToMany private Set attendees; } ================================================ FILE: src/main/java/com/okta/developer/jugtours/model/Group.java ================================================ package com.okta.developer.jugtours.model; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import jakarta.persistence.*; import java.util.Set; @Data @NoArgsConstructor @RequiredArgsConstructor @Entity @Table(name = "user_group") public class Group { @Id @GeneratedValue private Long id; @NonNull private String name; private String address; private String city; private String stateOrProvince; private String country; private String postalCode; @ManyToOne(cascade = CascadeType.PERSIST) private User user; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Set events; } ================================================ FILE: src/main/java/com/okta/developer/jugtours/model/GroupRepository.java ================================================ package com.okta.developer.jugtours.model; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface GroupRepository extends JpaRepository { Group findByName(String name); List findAllByUserId(String id); } ================================================ FILE: src/main/java/com/okta/developer/jugtours/model/User.java ================================================ package com.okta.developer.jugtours.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; @Data @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "users") public class User { @Id private String id; private String name; private String email; } ================================================ FILE: src/main/java/com/okta/developer/jugtours/model/UserRepository.java ================================================ package com.okta.developer.jugtours.model; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { } ================================================ FILE: src/main/java/com/okta/developer/jugtours/web/CookieCsrfFilter.java ================================================ package com.okta.developer.jugtours.web; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; /** * Spring Security 6 doesn't set a XSRF-TOKEN cookie by default. * This solution is * * recommended by Spring Security. */ public class CookieCsrfFilter extends OncePerRequestFilter { /** * {@inheritDoc} */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); response.setHeader(csrfToken.getHeaderName(), csrfToken.getToken()); filterChain.doFilter(request, response); } } ================================================ FILE: src/main/java/com/okta/developer/jugtours/web/GroupController.java ================================================ package com.okta.developer.jugtours.web; import com.okta.developer.jugtours.model.Group; import com.okta.developer.jugtours.model.GroupRepository; import com.okta.developer.jugtours.model.User; import com.okta.developer.jugtours.model.UserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.web.bind.annotation.*; import jakarta.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.security.Principal; import java.util.Collection; import java.util.Map; import java.util.Optional; @RestController @RequestMapping("/api") class GroupController { private final Logger log = LoggerFactory.getLogger(GroupController.class); private GroupRepository groupRepository; private UserRepository userRepository; public GroupController(GroupRepository groupRepository, UserRepository userRepository) { this.groupRepository = groupRepository; this.userRepository = userRepository; } @GetMapping("/groups") Collection groups(Principal principal) { return groupRepository.findAllByUserId(principal.getName()); } @GetMapping("/group/{id}") ResponseEntity getGroup(@PathVariable Long id) { Optional group = groupRepository.findById(id); return group.map(response -> ResponseEntity.ok().body(response)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); } @PostMapping("/group") ResponseEntity createGroup(@Valid @RequestBody Group group, @AuthenticationPrincipal OAuth2User principal) throws URISyntaxException { log.info("Request to create group: {}", group); Map details = principal.getAttributes(); String userId = details.get("sub").toString(); // check to see if user already exists Optional user = userRepository.findById(userId); group.setUser(user.orElse(new User(userId, details.get("name").toString(), details.get("email").toString()))); Group result = groupRepository.save(group); return ResponseEntity.created(new URI("/api/group/" + result.getId())) .body(result); } @PutMapping("/group/{id}") ResponseEntity updateGroup(@Valid @RequestBody Group group) { log.info("Request to update group: {}", group); Group result = groupRepository.save(group); return ResponseEntity.ok().body(result); } @DeleteMapping("/group/{id}") public ResponseEntity deleteGroup(@PathVariable Long id) { log.info("Request to delete group: {}", id); groupRepository.deleteById(id); return ResponseEntity.ok().build(); } } ================================================ FILE: src/main/java/com/okta/developer/jugtours/web/SpaWebFilter.java ================================================ package com.okta.developer.jugtours.web; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; import java.security.Principal; public class SpaWebFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String path = request.getRequestURI(); Authentication user = SecurityContextHolder.getContext().getAuthentication(); if (user != null && !path.startsWith("/api") && !path.contains(".") && path.matches("/(.*)")) { request.getRequestDispatcher("/").forward(request, response); return; } filterChain.doFilter(request, response); } } ================================================ FILE: src/main/java/com/okta/developer/jugtours/web/UserController.java ================================================ package com.okta.developer.jugtours.web; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import jakarta.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; @RestController public class UserController { private final ClientRegistration registration; public UserController(ClientRegistrationRepository registrations) { this.registration = registrations.findByRegistrationId("okta"); } @GetMapping("/api/user") public ResponseEntity getUser(@AuthenticationPrincipal OAuth2User user) { if (user == null) { return new ResponseEntity<>("", HttpStatus.OK); } else { return ResponseEntity.ok().body(user.getAttributes()); } } @PostMapping("/api/logout") public ResponseEntity logout(HttpServletRequest request, @AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) { // send logout URL to client so they can initiate logout String logoutUrl = this.registration.getProviderDetails() .getConfigurationMetadata().get("end_session_endpoint").toString(); Map logoutDetails = new HashMap<>(); logoutDetails.put("logoutUrl", logoutUrl); logoutDetails.put("idToken", idToken.getTokenValue()); request.getSession(false).invalidate(); return ResponseEntity.ok().body(logoutDetails); } } ================================================ FILE: src/main/resources/application.properties ================================================ spring.profiles.active=@spring.profiles.active@ ================================================ FILE: src/test/java/com/okta/developer/jugtours/JugtoursApplicationTests.java ================================================ package com.okta.developer.jugtours; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class JugtoursApplicationTests { @Test void contextLoads() { } }