├── src ├── main │ ├── resources │ │ └── application.properties │ └── java │ │ └── com │ │ └── okta │ │ └── developer │ │ └── jugtours │ │ ├── model │ │ ├── UserRepository.java │ │ ├── GroupRepository.java │ │ ├── User.java │ │ ├── Event.java │ │ └── Group.java │ │ ├── JugtoursApplication.java │ │ ├── web │ │ ├── CookieCsrfFilter.java │ │ ├── SpaWebFilter.java │ │ ├── UserController.java │ │ └── GroupController.java │ │ ├── Initializer.java │ │ └── config │ │ └── SecurityConfiguration.java └── test │ └── java │ └── com │ └── okta │ └── developer │ └── jugtours │ └── JugtoursApplicationTests.java ├── app ├── public │ ├── robots.txt │ ├── favicon.ico │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── index.html ├── src │ ├── setupTests.js │ ├── App.test.js │ ├── index.css │ ├── reportWebVitals.js │ ├── App.js │ ├── index.js │ ├── App.css │ ├── AppNavbar.js │ ├── Home.js │ ├── logo.svg │ ├── GroupList.js │ └── GroupEdit.js ├── .gitignore ├── package.json └── README.md ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── .gitignore ├── HELP.md ├── README.md ├── mvnw.cmd ├── pom.xml ├── mvnw ├── LICENSE └── demo.adoc /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.profiles.active=@spring.profiles.active@ 2 | -------------------------------------------------------------------------------- /app/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /app/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oktadev/okta-spring-boot-react-crud-example/HEAD/app/public/favicon.ico -------------------------------------------------------------------------------- /app/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oktadev/okta-spring-boot-react-crud-example/HEAD/app/public/logo192.png -------------------------------------------------------------------------------- /app/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oktadev/okta-spring-boot-react-crud-example/HEAD/app/public/logo512.png -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oktadev/okta-spring-boot-react-crud-example/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /src/main/java/com/okta/developer/jugtours/model/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.okta.developer.jugtours.model; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface UserRepository extends JpaRepository { 6 | } 7 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar 3 | -------------------------------------------------------------------------------- /app/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /app/src/App.test.js: -------------------------------------------------------------------------------- 1 | import { render, screen } from '@testing-library/react'; 2 | import App from './App'; 3 | 4 | test('renders loading...', () => { 5 | render(); 6 | const linkElement = screen.getByText(/loading/i); 7 | expect(linkElement).toBeInTheDocument(); 8 | }); 9 | -------------------------------------------------------------------------------- /src/test/java/com/okta/developer/jugtours/JugtoursApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.okta.developer.jugtours; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class JugtoursApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/okta/developer/jugtours/model/GroupRepository.java: -------------------------------------------------------------------------------- 1 | package com.okta.developer.jugtours.model; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | import java.util.List; 6 | 7 | public interface GroupRepository extends JpaRepository { 8 | Group findByName(String name); 9 | 10 | List findAllByUserId(String id); 11 | } 12 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | /node 14 | 15 | # misc 16 | .DS_Store 17 | .env.local 18 | .env.development.local 19 | .env.test.local 20 | .env.production.local 21 | 22 | npm-debug.log* 23 | yarn-debug.log* 24 | yarn-error.log* 25 | -------------------------------------------------------------------------------- /app/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /app/src/reportWebVitals.js: -------------------------------------------------------------------------------- 1 | const reportWebVitals = onPerfEntry => { 2 | if (onPerfEntry && onPerfEntry instanceof Function) { 3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 4 | getCLS(onPerfEntry); 5 | getFID(onPerfEntry); 6 | getFCP(onPerfEntry); 7 | getLCP(onPerfEntry); 8 | getTTFB(onPerfEntry); 9 | }); 10 | } 11 | }; 12 | 13 | export default reportWebVitals; 14 | -------------------------------------------------------------------------------- /src/main/java/com/okta/developer/jugtours/JugtoursApplication.java: -------------------------------------------------------------------------------- 1 | package com.okta.developer.jugtours; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class JugtoursApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(JugtoursApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.env 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /src/main/java/com/okta/developer/jugtours/model/User.java: -------------------------------------------------------------------------------- 1 | package com.okta.developer.jugtours.model; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | import jakarta.persistence.Entity; 8 | import jakarta.persistence.Id; 9 | import jakarta.persistence.Table; 10 | 11 | @Data 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | @Entity 15 | @Table(name = "users") 16 | public class User { 17 | 18 | @Id 19 | private String id; 20 | private String name; 21 | private String email; 22 | } 23 | -------------------------------------------------------------------------------- /app/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /app/src/App.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import './App.css'; 3 | import Home from './Home'; 4 | import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; 5 | import GroupList from './GroupList'; 6 | import GroupEdit from './GroupEdit'; 7 | 8 | const App = () => { 9 | return ( 10 | 11 | 12 | }/> 13 | }/> 14 | }/> 15 | 16 | 17 | ) 18 | } 19 | 20 | export default App; 21 | -------------------------------------------------------------------------------- /app/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom/client'; 3 | import './index.css'; 4 | import App from './App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | import 'bootstrap/dist/css/bootstrap.min.css'; 7 | import { CookiesProvider } from 'react-cookie'; 8 | 9 | const root = ReactDOM.createRoot(document.getElementById('root')); 10 | root.render( 11 | 12 | 13 | 14 | 15 | 16 | ); 17 | 18 | // If you want to start measuring performance in your app, pass a function 19 | // to log results (for example: reportWebVitals(console.log)) 20 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 21 | reportWebVitals(); 22 | -------------------------------------------------------------------------------- /src/main/java/com/okta/developer/jugtours/model/Event.java: -------------------------------------------------------------------------------- 1 | package com.okta.developer.jugtours.model; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import jakarta.persistence.Entity; 9 | import jakarta.persistence.GeneratedValue; 10 | import jakarta.persistence.Id; 11 | import jakarta.persistence.ManyToMany; 12 | 13 | import java.time.Instant; 14 | import java.util.Set; 15 | 16 | @Data 17 | @NoArgsConstructor 18 | @AllArgsConstructor 19 | @Builder 20 | @Entity 21 | public class Event { 22 | 23 | @Id 24 | @GeneratedValue 25 | private Long id; 26 | private Instant date; 27 | private String title; 28 | private String description; 29 | @ManyToMany 30 | private Set attendees; 31 | } 32 | -------------------------------------------------------------------------------- /app/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | 40 | nav + .container, nav + .container-fluid { 41 | margin-top: 20px; 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/okta/developer/jugtours/model/Group.java: -------------------------------------------------------------------------------- 1 | package com.okta.developer.jugtours.model; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | import lombok.NonNull; 6 | import lombok.RequiredArgsConstructor; 7 | 8 | import jakarta.persistence.*; 9 | 10 | import java.util.Set; 11 | 12 | @Data 13 | @NoArgsConstructor 14 | @RequiredArgsConstructor 15 | @Entity 16 | @Table(name = "user_group") 17 | public class Group { 18 | 19 | @Id 20 | @GeneratedValue 21 | private Long id; 22 | @NonNull 23 | private String name; 24 | private String address; 25 | private String city; 26 | private String stateOrProvince; 27 | private String country; 28 | private String postalCode; 29 | @ManyToOne(cascade = CascadeType.PERSIST) 30 | private User user; 31 | 32 | @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) 33 | private Set events; 34 | } 35 | -------------------------------------------------------------------------------- /app/src/AppNavbar.js: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | import { Collapse, Nav, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap'; 3 | import { Link } from 'react-router-dom'; 4 | 5 | const AppNavbar = () => { 6 | 7 | const [isOpen, setIsOpen] = useState(false); 8 | 9 | return ( 10 | 11 | Home 12 | { 13 | setIsOpen(!isOpen) 14 | }}/> 15 | 16 | 24 | 25 | 26 | ); 27 | }; 28 | 29 | export default AppNavbar; 30 | -------------------------------------------------------------------------------- /HELP.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | 3 | ### Reference Documentation 4 | For further reference, please consider the following sections: 5 | 6 | * [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) 7 | * [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/3.0.6/maven-plugin/reference/html/) 8 | * [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.0.6/maven-plugin/reference/html/#build-image) 9 | * [Spring Data JPA](https://docs.spring.io/spring-boot/docs/3.0.6/reference/htmlsingle/#data.sql.jpa-and-spring-data) 10 | * [Spring Web](https://docs.spring.io/spring-boot/docs/3.0.6/reference/htmlsingle/#web) 11 | 12 | ### Guides 13 | The following guides illustrate how to use some features concretely: 14 | 15 | * [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) 16 | * [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) 17 | * [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) 18 | * [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) 19 | 20 | -------------------------------------------------------------------------------- /app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "app", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^5.16.5", 7 | "@testing-library/react": "^13.4.0", 8 | "@testing-library/user-event": "^13.5.0", 9 | "bootstrap": "^5.2.3", 10 | "react": "^18.2.0", 11 | "react-cookie": "^4.1.1", 12 | "react-dom": "^18.2.0", 13 | "react-router-dom": "^6.10.0", 14 | "react-scripts": "5.0.1", 15 | "reactstrap": "^9.1.9", 16 | "web-vitals": "^2.1.4" 17 | }, 18 | "scripts": { 19 | "start": "react-scripts start", 20 | "build": "react-scripts build", 21 | "test": "react-scripts test", 22 | "eject": "react-scripts eject" 23 | }, 24 | "proxy": "http://localhost:8080", 25 | "eslintConfig": { 26 | "extends": [ 27 | "react-app", 28 | "react-app/jest" 29 | ] 30 | }, 31 | "browserslist": { 32 | "production": [ 33 | ">0.2%", 34 | "not dead", 35 | "not op_mini all" 36 | ], 37 | "development": [ 38 | "last 1 chrome version", 39 | "last 1 firefox version", 40 | "last 1 safari version" 41 | ] 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/okta/developer/jugtours/web/CookieCsrfFilter.java: -------------------------------------------------------------------------------- 1 | package com.okta.developer.jugtours.web; 2 | 3 | import jakarta.servlet.FilterChain; 4 | import jakarta.servlet.ServletException; 5 | import jakarta.servlet.http.HttpServletRequest; 6 | import jakarta.servlet.http.HttpServletResponse; 7 | import org.springframework.security.web.csrf.CsrfToken; 8 | import org.springframework.web.filter.OncePerRequestFilter; 9 | 10 | import java.io.IOException; 11 | 12 | /** 13 | * Spring Security 6 doesn't set a XSRF-TOKEN cookie by default. 14 | * This solution is 15 | * 16 | * recommended by Spring Security. 17 | */ 18 | public class CookieCsrfFilter extends OncePerRequestFilter { 19 | 20 | /** 21 | * {@inheritDoc} 22 | */ 23 | @Override 24 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 25 | FilterChain filterChain) throws ServletException, IOException { 26 | CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); 27 | response.setHeader(csrfToken.getHeaderName(), csrfToken.getToken()); 28 | filterChain.doFilter(request, response); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/okta/developer/jugtours/web/SpaWebFilter.java: -------------------------------------------------------------------------------- 1 | package com.okta.developer.jugtours.web; 2 | 3 | import jakarta.servlet.FilterChain; 4 | import jakarta.servlet.ServletException; 5 | import jakarta.servlet.http.HttpServletRequest; 6 | import jakarta.servlet.http.HttpServletResponse; 7 | import org.springframework.security.core.Authentication; 8 | import org.springframework.security.core.context.SecurityContextHolder; 9 | import org.springframework.security.oauth2.core.user.OAuth2User; 10 | import org.springframework.web.filter.OncePerRequestFilter; 11 | 12 | import java.io.IOException; 13 | import java.security.Principal; 14 | 15 | public class SpaWebFilter extends OncePerRequestFilter { 16 | 17 | @Override 18 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 19 | FilterChain filterChain) throws ServletException, IOException { 20 | String path = request.getRequestURI(); 21 | Authentication user = SecurityContextHolder.getContext().getAuthentication(); 22 | if (user != null && !path.startsWith("/api") && !path.contains(".") && path.matches("/(.*)")) { 23 | request.getRequestDispatcher("/").forward(request, response); 24 | return; 25 | } 26 | 27 | filterChain.doFilter(request, response); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/okta/developer/jugtours/Initializer.java: -------------------------------------------------------------------------------- 1 | package com.okta.developer.jugtours; 2 | 3 | import com.okta.developer.jugtours.model.Event; 4 | import com.okta.developer.jugtours.model.Group; 5 | import com.okta.developer.jugtours.model.GroupRepository; 6 | import org.springframework.boot.CommandLineRunner; 7 | import org.springframework.stereotype.Component; 8 | 9 | import java.time.Instant; 10 | import java.util.Collections; 11 | import java.util.stream.Stream; 12 | 13 | @Component 14 | class Initializer implements CommandLineRunner { 15 | 16 | private final GroupRepository repository; 17 | 18 | public Initializer(GroupRepository repository) { 19 | this.repository = repository; 20 | } 21 | 22 | @Override 23 | public void run(String... strings) { 24 | Stream.of("Seattle JUG", "Denver JUG", "Dublin JUG", 25 | "London JUG").forEach(name -> 26 | repository.save(new Group(name)) 27 | ); 28 | 29 | Group djug = repository.findByName("Seattle JUG"); 30 | Event e = Event.builder().title("Micro Frontends for Java Developers") 31 | .description("JHipster now has microfrontend support!") 32 | .date(Instant.parse("2022-09-13T17:00:00.000Z")) 33 | .build(); 34 | djug.setEvents(Collections.singleton(e)); 35 | repository.save(djug); 36 | 37 | repository.findAll().forEach(System.out::println); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /app/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/main/java/com/okta/developer/jugtours/web/UserController.java: -------------------------------------------------------------------------------- 1 | package com.okta.developer.jugtours.web; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.http.ResponseEntity; 5 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 6 | import org.springframework.security.oauth2.client.registration.ClientRegistration; 7 | import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; 8 | import org.springframework.security.oauth2.core.oidc.OidcIdToken; 9 | import org.springframework.security.oauth2.core.user.OAuth2User; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.PostMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import jakarta.servlet.http.HttpServletRequest; 15 | 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | @RestController 20 | public class UserController { 21 | private final ClientRegistration registration; 22 | 23 | public UserController(ClientRegistrationRepository registrations) { 24 | this.registration = registrations.findByRegistrationId("okta"); 25 | } 26 | 27 | @GetMapping("/api/user") 28 | public ResponseEntity getUser(@AuthenticationPrincipal OAuth2User user) { 29 | if (user == null) { 30 | return new ResponseEntity<>("", HttpStatus.OK); 31 | } else { 32 | return ResponseEntity.ok().body(user.getAttributes()); 33 | } 34 | } 35 | 36 | @PostMapping("/api/logout") 37 | public ResponseEntity logout(HttpServletRequest request, 38 | @AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) { 39 | // send logout URL to client so they can initiate logout 40 | String logoutUrl = this.registration.getProviderDetails() 41 | .getConfigurationMetadata().get("end_session_endpoint").toString(); 42 | 43 | Map logoutDetails = new HashMap<>(); 44 | logoutDetails.put("logoutUrl", logoutUrl); 45 | logoutDetails.put("idToken", idToken.getTokenValue()); 46 | request.getSession(false).invalidate(); 47 | return ResponseEntity.ok().body(logoutDetails); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /app/src/Home.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | import './App.css'; 3 | import AppNavbar from './AppNavbar'; 4 | import { Link } from 'react-router-dom'; 5 | import { Button, Container } from 'reactstrap'; 6 | import { useCookies } from 'react-cookie'; 7 | 8 | const Home = () => { 9 | 10 | const [authenticated, setAuthenticated] = useState(false); 11 | const [loading, setLoading] = useState(false); 12 | const [user, setUser] = useState(undefined); 13 | const [cookies] = useCookies(['XSRF-TOKEN']); // <.> 14 | 15 | useEffect(() => { 16 | setLoading(true); 17 | fetch('api/user', { credentials: 'include' }) // <.> 18 | .then(response => response.text()) 19 | .then(body => { 20 | if (body === '') { 21 | setAuthenticated(false); 22 | } else { 23 | setUser(JSON.parse(body)); 24 | setAuthenticated(true); 25 | } 26 | setLoading(false); 27 | }); 28 | }, [setAuthenticated, setLoading, setUser]) 29 | 30 | const login = () => { 31 | let port = (window.location.port ? ':' + window.location.port : ''); 32 | if (port === ':3000') { 33 | port = ':8080'; 34 | } 35 | window.location.href = `//${window.location.hostname}${port}/api/private`; 36 | } 37 | 38 | const logout = () => { 39 | fetch('/api/logout', { 40 | method: 'POST', credentials: 'include', 41 | headers: { 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'] } // <.> 42 | }) 43 | .then(res => res.json()) 44 | .then(response => { 45 | window.location.href = `${response.logoutUrl}?id_token_hint=${response.idToken}` 46 | + `&post_logout_redirect_uri=${window.location.origin}`; 47 | }); 48 | } 49 | 50 | const message = user ? 51 |

Welcome, {user.name}!

: 52 |

Please log in to manage your JUG Tour.

; 53 | 54 | const button = authenticated ? 55 |
56 | 57 |
58 | 59 |
: 60 | ; 61 | 62 | if (loading) { 63 | return

Loading...

; 64 | } 65 | 66 | return ( 67 |
68 | 69 | 70 | {message} 71 | {button} 72 | 73 |
74 | ); 75 | } 76 | 77 | export default Home; 78 | -------------------------------------------------------------------------------- /app/src/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/java/com/okta/developer/jugtours/config/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.okta.developer.jugtours.config; 2 | 3 | import com.okta.developer.jugtours.web.CookieCsrfFilter; 4 | import com.okta.developer.jugtours.web.SpaWebFilter; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 8 | import org.springframework.security.web.SecurityFilterChain; 9 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; 10 | import org.springframework.security.web.csrf.CookieCsrfTokenRepository; 11 | import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler; 12 | import org.springframework.security.web.savedrequest.HttpSessionRequestCache; 13 | import org.springframework.security.web.savedrequest.RequestCache; 14 | import org.springframework.security.web.savedrequest.SimpleSavedRequest; 15 | 16 | import jakarta.servlet.http.HttpServletRequest; 17 | import jakarta.servlet.http.HttpServletResponse; 18 | 19 | @Configuration 20 | public class SecurityConfiguration { 21 | 22 | @Bean 23 | public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { 24 | http 25 | .authorizeHttpRequests((authz) -> authz 26 | .requestMatchers("/", "/index.html", "/static/**", 27 | "/*.ico", "/*.json", "/*.png", "/api/user").permitAll() 28 | .anyRequest().authenticated() 29 | ) 30 | .csrf((csrf) -> csrf 31 | .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) 32 | // https://stackoverflow.com/a/74521360/65681 33 | .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()) 34 | ) 35 | .addFilterAfter(new CookieCsrfFilter(), BasicAuthenticationFilter.class) 36 | .addFilterAfter(new SpaWebFilter(), BasicAuthenticationFilter.class) 37 | .oauth2Login(); 38 | return http.build(); 39 | } 40 | 41 | @Bean 42 | public RequestCache refererRequestCache() { 43 | return new HttpSessionRequestCache() { 44 | @Override 45 | public void saveRequest(HttpServletRequest request, HttpServletResponse response) { 46 | String referrer = request.getHeader("referer"); 47 | if (referrer == null) { 48 | referrer = request.getRequestURL().toString(); 49 | } 50 | request.getSession().setAttribute("SPRING_SECURITY_SAVED_REQUEST", 51 | new SimpleSavedRequest(referrer)); 52 | 53 | } 54 | }; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /app/src/GroupList.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | import { Button, ButtonGroup, Container, Table } from 'reactstrap'; 3 | import AppNavbar from './AppNavbar'; 4 | import { Link } from 'react-router-dom'; 5 | import { useCookies } from 'react-cookie'; 6 | 7 | const GroupList = () => { 8 | 9 | const [groups, setGroups] = useState([]); 10 | const [loading, setLoading] = useState(false); 11 | const [cookies] = useCookies(['XSRF-TOKEN']); 12 | 13 | useEffect(() => { 14 | setLoading(true); 15 | 16 | fetch('api/groups') 17 | .then(response => response.json()) 18 | .then(data => { 19 | setGroups(data); 20 | setLoading(false); 21 | }) 22 | }, []); 23 | 24 | const remove = async (id) => { 25 | await fetch(`/api/group/${id}`, { 26 | method: 'DELETE', 27 | headers: { 28 | 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'], 29 | 'Accept': 'application/json', 30 | 'Content-Type': 'application/json' 31 | }, 32 | credentials: 'include' 33 | }).then(() => { 34 | let updatedGroups = [...groups].filter(i => i.id !== id); 35 | setGroups(updatedGroups); 36 | }); 37 | } 38 | 39 | if (loading) { 40 | return

Loading...

; 41 | } 42 | 43 | const groupList = groups.map(group => { 44 | const address = `${group.address || ''} ${group.city || ''} ${group.stateOrProvince || ''}`; 45 | return 46 | {group.name} 47 | {address} 48 | {group.events.map(event => { 49 | return
{new Intl.DateTimeFormat('en-US', { 50 | year: 'numeric', 51 | month: 'long', 52 | day: '2-digit' 53 | }).format(new Date(event.date))}: {event.title}
54 | })} 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | }); 63 | 64 | return ( 65 |
66 | 67 | 68 |
69 | 70 |
71 |

My JUG Tour

72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | {groupList} 83 | 84 |
NameLocationEventsActions
85 |
86 |
87 | ); 88 | }; 89 | 90 | export default GroupList; 91 | -------------------------------------------------------------------------------- /src/main/java/com/okta/developer/jugtours/web/GroupController.java: -------------------------------------------------------------------------------- 1 | package com.okta.developer.jugtours.web; 2 | 3 | import com.okta.developer.jugtours.model.Group; 4 | import com.okta.developer.jugtours.model.GroupRepository; 5 | import com.okta.developer.jugtours.model.User; 6 | import com.okta.developer.jugtours.model.UserRepository; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 11 | import org.springframework.http.ResponseEntity; 12 | import org.springframework.security.oauth2.core.user.OAuth2User; 13 | import org.springframework.web.bind.annotation.*; 14 | 15 | import jakarta.validation.Valid; 16 | 17 | import java.net.URI; 18 | import java.net.URISyntaxException; 19 | import java.security.Principal; 20 | import java.util.Collection; 21 | import java.util.Map; 22 | import java.util.Optional; 23 | 24 | @RestController 25 | @RequestMapping("/api") 26 | class GroupController { 27 | 28 | private final Logger log = LoggerFactory.getLogger(GroupController.class); 29 | private GroupRepository groupRepository; 30 | private UserRepository userRepository; 31 | 32 | public GroupController(GroupRepository groupRepository, UserRepository userRepository) { 33 | this.groupRepository = groupRepository; 34 | this.userRepository = userRepository; 35 | } 36 | 37 | @GetMapping("/groups") 38 | Collection groups(Principal principal) { 39 | return groupRepository.findAllByUserId(principal.getName()); 40 | } 41 | 42 | @GetMapping("/group/{id}") 43 | ResponseEntity getGroup(@PathVariable Long id) { 44 | Optional group = groupRepository.findById(id); 45 | return group.map(response -> ResponseEntity.ok().body(response)) 46 | .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); 47 | } 48 | 49 | @PostMapping("/group") 50 | ResponseEntity createGroup(@Valid @RequestBody Group group, 51 | @AuthenticationPrincipal OAuth2User principal) throws URISyntaxException { 52 | log.info("Request to create group: {}", group); 53 | Map details = principal.getAttributes(); 54 | String userId = details.get("sub").toString(); 55 | 56 | // check to see if user already exists 57 | Optional user = userRepository.findById(userId); 58 | group.setUser(user.orElse(new User(userId, 59 | details.get("name").toString(), details.get("email").toString()))); 60 | 61 | Group result = groupRepository.save(group); 62 | return ResponseEntity.created(new URI("/api/group/" + result.getId())) 63 | .body(result); 64 | } 65 | 66 | @PutMapping("/group/{id}") 67 | ResponseEntity updateGroup(@Valid @RequestBody Group group) { 68 | log.info("Request to update group: {}", group); 69 | Group result = groupRepository.save(group); 70 | return ResponseEntity.ok().body(result); 71 | } 72 | 73 | @DeleteMapping("/group/{id}") 74 | public ResponseEntity deleteGroup(@PathVariable Long id) { 75 | log.info("Request to delete group: {}", id); 76 | groupRepository.deleteById(id); 77 | return ResponseEntity.ok().build(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /app/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser. 13 | 14 | The page will reload when you make changes.\ 15 | You may also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can't go back!** 35 | 36 | 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. 37 | 38 | 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. 39 | 40 | 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. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | 48 | ### Code Splitting 49 | 50 | 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) 51 | 52 | ### Analyzing the Bundle Size 53 | 54 | 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) 55 | 56 | ### Making a Progressive Web App 57 | 58 | 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) 59 | 60 | ### Advanced Configuration 61 | 62 | 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) 63 | 64 | ### Deployment 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 67 | 68 | ### `npm run build` fails to minify 69 | 70 | 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) 71 | -------------------------------------------------------------------------------- /app/src/GroupEdit.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | import { Link, useNavigate, useParams } from 'react-router-dom'; 3 | import { Button, Container, Form, FormGroup, Input, Label } from 'reactstrap'; 4 | import AppNavbar from './AppNavbar'; 5 | import { useCookies } from 'react-cookie'; 6 | 7 | const GroupEdit = () => { 8 | const initialFormState = { 9 | name: '', 10 | address: '', 11 | city: '', 12 | stateOrProvince: '', 13 | country: '', 14 | postalCode: '' 15 | }; 16 | const [group, setGroup] = useState(initialFormState); 17 | const navigate = useNavigate(); 18 | const { id } = useParams(); 19 | const [cookies] = useCookies(['XSRF-TOKEN']); 20 | 21 | useEffect(() => { 22 | if (id !== 'new') { 23 | fetch(`/api/group/${id}`) 24 | .then(response => response.json()) 25 | .then(data => setGroup(data)); 26 | } 27 | }, [id, setGroup]); 28 | 29 | const handleChange = (event) => { 30 | const { name, value } = event.target 31 | 32 | setGroup({ ...group, [name]: value }) 33 | } 34 | 35 | const handleSubmit = async (event) => { 36 | event.preventDefault(); 37 | 38 | await fetch(`/api/group${group.id ? `/${group.id}` : ''}`, { 39 | method: (group.id) ? 'PUT' : 'POST', 40 | headers: { 41 | 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'], 42 | 'Accept': 'application/json', 43 | 'Content-Type': 'application/json' 44 | }, 45 | body: JSON.stringify(group), 46 | credentials: 'include' 47 | }); 48 | setGroup(initialFormState); 49 | navigate('/groups'); 50 | } 51 | 52 | const title =

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

; 53 | 54 | return (
55 | 56 | 57 | {title} 58 |
59 | 60 | 61 | 63 | 64 | 65 | 66 | 68 | 69 | 70 | 71 | 73 | 74 |
75 | 76 | 77 | 79 | 80 | 81 | 82 | 84 | 85 | 86 | 87 | 89 | 90 |
91 | 92 | {' '} 93 | 94 | 95 |
96 |
97 |
98 | ) 99 | }; 100 | 101 | export default GroupEdit; 102 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JUG Tours with Spring Boot and React 2 | 3 | This example app shows how to create a Spring Boot API and CRUD (create, read, update, and delete) its data with a React app. 4 | 5 | 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. 6 | 7 | **Prerequisites:** [Java 17](http://sdkman.io) and [Node.js 18+](https://nodejs.org/) 8 | 9 | > [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. 10 | 11 | * [Getting Started](#getting-started) 12 | * [Links](#links) 13 | * [Help](#help) 14 | * [License](#license) 15 | 16 | ## Getting Started 17 | 18 | To install this example application, run the following commands: 19 | 20 | ```bash 21 | git clone https://github.com/oktadev/okta-spring-boot-react-crud-example.git spring-react 22 | cd spring-react 23 | ``` 24 | 25 | This will get a copy of the project installed locally. 26 | 27 | ### Create an Application in Okta 28 | 29 | 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`. 30 | 31 | Then, run `okta apps create`. Select the default app name, or change it as you see fit. Choose **Web** and press **Enter**. 32 | 33 | 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. 34 | 35 | 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: 36 | 37 | ```shell 38 | Okta application configuration has been written to: 39 | /path/to/app/src/main/resources/application.properties 40 | ``` 41 | 42 | Open `src/main/resources/application.properties` to see the issuer and credentials for your app. 43 | 44 | ```properties 45 | okta.oauth2.issuer=https://dev-133337.okta.com/oauth2/default 46 | okta.oauth2.client-id=0oab8eb55Kb9jdMIr5d6 47 | okta.oauth2.client-secret=NEVER-SHOW-SECRETS 48 | ``` 49 | 50 | 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. 51 | 52 | Run `./mvnw spring-boot:run -Pprod` and log in to your app at `http://localhost:8080`. 53 | 54 | ### Use Auth0 for OpenID Connect 55 | 56 | If you'd rather use Auth0, that's possible too! First, you'll need to checkout the `auth0` branch of this repository. 57 | 58 | ```bash 59 | git clone -b auth0 https://github.com/oktadev/okta-spring-boot-react-crud-example.git spring-react 60 | cd spring-react 61 | ``` 62 | 63 | Then, install the [Auth0 CLI](https://github.com/auth0/auth0-cli) and run `auth0 login` in a terminal. 64 | 65 | Next, run `auth0 apps create` and specify the appropriate URLs: 66 | 67 | ```bash 68 | auth0 apps create \ 69 | --name "Spring Boot + React" \ 70 | --description "Spring Boot OIDC App" \ 71 | --type regular \ 72 | --callbacks http://localhost:8080/login/oauth2/code/okta \ 73 | --logout-urls http://localhost:3000,http://localhost:8080 \ 74 | --reveal-secrets 75 | ``` 76 | 77 | Modify your `src/main/resources/application.properties` to include your Auth0 issuer, client ID, and client secret. 78 | 79 | ```properties 80 | # make sure to include the trailing slash for the Auth0 issuer 81 | okta.oauth2.issuer=https:/// 82 | okta.oauth2.issuer.client-id= 83 | okta.oauth2.issuer.client-secret= 84 | ``` 85 | 86 | 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. 87 | 88 | Run `./mvnw spring-boot:run -Pprod` and log in to your app at `http://localhost:8080`. 89 | 90 | ## Links 91 | 92 | This example uses the following open source libraries: 93 | 94 | * [React](https://reactjs.org/) 95 | * [Spring Boot](https://spring.io/projects/spring-boot) 96 | * [Spring Security](https://spring.io/projects/spring-security) 97 | 98 | ## Help 99 | 100 | 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/). 101 | 102 | ## License 103 | 104 | Apache 2.0, see [LICENSE](LICENSE). 105 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 50 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 124 | 125 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% ^ 162 | %JVM_CONFIG_MAVEN_PROPS% ^ 163 | %MAVEN_OPTS% ^ 164 | %MAVEN_DEBUG_OPTS% ^ 165 | -classpath %WRAPPER_JAR% ^ 166 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 167 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 168 | if ERRORLEVEL 1 goto error 169 | goto end 170 | 171 | :error 172 | set ERROR_CODE=1 173 | 174 | :end 175 | @endlocal & set ERROR_CODE=%ERROR_CODE% 176 | 177 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 178 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 179 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 180 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 181 | :skipRcPost 182 | 183 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 184 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 185 | 186 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 187 | 188 | cmd /C exit /B %ERROR_CODE% 189 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 3.0.6 9 | 10 | 11 | com.okta.developer 12 | jugtours 13 | 0.0.1-SNAPSHOT 14 | jugtours 15 | Demo project for Spring Boot 16 | 17 | 17 18 | 1.12.1 19 | v18.16.0 20 | 9.6.5 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-data-jpa 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-validation 34 | 35 | 36 | com.okta.spring 37 | okta-spring-boot-starter 38 | 3.0.3 39 | 40 | 41 | com.h2database 42 | h2 43 | runtime 44 | 45 | 46 | org.projectlombok 47 | lombok 48 | true 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-test 53 | test 54 | 55 | 56 | 57 | 58 | spring-boot:run 59 | 60 | 61 | org.springframework.boot 62 | spring-boot-maven-plugin 63 | 64 | 65 | 66 | org.projectlombok 67 | lombok 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | dev 78 | 79 | true 80 | 81 | 82 | dev 83 | 84 | 85 | 86 | prod 87 | 88 | 89 | 90 | maven-resources-plugin 91 | 92 | 93 | copy-resources 94 | process-classes 95 | 96 | copy-resources 97 | 98 | 99 | ${basedir}/target/classes/static 100 | 101 | 102 | app/build 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | com.github.eirslett 111 | frontend-maven-plugin 112 | ${frontend-maven-plugin.version} 113 | 114 | app 115 | 116 | 117 | 118 | install node 119 | 120 | install-node-and-npm 121 | 122 | 123 | ${node.version} 124 | ${npm.version} 125 | 126 | 127 | 128 | npm install 129 | 130 | npm 131 | 132 | generate-resources 133 | 134 | 135 | npm test 136 | 137 | npm 138 | 139 | test 140 | 141 | test 142 | 143 | true 144 | 145 | 146 | 147 | 148 | npm build 149 | 150 | npm 151 | 152 | compile 153 | 154 | run build 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | prod 163 | 164 | 165 | 166 | 167 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /usr/local/etc/mavenrc ] ; then 40 | . /usr/local/etc/mavenrc 41 | fi 42 | 43 | if [ -f /etc/mavenrc ] ; then 44 | . /etc/mavenrc 45 | fi 46 | 47 | if [ -f "$HOME/.mavenrc" ] ; then 48 | . "$HOME/.mavenrc" 49 | fi 50 | 51 | fi 52 | 53 | # OS specific support. $var _must_ be set to either true or false. 54 | cygwin=false; 55 | darwin=false; 56 | mingw=false 57 | case "`uname`" in 58 | CYGWIN*) cygwin=true ;; 59 | MINGW*) mingw=true;; 60 | Darwin*) darwin=true 61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 63 | if [ -z "$JAVA_HOME" ]; then 64 | if [ -x "/usr/libexec/java_home" ]; then 65 | export JAVA_HOME="`/usr/libexec/java_home`" 66 | else 67 | export JAVA_HOME="/Library/Java/Home" 68 | fi 69 | fi 70 | ;; 71 | esac 72 | 73 | if [ -z "$JAVA_HOME" ] ; then 74 | if [ -r /etc/gentoo-release ] ; then 75 | JAVA_HOME=`java-config --jre-home` 76 | fi 77 | fi 78 | 79 | if [ -z "$M2_HOME" ] ; then 80 | ## resolve links - $0 may be a link to maven's home 81 | PRG="$0" 82 | 83 | # need this for relative symlinks 84 | while [ -h "$PRG" ] ; do 85 | ls=`ls -ld "$PRG"` 86 | link=`expr "$ls" : '.*-> \(.*\)$'` 87 | if expr "$link" : '/.*' > /dev/null; then 88 | PRG="$link" 89 | else 90 | PRG="`dirname "$PRG"`/$link" 91 | fi 92 | done 93 | 94 | saveddir=`pwd` 95 | 96 | M2_HOME=`dirname "$PRG"`/.. 97 | 98 | # make it fully qualified 99 | M2_HOME=`cd "$M2_HOME" && pwd` 100 | 101 | cd "$saveddir" 102 | # echo Using m2 at $M2_HOME 103 | fi 104 | 105 | # For Cygwin, ensure paths are in UNIX format before anything is touched 106 | if $cygwin ; then 107 | [ -n "$M2_HOME" ] && 108 | M2_HOME=`cygpath --unix "$M2_HOME"` 109 | [ -n "$JAVA_HOME" ] && 110 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 111 | [ -n "$CLASSPATH" ] && 112 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 113 | fi 114 | 115 | # For Mingw, ensure paths are in UNIX format before anything is touched 116 | if $mingw ; then 117 | [ -n "$M2_HOME" ] && 118 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 119 | [ -n "$JAVA_HOME" ] && 120 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 121 | fi 122 | 123 | if [ -z "$JAVA_HOME" ]; then 124 | javaExecutable="`which javac`" 125 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 126 | # readlink(1) is not available as standard on Solaris 10. 127 | readLink=`which readlink` 128 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 129 | if $darwin ; then 130 | javaHome="`dirname \"$javaExecutable\"`" 131 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 132 | else 133 | javaExecutable="`readlink -f \"$javaExecutable\"`" 134 | fi 135 | javaHome="`dirname \"$javaExecutable\"`" 136 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 137 | JAVA_HOME="$javaHome" 138 | export JAVA_HOME 139 | fi 140 | fi 141 | fi 142 | 143 | if [ -z "$JAVACMD" ] ; then 144 | if [ -n "$JAVA_HOME" ] ; then 145 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 146 | # IBM's JDK on AIX uses strange locations for the executables 147 | JAVACMD="$JAVA_HOME/jre/sh/java" 148 | else 149 | JAVACMD="$JAVA_HOME/bin/java" 150 | fi 151 | else 152 | JAVACMD="`\\unset -f command; \\command -v java`" 153 | fi 154 | fi 155 | 156 | if [ ! -x "$JAVACMD" ] ; then 157 | echo "Error: JAVA_HOME is not defined correctly." >&2 158 | echo " We cannot execute $JAVACMD" >&2 159 | exit 1 160 | fi 161 | 162 | if [ -z "$JAVA_HOME" ] ; then 163 | echo "Warning: JAVA_HOME environment variable is not set." 164 | fi 165 | 166 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 167 | 168 | # traverses directory structure from process work directory to filesystem root 169 | # first directory with .mvn subdirectory is considered project base directory 170 | find_maven_basedir() { 171 | 172 | if [ -z "$1" ] 173 | then 174 | echo "Path not specified to find_maven_basedir" 175 | return 1 176 | fi 177 | 178 | basedir="$1" 179 | wdir="$1" 180 | while [ "$wdir" != '/' ] ; do 181 | if [ -d "$wdir"/.mvn ] ; then 182 | basedir=$wdir 183 | break 184 | fi 185 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 186 | if [ -d "${wdir}" ]; then 187 | wdir=`cd "$wdir/.."; pwd` 188 | fi 189 | # end of workaround 190 | done 191 | echo "${basedir}" 192 | } 193 | 194 | # concatenates all lines of a file 195 | concat_lines() { 196 | if [ -f "$1" ]; then 197 | echo "$(tr -s '\n' ' ' < "$1")" 198 | fi 199 | } 200 | 201 | BASE_DIR=`find_maven_basedir "$(pwd)"` 202 | if [ -z "$BASE_DIR" ]; then 203 | exit 1; 204 | fi 205 | 206 | ########################################################################################## 207 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 208 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 209 | ########################################################################################## 210 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Found .mvn/wrapper/maven-wrapper.jar" 213 | fi 214 | else 215 | if [ "$MVNW_VERBOSE" = true ]; then 216 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 217 | fi 218 | if [ -n "$MVNW_REPOURL" ]; then 219 | jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 220 | else 221 | jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 222 | fi 223 | while IFS="=" read key value; do 224 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 225 | esac 226 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 227 | if [ "$MVNW_VERBOSE" = true ]; then 228 | echo "Downloading from: $jarUrl" 229 | fi 230 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 231 | if $cygwin; then 232 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 233 | fi 234 | 235 | if command -v wget > /dev/null; then 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Found wget ... using wget" 238 | fi 239 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 240 | wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 241 | else 242 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 243 | fi 244 | elif command -v curl > /dev/null; then 245 | if [ "$MVNW_VERBOSE" = true ]; then 246 | echo "Found curl ... using curl" 247 | fi 248 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 249 | curl -o "$wrapperJarPath" "$jarUrl" -f 250 | else 251 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 252 | fi 253 | 254 | else 255 | if [ "$MVNW_VERBOSE" = true ]; then 256 | echo "Falling back to using Java to download" 257 | fi 258 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 259 | # For Cygwin, switch paths to Windows format before running javac 260 | if $cygwin; then 261 | javaClass=`cygpath --path --windows "$javaClass"` 262 | fi 263 | if [ -e "$javaClass" ]; then 264 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 265 | if [ "$MVNW_VERBOSE" = true ]; then 266 | echo " - Compiling MavenWrapperDownloader.java ..." 267 | fi 268 | # Compiling the Java class 269 | ("$JAVA_HOME/bin/javac" "$javaClass") 270 | fi 271 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 272 | # Running the downloader 273 | if [ "$MVNW_VERBOSE" = true ]; then 274 | echo " - Running MavenWrapperDownloader.java ..." 275 | fi 276 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 277 | fi 278 | fi 279 | fi 280 | fi 281 | ########################################################################################## 282 | # End of extension 283 | ########################################################################################## 284 | 285 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 286 | if [ "$MVNW_VERBOSE" = true ]; then 287 | echo $MAVEN_PROJECTBASEDIR 288 | fi 289 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 290 | 291 | # For Cygwin, switch paths to Windows format before running java 292 | if $cygwin; then 293 | [ -n "$M2_HOME" ] && 294 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 295 | [ -n "$JAVA_HOME" ] && 296 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 297 | [ -n "$CLASSPATH" ] && 298 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 299 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 300 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 301 | fi 302 | 303 | # Provide a "standardized" way to retrieve the CLI args that will 304 | # work with both Windows and non-Windows executions. 305 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 306 | export MAVEN_CMD_LINE_ARGS 307 | 308 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 309 | 310 | exec "$JAVACMD" \ 311 | $MAVEN_OPTS \ 312 | $MAVEN_DEBUG_OPTS \ 313 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 314 | "-Dmaven.home=${M2_HOME}" \ 315 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 316 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 317 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018-Present Okta, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /demo.adoc: -------------------------------------------------------------------------------- 1 | :experimental: 2 | :commandkey: ⌘ 3 | :toc: macro 4 | :source-highlighter: highlight.js 5 | 6 | = Use React and Spring Boot to Build a Simple CRUD App 7 | 8 | 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. 9 | 10 | **Prerequisites**: 11 | 12 | - http://sdkman.io[Java 17] 13 | - https://nodejs.org/[Node 16] 14 | - https://github.com/okta/okta-cli[Okta CLI] 15 | 16 | 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]. 17 | 18 | toc::[] 19 | 20 | == Create an API app with Spring Boot 21 | 22 | . Navigate to https://start.spring.io[start.spring.io] and make the following selections: 23 | 24 | * **Project:** `Maven Project` 25 | * **Group:** `com.okta.developer` 26 | * **Artifact:** `jugtours` 27 | * **Dependencies**: `JPA`, `H2`, `Web`, `Lombok` 28 | 29 | . Click **Generate Project**, expand `jugtours.zip` after downloading, and open the project in your favorite IDE. 30 | 31 | === Add a JPA domain model 32 | 33 | . Create a `src/main/java/com/okta/developer/jugtours/model` directory and a `Group.java` class in it. [`sbr-group`] 34 | + 35 | .`Group.java` 36 | [%collapsible] 37 | ==== 38 | [source,java] 39 | ---- 40 | package com.okta.developer.jugtours.model; 41 | 42 | import lombok.Data; 43 | import lombok.NoArgsConstructor; 44 | import lombok.NonNull; 45 | import lombok.RequiredArgsConstructor; 46 | 47 | import jakarta.persistence.*; 48 | import java.util.Set; 49 | 50 | @Data 51 | @NoArgsConstructor 52 | @RequiredArgsConstructor 53 | @Entity 54 | @Table(name = "user_group") 55 | public class Group { 56 | 57 | @Id 58 | @GeneratedValue 59 | private Long id; 60 | @NonNull 61 | private String name; 62 | private String address; 63 | private String city; 64 | private String stateOrProvince; 65 | private String country; 66 | private String postalCode; 67 | @ManyToOne(cascade=CascadeType.PERSIST) 68 | private User user; 69 | 70 | @OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL) 71 | private Set events; 72 | } 73 | ---- 74 | ==== 75 | 76 | . Create an `Event.java` class in the same package. [`sbr-event`] 77 | + 78 | .`Event.java` 79 | [%collapsible] 80 | ==== 81 | [source,java] 82 | ---- 83 | package com.okta.developer.jugtours.model; 84 | 85 | import lombok.AllArgsConstructor; 86 | import lombok.Builder; 87 | import lombok.Data; 88 | import lombok.NoArgsConstructor; 89 | 90 | import jakarta.persistence.Entity; 91 | import jakarta.persistence.GeneratedValue; 92 | import jakarta.persistence.Id; 93 | import jakarta.persistence.ManyToMany; 94 | import java.time.Instant; 95 | import java.util.Set; 96 | 97 | @Data 98 | @NoArgsConstructor 99 | @AllArgsConstructor 100 | @Builder 101 | @Entity 102 | public class Event { 103 | 104 | @Id 105 | @GeneratedValue 106 | private Long id; 107 | private Instant date; 108 | private String title; 109 | private String description; 110 | @ManyToMany 111 | private Set attendees; 112 | } 113 | ---- 114 | ==== 115 | 116 | . And a `User.java` class. [`sbr-user`] 117 | + 118 | .`User.java` 119 | [%collapsible] 120 | ==== 121 | [source,java] 122 | ---- 123 | package com.okta.developer.jugtours.model; 124 | 125 | import lombok.AllArgsConstructor; 126 | import lombok.Data; 127 | import lombok.NoArgsConstructor; 128 | 129 | import jakarta.persistence.Entity; 130 | import jakarta.persistence.Id; 131 | import jakarta.persistence.Table; 132 | 133 | @Data 134 | @NoArgsConstructor 135 | @AllArgsConstructor 136 | @Entity 137 | @Table(name = "users") 138 | public class User { 139 | 140 | @Id 141 | private String id; 142 | private String name; 143 | private String email; 144 | } 145 | ---- 146 | ==== 147 | 148 | . Create a `GroupRepository.java` to manage the group entity. [`sbr-group-repo`] 149 | + 150 | .`GroupRepository.java` 151 | [%collapsible] 152 | ==== 153 | [source,java] 154 | ---- 155 | package com.okta.developer.jugtours.model; 156 | 157 | import org.springframework.data.jpa.repository.JpaRepository; 158 | 159 | import java.util.List; 160 | 161 | public interface GroupRepository extends JpaRepository { 162 | Group findByName(String name); 163 | } 164 | ---- 165 | ==== 166 | 167 | . To load some default data, create an `Initializer.java` class in the `com.okta.developer.jugtours` package. [`sbr-init`] 168 | + 169 | .`Initializer.java` 170 | [%collapsible] 171 | ==== 172 | [source,java] 173 | ---- 174 | package com.okta.developer.jugtours; 175 | 176 | import com.okta.developer.jugtours.model.Event; 177 | import com.okta.developer.jugtours.model.Group; 178 | import com.okta.developer.jugtours.model.GroupRepository; 179 | import org.springframework.boot.CommandLineRunner; 180 | import org.springframework.stereotype.Component; 181 | 182 | import java.time.Instant; 183 | import java.util.Collections; 184 | import java.util.stream.Stream; 185 | 186 | @Component 187 | class Initializer implements CommandLineRunner { 188 | 189 | private final GroupRepository repository; 190 | 191 | public Initializer(GroupRepository repository) { 192 | this.repository = repository; 193 | } 194 | 195 | @Override 196 | public void run(String... strings) { 197 | Stream.of("Seattle JUG", "Denver JUG", "Dublin JUG", 198 | "London JUG").forEach(name -> 199 | repository.save(new Group(name)) 200 | ); 201 | 202 | Group djug = repository.findByName("Seattle JUG"); 203 | Event e = Event.builder().title("Micro Frontends for Java Developers") 204 | .description("JHipster now has microfrontend support!") 205 | .date(Instant.parse("2022-09-13T17:00:00.000Z")) 206 | .build(); 207 | djug.setEvents(Collections.singleton(e)); 208 | repository.save(djug); 209 | 210 | repository.findAll().forEach(System.out::println); 211 | } 212 | } 213 | ---- 214 | ==== 215 | + 216 | 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. 217 | + 218 | . Start your app with `mvn spring-boot:run` and you should see groups and events being created. 219 | 220 | . Add a `GroupController.java` class (in `src/main/java/.../jugtours/web`) that allows you to CRUD groups. [`sbr-group-controller`] 221 | + 222 | .`GroupController.java` 223 | [%collapsible] 224 | ==== 225 | [source,java] 226 | ---- 227 | package com.okta.developer.jugtours.web; 228 | 229 | import com.okta.developer.jugtours.model.Group; 230 | import com.okta.developer.jugtours.model.GroupRepository; 231 | import org.slf4j.Logger; 232 | import org.slf4j.LoggerFactory; 233 | import org.springframework.http.HttpStatus; 234 | import org.springframework.http.ResponseEntity; 235 | import org.springframework.web.bind.annotation.*; 236 | 237 | import jakarta.validation.Valid; 238 | import java.net.URI; 239 | import java.net.URISyntaxException; 240 | import java.util.Collection; 241 | import java.util.Optional; 242 | 243 | @RestController 244 | @RequestMapping("/api") 245 | class GroupController { 246 | 247 | private final Logger log = LoggerFactory.getLogger(GroupController.class); 248 | private GroupRepository groupRepository; 249 | 250 | public GroupController(GroupRepository groupRepository) { 251 | this.groupRepository = groupRepository; 252 | } 253 | 254 | @GetMapping("/groups") 255 | Collection groups() { 256 | return groupRepository.findAll(); 257 | } 258 | 259 | @GetMapping("/group/{id}") 260 | ResponseEntity getGroup(@PathVariable Long id) { 261 | Optional group = groupRepository.findById(id); 262 | return group.map(response -> ResponseEntity.ok().body(response)) 263 | .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); 264 | } 265 | 266 | @PostMapping("/group") 267 | ResponseEntity createGroup(@Valid @RequestBody Group group) throws URISyntaxException { 268 | log.info("Request to create group: {}", group); 269 | Group result = groupRepository.save(group); 270 | return ResponseEntity.created(new URI("/api/group/" + result.getId())) 271 | .body(result); 272 | } 273 | 274 | @PutMapping("/group/{id}") 275 | ResponseEntity updateGroup(@Valid @RequestBody Group group) { 276 | log.info("Request to update group: {}", group); 277 | Group result = groupRepository.save(group); 278 | return ResponseEntity.ok().body(result); 279 | } 280 | 281 | @DeleteMapping("/group/{id}") 282 | public ResponseEntity deleteGroup(@PathVariable Long id) { 283 | log.info("Request to delete group: {}", id); 284 | groupRepository.deleteById(id); 285 | return ResponseEntity.ok().build(); 286 | } 287 | } 288 | ---- 289 | ==== 290 | 291 | . Add the following dependency to your `pom.xml` to fix compilation errors: 292 | + 293 | [source,xml] 294 | ---- 295 | 296 | org.springframework.boot 297 | spring-boot-starter-validation 298 | 299 | ---- 300 | 301 | . Restart the app and hit `http://localhost:8080/api/groups` with https://httpie.org[HTTPie] and you should see the list of groups. 302 | 303 | http :8080/api/groups 304 | 305 | . You can create, read, update, and delete groups with the following commands. 306 | + 307 | [source,shell] 308 | ---- 309 | http POST :8080/api/group name='Utah JUG' city='Salt Lake City' country=USA 310 | http :8080/api/group/5 311 | http PUT :8080/api/group/5 id=6 name='Utah JUG' address='On the slopes' 312 | http DELETE :8080/api/group/5 313 | ---- 314 | 315 | == Create a React UI with Create React App 316 | 317 | . Create a new project in the root directory with `npx` and Create React App. 318 | + 319 | [source,shell] 320 | ---- 321 | npx create-react-app@5 app 322 | ---- 323 | 324 | . After the app creation process completes, navigate into the `app` directory and install Bootstrap, cookie support for React, React Router, and Reactstrap. 325 | + 326 | [source,shell] 327 | ---- 328 | cd app 329 | npm i bootstrap@5 react-cookie@4 react-router-dom@6 reactstrap@9 330 | ---- 331 | 332 | . Add Bootstrap's CSS file as an import in `app/src/index.js`. 333 | + 334 | [source,js] 335 | ---- 336 | import 'bootstrap/dist/css/bootstrap.min.css'; 337 | ---- 338 | 339 | == Call your Spring Boot API and display the results 340 | 341 | . Modify `App.js` to use the following code that calls `/api/groups` and displays the list in the UI. [`sbr-app`] 342 | + 343 | .`app/src/App.js` 344 | [%collapsible] 345 | ==== 346 | [source,jsx] 347 | ---- 348 | import React, { useEffect, useState } from 'react'; 349 | import logo from './logo.svg'; 350 | import './App.css'; 351 | 352 | const App = () => { 353 | 354 | const [groups, setGroups] = useState([]); 355 | const [loading, setLoading] = useState(false); 356 | 357 | useEffect(() => { 358 | setLoading(true); 359 | 360 | fetch('api/groups') 361 | .then(response => response.json()) 362 | .then(data => { 363 | setGroups(data); 364 | setLoading(false); 365 | }) 366 | }, []); 367 | 368 | if (loading) { 369 | return

Loading...

; 370 | } 371 | 372 | return ( 373 |
374 |
375 | logo 376 |
377 |

JUG List

378 | {groups.map(group => 379 |
380 | {group.name} 381 |
382 | )} 383 |
384 |
385 |
386 | ); 387 | } 388 | 389 | export default App; 390 | ---- 391 | ==== 392 | 393 | . To proxy from `/api` to `http://localhost:8080/api`, add a proxy setting to `app/package.json`. 394 | + 395 | [source,json] 396 | ---- 397 | "scripts": {...}, 398 | "proxy": "http://localhost:8080", 399 | ---- 400 | 401 | . Make sure Spring Boot is running, then run `npm start` in your `app` directory. You should see the list of default groups. 402 | 403 | == Build a React `GroupList` component 404 | 405 | . 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`] 406 | + 407 | .`src/app/GroupList.js` 408 | [%collapsible] 409 | ==== 410 | [source,jsx] 411 | ---- 412 | import React, { useEffect, useState } from 'react'; 413 | import { Button, ButtonGroup, Container, Table } from 'reactstrap'; 414 | import AppNavbar from './AppNavbar'; 415 | import { Link } from 'react-router-dom'; 416 | 417 | const GroupList = () => { 418 | 419 | const [groups, setGroups] = useState([]); 420 | const [loading, setLoading] = useState(false); 421 | 422 | useEffect(() => { 423 | setLoading(true); 424 | 425 | fetch('api/groups') 426 | .then(response => response.json()) 427 | .then(data => { 428 | setGroups(data); 429 | setLoading(false); 430 | }) 431 | }, []); 432 | 433 | const remove = async (id) => { 434 | await fetch(`/api/group/${id}`, { 435 | method: 'DELETE', 436 | headers: { 437 | 'Accept': 'application/json', 438 | 'Content-Type': 'application/json' 439 | } 440 | }).then(() => { 441 | let updatedGroups = [...groups].filter(i => i.id !== id); 442 | setGroups(updatedGroups); 443 | }); 444 | } 445 | 446 | if (loading) { 447 | return

Loading...

; 448 | } 449 | 450 | const groupList = groups.map(group => { 451 | const address = `${group.address || ''} ${group.city || ''} ${group.stateOrProvince || ''}`; 452 | return 453 | {group.name} 454 | {address} 455 | {group.events.map(event => { 456 | return
{new Intl.DateTimeFormat('en-US', { 457 | year: 'numeric', 458 | month: 'long', 459 | day: '2-digit' 460 | }).format(new Date(event.date))}: {event.title}
461 | })} 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | }); 470 | 471 | return ( 472 |
473 | 474 | 475 |
476 | 477 |
478 |

My JUG Tour

479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | {groupList} 490 | 491 |
NameLocationEventsActions
492 |
493 |
494 | ); 495 | }; 496 | 497 | export default GroupList; 498 | ---- 499 | ==== 500 | 501 | . Create `AppNavbar.js` in the same directory to establish a common UI feature between components. [`sbr-navbar`] 502 | + 503 | .`src/app/AppNavbar.js` 504 | [%collapsible] 505 | ==== 506 | [source,jsx] 507 | ---- 508 | import React, { useState } from 'react'; 509 | import { Collapse, Nav, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap'; 510 | import { Link } from 'react-router-dom'; 511 | 512 | const AppNavbar = () => { 513 | 514 | const [isOpen, setIsOpen] = useState(false); 515 | 516 | return ( 517 | 518 | Home 519 | { setIsOpen(!isOpen) }}/> 520 | 521 | 529 | 530 | 531 | ); 532 | }; 533 | 534 | export default AppNavbar; 535 | ---- 536 | ==== 537 | 538 | . Create `Home.js` to serve as the landing page for your app. [`sbr-home`] 539 | + 540 | .`src/app/Home.js` 541 | [%collapsible] 542 | ==== 543 | [source,jsx] 544 | ---- 545 | import React from 'react'; 546 | import './App.css'; 547 | import AppNavbar from './AppNavbar'; 548 | import { Link } from 'react-router-dom'; 549 | import { Button, Container } from 'reactstrap'; 550 | 551 | const Home = () => { 552 | return ( 553 |
554 | 555 | 556 | 557 | 558 |
559 | ); 560 | } 561 | 562 | export default Home; 563 | ---- 564 | ==== 565 | 566 | . Also, change `App.js` to use React Router to navigate between components. [`sbr-app-router`] 567 | + 568 | .`src/app/App.js` 569 | [%collapsible] 570 | ==== 571 | [source,jsx] 572 | ---- 573 | import React from 'react'; 574 | import './App.css'; 575 | import Home from './Home'; 576 | import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; 577 | import GroupList from './GroupList'; 578 | 579 | const App = () => { 580 | return ( 581 | 582 | 583 | }/> 584 | }/> 585 | 586 | 587 | ) 588 | } 589 | 590 | export default App; 591 | ---- 592 | ==== 593 | 594 | . To make your UI a bit more spacious, add a top margin to Bootstrap's container classes in `App.css`. 595 | + 596 | [source,css] 597 | ---- 598 | nav + .container, nav + .container-fluid { 599 | margin-top: 20px; 600 | } 601 | ---- 602 | 603 | . Your React app should update itself as you make changes at `http://localhost:3000`. 604 | 605 | . Click on **Manage JUG Tour** and you should see a list of the default groups. 606 | 607 | == Add a React `GroupEdit` component 608 | 609 | . Create `GroupEdit.js` and use `useEffect()` to fetch the group resource with the ID from the URL. [`sbr-group-edit`] 610 | + 611 | .`app/src/GroupEdit.js` 612 | [%collapsible] 613 | ==== 614 | [source,jsx] 615 | ---- 616 | import React, { useEffect, useState } from 'react'; 617 | import { Link, useNavigate, useParams } from 'react-router-dom'; 618 | import { Button, Container, Form, FormGroup, Input, Label } from 'reactstrap'; 619 | import AppNavbar from './AppNavbar'; 620 | 621 | const GroupEdit = () => { 622 | const initialFormState = { 623 | name: '', 624 | address: '', 625 | city: '', 626 | stateOrProvince: '', 627 | country: '', 628 | postalCode: '' 629 | }; 630 | const [group, setGroup] = useState(initialFormState); 631 | const navigate = useNavigate(); 632 | const { id } = useParams(); 633 | 634 | useEffect(() => { 635 | if (id !== 'new') { 636 | fetch(`/api/group/${id}`) 637 | .then(response => response.json()) 638 | .then(data => setGroup(data)); 639 | } 640 | }, [id, setGroup]); 641 | 642 | const handleChange = (event) => { 643 | const { name, value } = event.target 644 | 645 | setGroup({ ...group, [name]: value }) 646 | } 647 | 648 | const handleSubmit = async (event) => { 649 | event.preventDefault(); 650 | 651 | await fetch('/api/group' + (group.id ? '/' + group.id : ''), { 652 | method: (group.id) ? 'PUT' : 'POST', 653 | headers: { 654 | 'Accept': 'application/json', 655 | 'Content-Type': 'application/json' 656 | }, 657 | body: JSON.stringify(group) 658 | }); 659 | setGroup(initialFormState); 660 | navigate('/groups'); 661 | } 662 | 663 | const title =

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

; 664 | 665 | return (
666 | 667 | 668 | {title} 669 |
670 | 671 | 672 | 674 | 675 | 676 | 677 | 679 | 680 | 681 | 682 | 684 | 685 |
686 | 687 | 688 | 690 | 691 | 692 | 693 | 695 | 696 | 697 | 698 | 700 | 701 |
702 | 703 | {' '} 704 | 705 | 706 |
707 |
708 |
709 | ) 710 | }; 711 | 712 | export default GroupEdit; 713 | ---- 714 | ==== 715 | 716 | . Modify `App.js` to import `GroupEdit` and specify a path to it. 717 | + 718 | [source,jsx] 719 | ---- 720 | import GroupEdit from './GroupEdit'; 721 | 722 | const App = () => { 723 | return ( 724 | 725 | 726 | ... 727 | }/> 728 | 729 | 730 | ) 731 | } 732 | ---- 733 | 734 | Now you should be able to add and edit groups! 735 | 736 | == Add Authentication with Auth0 737 | 738 | . Add the necessary Spring Security dependencies to do OIDC authentication. [`sbr-spring-oauth`] 739 | + 740 | [source,xml] 741 | ---- 742 | 743 | org.springframework.boot 744 | spring-boot-starter-security 745 | 746 | 747 | org.springframework.security 748 | spring-security-config 749 | 750 | 751 | org.springframework.security 752 | spring-security-oauth2-client 753 | 754 | 755 | org.springframework.security 756 | spring-security-oauth2-jose 757 | 758 | ---- 759 | + 760 | 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. 761 | 762 | . Install the https://github.com/auth0/auth0-cli[Auth0 CLI] and run `auth0 login` in a terminal. 763 | 764 | . 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**. 765 | 766 | . 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`] 767 | + 768 | [source,properties] 769 | ---- 770 | # make sure to include the trailing slash for the Auth0 issuer 771 | spring.security.oauth2.client.provider.auth0.issuer-uri=https:/// 772 | spring.security.oauth2.client.registration.auth0.client-id= 773 | spring.security.oauth2.client.registration.auth0.client-secret= 774 | spring.security.oauth2.client.registration.auth0.scope=openid,profile,email 775 | ---- 776 | + 777 | 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. 778 | 779 | == Add Authentication with Okta 780 | 781 | . Add the Okta Spring Boot starter to do OIDC authentication. 782 | + 783 | [source,xml] 784 | ---- 785 | 786 | com.okta.spring 787 | okta-spring-boot-starter 788 | 2.1.6 789 | 790 | ---- 791 | 792 | . 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**. 793 | + 794 | Select **Okta Spring Boot Starter**. Accept the default Redirect URI and use `\http://localhost:3000,http://localhost:8080` for the Logout Redirect URI. 795 | 796 | . After configuring Spring Security in the section below, update `UserController.java` to use `okta` in its constructor: 797 | + 798 | [source,java] 799 | ---- 800 | public UserController(ClientRegistrationRepository registrations) { 801 | this.registration = registrations.findByRegistrationId("okta"); 802 | } 803 | ---- 804 | 805 | . And update the `logout()` method to work with Okta: 806 | + 807 | [source,java] 808 | ---- 809 | @PostMapping("/api/logout") 810 | public ResponseEntity logout(HttpServletRequest request, 811 | @AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) { 812 | // send logout URL to client so they can initiate logout 813 | String logoutUrl = this.registration.getProviderDetails() 814 | .getConfigurationMetadata().get("end_session_endpoint").toString(); 815 | 816 | Map logoutDetails = new HashMap<>(); 817 | logoutDetails.put("logoutUrl", logoutUrl); 818 | logoutDetails.put("idToken", idToken.getTokenValue()); 819 | request.getSession(false).invalidate(); 820 | return ResponseEntity.ok().body(logoutDetails); 821 | } 822 | ---- 823 | 824 | . Update `Home.js` in the React project to use different parameters for the logout redirect: 825 | + 826 | [source,js] 827 | ---- 828 | window.location.href = `${response.logoutUrl}?id_token_hint=${response.idToken}` 829 | + `&post_logout_redirect_uri=${window.location.origin}`; 830 | ---- 831 | 832 | 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]. 833 | 834 | == Configure Spring Security for React and user identity 835 | 836 | . To make Spring Security React-friendly, create a `SecurityConfiguration.java` file in `src/main/java/.../jugtours/config`. [`sbr-security-config`] 837 | + 838 | ==== 839 | [source,java] 840 | ---- 841 | package com.okta.developer.jugtours.config; 842 | 843 | import com.okta.developer.jugtours.web.CookieCsrfFilter; 844 | import org.springframework.context.annotation.Bean; 845 | import org.springframework.context.annotation.Configuration; 846 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 847 | import org.springframework.security.web.SecurityFilterChain; 848 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; 849 | import org.springframework.security.web.context.SecurityContextHolderFilter; 850 | import org.springframework.security.web.csrf.CookieCsrfTokenRepository; 851 | import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler; 852 | import org.springframework.security.web.savedrequest.HttpSessionRequestCache; 853 | import org.springframework.security.web.savedrequest.RequestCache; 854 | import org.springframework.security.web.savedrequest.SimpleSavedRequest; 855 | 856 | import jakarta.servlet.http.HttpServletRequest; 857 | import jakarta.servlet.http.HttpServletResponse; 858 | 859 | import java.util.Enumeration; 860 | 861 | import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; 862 | 863 | @Configuration 864 | public class SecurityConfiguration { 865 | 866 | @Bean 867 | public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { 868 | http 869 | .authorizeHttpRequests((authz) -> authz 870 | .requestMatchers("/", "/index.html", "/static/**", 871 | "/*.ico", "/*.json", "/*.png", "/api/user").permitAll() // <.> 872 | .anyRequest().authenticated() 873 | ) 874 | .csrf((csrf) -> csrf 875 | .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) // <.> 876 | // https://stackoverflow.com/a/74521360/65681 877 | .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()) 878 | ) 879 | .addFilterAfter(new CookieCsrfFilter(), BasicAuthenticationFilter.class) // <.> 880 | .oauth2Login(); 881 | return http.build(); 882 | } 883 | 884 | @Bean 885 | public RequestCache refererRequestCache() { // <.> 886 | return new HttpSessionRequestCache() { 887 | @Override 888 | public void saveRequest(HttpServletRequest request, HttpServletResponse response) { 889 | String referrer = request.getHeader("referer"); // <.> 890 | if (referrer == null) { 891 | referrer = request.getRequestURL().toString(); 892 | } 893 | request.getSession().setAttribute("SPRING_SECURITY_SAVED_REQUEST", 894 | new SimpleSavedRequest(referrer)); 895 | 896 | } 897 | }; 898 | } 899 | } 900 | ---- 901 | . Define what URLs are allowed for anonymous users. 902 | . `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. 903 | . Spring Security 6 no longer sets a CSRF cookie for you. Add a filter to do it. 904 | . The `RequestCache` bean overrides the default request cache. 905 | . It saves the referrer header (misspelled `referer` in real life), so Spring Security can redirect back to it after authentication. 906 | ==== 907 | 908 | . Create `src/main/java/.../jugtours/web/CookieCsrfFilter.java` to set a CSRF cookie. [`sbr-csrf`] 909 | + 910 | .`CookieCsrfFilter.java` 911 | [%collapsible] 912 | ==== 913 | [source,java] 914 | ---- 915 | package com.okta.developer.jugtours.web; 916 | 917 | import jakarta.servlet.FilterChain; 918 | import jakarta.servlet.ServletException; 919 | import jakarta.servlet.http.HttpServletRequest; 920 | import jakarta.servlet.http.HttpServletResponse; 921 | import org.springframework.security.web.csrf.CsrfToken; 922 | import org.springframework.web.filter.OncePerRequestFilter; 923 | 924 | import java.io.IOException; 925 | 926 | /** 927 | * Spring Security 6 doesn't set a XSRF-TOKEN cookie by default. 928 | * This solution is 929 | * 930 | * recommended by Spring Security. 931 | */ 932 | public class CookieCsrfFilter extends OncePerRequestFilter { 933 | 934 | /** 935 | * {@inheritDoc} 936 | */ 937 | @Override 938 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 939 | FilterChain filterChain) throws ServletException, IOException { 940 | CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); 941 | response.setHeader(csrfToken.getHeaderName(), csrfToken.getToken()); 942 | filterChain.doFilter(request, response); 943 | } 944 | } 945 | ---- 946 | ==== 947 | 948 | . 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`] 949 | + 950 | .`UserController.java` 951 | [%collapsible] 952 | ==== 953 | [source,java] 954 | ---- 955 | package com.okta.developer.jugtours.web; 956 | 957 | import org.springframework.http.HttpStatus; 958 | import org.springframework.http.ResponseEntity; 959 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 960 | import org.springframework.security.oauth2.client.registration.ClientRegistration; 961 | import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; 962 | import org.springframework.security.oauth2.core.user.OAuth2User; 963 | import org.springframework.web.bind.annotation.GetMapping; 964 | import org.springframework.web.bind.annotation.PostMapping; 965 | import org.springframework.web.bind.annotation.RestController; 966 | 967 | import jakarta.servlet.http.HttpServletRequest; 968 | import java.util.HashMap; 969 | import java.util.Map; 970 | 971 | @RestController 972 | public class UserController { 973 | private ClientRegistration registration; 974 | 975 | public UserController(ClientRegistrationRepository registrations) { 976 | this.registration = registrations.findByRegistrationId("auth0"); 977 | } 978 | 979 | @GetMapping("/api/user") 980 | public ResponseEntity getUser(@AuthenticationPrincipal OAuth2User user) { 981 | if (user == null) { 982 | return new ResponseEntity<>("", HttpStatus.OK); 983 | } else { 984 | return ResponseEntity.ok().body(user.getAttributes()); 985 | } 986 | } 987 | 988 | @PostMapping("/api/logout") 989 | public ResponseEntity logout(HttpServletRequest request) { 990 | // send logout URL to client so they can initiate logout 991 | StringBuilder logoutUrl = new StringBuilder(); 992 | String issuerUri = this.registration.getProviderDetails().getIssuerUri(); 993 | logoutUrl.append(issuerUri.endsWith("/") ? issuerUri + "v2/logout" : issuerUri + "/v2/logout"); 994 | logoutUrl.append("?client_id=").append(this.registration.getClientId()); 995 | 996 | Map logoutDetails = new HashMap<>(); 997 | logoutDetails.put("logoutUrl", logoutUrl.toString()); 998 | request.getSession(false).invalidate(); 999 | return ResponseEntity.ok().body(logoutDetails); 1000 | } 1001 | } 1002 | ---- 1003 | ==== 1004 | 1005 | . 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`. 1006 | + 1007 | [source,java] 1008 | ---- 1009 | package com.okta.developer.jugtours.model; 1010 | 1011 | import org.springframework.data.jpa.repository.JpaRepository; 1012 | 1013 | public interface UserRepository extends JpaRepository { 1014 | } 1015 | ---- 1016 | 1017 | . Add a new `findAllByUserId(String id)` method to `GroupRepository.java`. 1018 | + 1019 | [source,java] 1020 | ---- 1021 | List findAllByUserId(String id); 1022 | ---- 1023 | 1024 | . 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. 1025 | + 1026 | [source,java] 1027 | ---- 1028 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 1029 | ... 1030 | 1031 | @GetMapping("/groups") 1032 | Collection groups(Principal principal) { 1033 | return groupRepository.findAllByUserId(principal.getName()); 1034 | } 1035 | ... 1036 | 1037 | @PostMapping("/group") 1038 | ResponseEntity createGroup(@Valid @RequestBody Group group, 1039 | @AuthenticationPrincipal OAuth2User principal) throws URISyntaxException { 1040 | log.info("Request to create group: {}", group); 1041 | Map details = principal.getAttributes(); 1042 | String userId = details.get("sub").toString(); 1043 | 1044 | // check to see if user already exists 1045 | Optional user = userRepository.findById(userId); 1046 | group.setUser(user.orElse(new User(userId, 1047 | details.get("name").toString(), details.get("email").toString()))); 1048 | 1049 | Group result = groupRepository.save(group); 1050 | return ResponseEntity.created(new URI("/api/group/" + result.getId())) 1051 | .body(result); 1052 | } 1053 | ---- 1054 | 1055 | == Modify React to handle CSRF and be identity-aware 1056 | 1057 | You'll need to make a few changes to your React components to make them identity-aware. 1058 | 1059 | . 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. 1060 | + 1061 | [source,jsx] 1062 | ---- 1063 | import { CookiesProvider } from 'react-cookie'; 1064 | 1065 | const root = ReactDOM.createRoot(document.getElementById('root')); 1066 | root.render( 1067 | 1068 | 1069 | 1070 | 1071 | 1072 | ); 1073 | ---- 1074 | 1075 | . 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`] 1076 | + 1077 | ==== 1078 | [source,jsx] 1079 | ---- 1080 | import React, { useEffect, useState } from 'react'; 1081 | import './App.css'; 1082 | import AppNavbar from './AppNavbar'; 1083 | import { Link } from 'react-router-dom'; 1084 | import { Button, Container } from 'reactstrap'; 1085 | import { useCookies } from 'react-cookie'; 1086 | 1087 | const Home = () => { 1088 | 1089 | const [authenticated, setAuthenticated] = useState(false); 1090 | const [loading, setLoading] = useState(false); 1091 | const [user, setUser] = useState(undefined); 1092 | const [cookies] = useCookies(['XSRF-TOKEN']); // <.> 1093 | 1094 | useEffect(() => { 1095 | setLoading(true); 1096 | fetch('api/user', { credentials: 'include' }) // <.> 1097 | .then(response => response.text()) 1098 | .then(body => { 1099 | if (body === '') { 1100 | setAuthenticated(false); 1101 | } else { 1102 | setUser(JSON.parse(body)); 1103 | setAuthenticated(true); 1104 | } 1105 | setLoading(false); 1106 | }); 1107 | }, [setAuthenticated, setLoading, setUser]) 1108 | 1109 | const login = () => { 1110 | let port = (window.location.port ? ':' + window.location.port : ''); 1111 | if (port === ':3000') { 1112 | port = ':8080'; 1113 | } 1114 | // redirect to a protected URL to trigger authentication 1115 | window.location.href = `//${window.location.hostname}${port}/api/private`; 1116 | } 1117 | 1118 | const logout = () => { 1119 | fetch('/api/logout', { 1120 | method: 'POST', credentials: 'include', 1121 | headers: { 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'] } // <.> 1122 | }) 1123 | .then(res => res.json()) 1124 | .then(response => { 1125 | window.location.href = `${response.logoutUrl}&returnTo=${window.location.origin}`; 1126 | }); 1127 | } 1128 | 1129 | const message = user ? 1130 |

Welcome, {user.name}!

: 1131 |

Please log in to manage your JUG Tour.

; 1132 | 1133 | const button = authenticated ? 1134 |
1135 | 1136 |
1137 | 1138 |
: 1139 | ; 1140 | 1141 | if (loading) { 1142 | return

Loading...

; 1143 | } 1144 | 1145 | return ( 1146 |
1147 | 1148 | 1149 | {message} 1150 | {button} 1151 | 1152 |
1153 | ); 1154 | } 1155 | 1156 | export default Home; 1157 | ---- 1158 | . `useCookies()` is used for access to cookies. Then you can fetch a cookie with `cookies['XSRF-TOKEN']`. 1159 | . 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. 1160 | . 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`. 1161 | ==== 1162 | 1163 | . Update `GroupList.js` to have similar changes. 1164 | + 1165 | [source,jsx] 1166 | ---- 1167 | import { useCookies } from 'react-cookie'; 1168 | 1169 | const GroupList = () => { 1170 | 1171 | ... 1172 | const [cookies] = useCookies(['XSRF-TOKEN']); 1173 | 1174 | ... 1175 | const remove = async (id) => { 1176 | await fetch(`/api/group/${id}`, { 1177 | method: 'DELETE', 1178 | headers: { 1179 | 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'], 1180 | 'Accept': 'application/json', 1181 | 'Content-Type': 'application/json' 1182 | }, 1183 | credentials: 'include' 1184 | }).then(() => { 1185 | let updatedGroups = [...groups].filter(i => i.id !== id); 1186 | setGroups(updatedGroups); 1187 | }); 1188 | } 1189 | ... 1190 | 1191 | return (...) 1192 | } 1193 | 1194 | export default GroupList; 1195 | ---- 1196 | 1197 | . Update `GroupEdit.js` too. 1198 | + 1199 | [source,jsx] 1200 | ---- 1201 | import { useCookies } from 'react-cookie'; 1202 | 1203 | const GroupEdit = () => { 1204 | 1205 | ... 1206 | const [cookies] = useCookies(['XSRF-TOKEN']); 1207 | 1208 | ... 1209 | const handleSubmit = async (event) => { 1210 | event.preventDefault(); 1211 | 1212 | await fetch(`/api/group${group.id ? `/${group.id}` : ''}`, { 1213 | method: group.id ? 'PUT' : 'POST', 1214 | headers: { 1215 | 'X-XSRF-TOKEN': cookies['XSRF-TOKEN'], 1216 | 'Accept': 'application/json', 1217 | 'Content-Type': 'application/json' 1218 | }, 1219 | body: JSON.stringify(group), 1220 | credentials: 'include' 1221 | }); 1222 | setGroup(initialFormState); 1223 | navigate('/groups'); 1224 | } 1225 | 1226 | ... 1227 | 1228 | return (...) 1229 | } 1230 | 1231 | export default GroupEdit; 1232 | ---- 1233 | 1234 | 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! 1235 | 1236 | == Configure Maven to build and package React with Spring Boot 1237 | 1238 | 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. 1239 | 1240 | . Add properties for versions and a `` section to your `pom.xml`. [`sbr-properties` and `sbr-profiles`] 1241 | + 1242 | .`pom.xml` 1243 | [%collapsible] 1244 | ==== 1245 | [source,xml] 1246 | ---- 1247 | 1248 | ... 1249 | 1.12.1 1250 | v16.18.1 1251 | v8.19.2 1252 | 1253 | 1254 | 1255 | 1256 | dev 1257 | 1258 | true 1259 | 1260 | 1261 | dev 1262 | 1263 | 1264 | 1265 | prod 1266 | 1267 | 1268 | 1269 | maven-resources-plugin 1270 | 1271 | 1272 | copy-resources 1273 | process-classes 1274 | 1275 | copy-resources 1276 | 1277 | 1278 | ${basedir}/target/classes/static 1279 | 1280 | 1281 | app/build 1282 | 1283 | 1284 | 1285 | 1286 | 1287 | 1288 | 1289 | com.github.eirslett 1290 | frontend-maven-plugin 1291 | ${frontend-maven-plugin.version} 1292 | 1293 | app 1294 | 1295 | 1296 | 1297 | install node 1298 | 1299 | install-node-and-npm 1300 | 1301 | 1302 | ${node.version} 1303 | ${npm.version} 1304 | 1305 | 1306 | 1307 | npm install 1308 | 1309 | npm 1310 | 1311 | generate-resources 1312 | 1313 | 1314 | npm test 1315 | 1316 | test 1317 | 1318 | test 1319 | 1320 | test 1321 | 1322 | true 1323 | 1324 | 1325 | 1326 | 1327 | npm build 1328 | 1329 | npm 1330 | 1331 | compile 1332 | 1333 | run build 1334 | 1335 | 1336 | 1337 | 1338 | 1339 | 1340 | 1341 | prod 1342 | 1343 | 1344 | 1345 | ---- 1346 | ==== 1347 | + 1348 | Add the active profile setting to `src/main/resources/application.properties`: 1349 | + 1350 | [source,properties] 1351 | ---- 1352 | spring.profiles.active=@spring.profiles.active@ 1353 | ---- 1354 | 1355 | . After adding this, you should be able to run `./mvnw spring-boot:run -Pprod` and see your app running on `http://localhost:8080`. 1356 | 1357 | . 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`] 1358 | + 1359 | .`SpaWebFilter.java` 1360 | [%collapsible] 1361 | ==== 1362 | [source,java] 1363 | ---- 1364 | package com.okta.developer.jugtours.web; 1365 | 1366 | import jakarta.servlet.FilterChain; 1367 | import jakarta.servlet.ServletException; 1368 | import jakarta.servlet.http.HttpServletRequest; 1369 | import jakarta.servlet.http.HttpServletResponse; 1370 | import org.springframework.security.core.Authentication; 1371 | import org.springframework.security.core.context.SecurityContextHolder; 1372 | import org.springframework.security.oauth2.core.user.OAuth2User; 1373 | import org.springframework.web.filter.OncePerRequestFilter; 1374 | 1375 | import java.io.IOException; 1376 | import java.security.Principal; 1377 | 1378 | public class SpaWebFilter extends OncePerRequestFilter { 1379 | 1380 | @Override 1381 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 1382 | FilterChain filterChain) throws ServletException, IOException { 1383 | String path = request.getRequestURI(); 1384 | Authentication user = SecurityContextHolder.getContext().getAuthentication(); 1385 | if (user != null && !path.startsWith("/api") && 1386 | !path.contains(".") && path.matches("/(.*)")) { 1387 | request.getRequestDispatcher("/").forward(request, response); 1388 | return; 1389 | } 1390 | 1391 | filterChain.doFilter(request, response); 1392 | } 1393 | } 1394 | ---- 1395 | ==== 1396 | 1397 | . And add it to `SecurityConfiguration.java`: 1398 | + 1399 | [source,java] 1400 | ---- 1401 | .addFilterAfter(new SpaWebFilter(), BasicAuthenticationFilter.class) 1402 | ---- 1403 | 1404 | . Now, if you restart and reload the page, everything will work as expected. 🤗 1405 | 1406 | == Giddyup with React and Spring Boot! 1407 | 1408 | I hope you enjoyed this screencast, and it helped you understand how to integrate React and Spring Boot securely. 1409 | 1410 | ⚛️ Find the code on GitHub: https://github.com/oktadev/okta-spring-boot-react-crud-example[@oktadev/okta-spring-boot-react-crud-example] 1411 | 1412 | 🍃 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] 1413 | --------------------------------------------------------------------------------