From 5867f4c5751aa025d49bcaf144a0999206d5e3e4 Mon Sep 17 00:00:00 2001 From: Solian21 Date: Sun, 18 Oct 2026 18:07:42 -0700 Subject: [PATCH 1/4] Adding in OAuth Dependicies and redoing the principal --- api/build.gradle | 1 + .../edu/csumb/cst438/api/SecurityConfig.java | 22 ++++++++++++++++++- api/src/main/resources/application.yaml | 6 +++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/api/build.gradle b/api/build.gradle index 2784c6d..edee5e1 100644 --- a/api/build.gradle +++ b/api/build.gradle @@ -32,6 +32,7 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-webmvc' implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:3.1.1' + implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server' runtimeOnly 'com.h2database:h2' runtimeOnly 'org.postgresql:postgresql' testImplementation 'org.springframework.boot:spring-boot-starter-actuator-test' diff --git a/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java b/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java index c34e866..d62bcd2 100644 --- a/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java +++ b/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java @@ -14,6 +14,7 @@ import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.web.servlet.HandlerExceptionResolver; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; /** * This class should limit specific API routes to admin only @@ -59,10 +60,29 @@ public SecurityFilterChain securityFilterChain( .requestMatchers(HttpMethod.PATCH, "/api/v1/users/{userid}").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/api/v1/users/{userid}").hasRole("ADMIN") .anyRequest().authenticated() + ) .exceptionHandling(ex -> ex .authenticationEntryPoint(entryPoint) - .accessDeniedHandler(deniedHandler)); + .accessDeniedHandler(deniedHandler)) + // Adding in OAuth + .oauth2ResourceServer(oauth2 -> + oauth2.jwt(jwt -> + jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())) + ); return http.build(); } + + /** + * This converts the Google JWT into a Spring authentication object + * The users email becmes the principal name + * This lets controllers use principal.getName() to identify the current user + * @return a JWT authentication converter that uses the email claim + */ + @Bean + public JwtAuthenticationConverter jwtAuthenticationConverter() { + JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); + converter.setPrincipalClaimName("email"); + return converter; + } } diff --git a/api/src/main/resources/application.yaml b/api/src/main/resources/application.yaml index d46cca5..7f33750 100644 --- a/api/src/main/resources/application.yaml +++ b/api/src/main/resources/application.yaml @@ -6,6 +6,12 @@ spring: mvc: problemdetails: enabled: true + security: + oauth2: + resourceserver: + jwt: + issuer-uri: https://accounts.google.com + audiences: ${GOOGLE_CLIENT_ID} datasource: url: ${DATABASE_URL} username: ${DB_USER} From 894fff8fc33c06dbd41a0a243e310f6aff371220 Mon Sep 17 00:00:00 2001 From: Solian21 Date: Sun, 18 Oct 2026 19:40:10 -0700 Subject: [PATCH 2/4] Fix JWT database role authorities and invalid token handling --- .../gradle-9.7.1-bin.zip.lck | 0 .../gradle-9.7.1-bin.zip.part | 0 .../edu/csumb/cst438/api/SecurityConfig.java | 50 ++++++++++++++++--- .../cst438/api/controller/UserController.java | 1 - .../cst438/api/MealPlanControllerTest.java | 15 ++++++ .../csumb/cst438/api/UserControllerTest.java | 39 +++++++++++++++ 6 files changed, 96 insertions(+), 9 deletions(-) create mode 100644 api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.lck create mode 100644 api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.part diff --git a/api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.lck b/api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.lck new file mode 100644 index 0000000..e69de29 diff --git a/api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.part b/api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.part new file mode 100644 index 0000000..e69de29 diff --git a/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java b/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java index d62bcd2..18e18bb 100644 --- a/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java +++ b/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java @@ -15,6 +15,14 @@ import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.repository.UserRepository; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; + +import java.util.ArrayList; +import java.util.Collection; /** * This class should limit specific API routes to admin only @@ -28,6 +36,7 @@ public class SecurityConfig { /** * This basically just states what routes can only be called by ADMIN + * * @param http http * @return http.build() * @throws Exception if there's an exception @@ -35,7 +44,7 @@ public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain( HttpSecurity http, - @Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver) throws Exception{ + @Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver, JwtAuthenticationConverter jwtAuthenticationConverter) throws Exception { AuthenticationEntryPoint entryPoint = (request, response, ex) -> { response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer"); resolver.resolveException(request, response, null, ex); @@ -66,23 +75,48 @@ public SecurityFilterChain securityFilterChain( .authenticationEntryPoint(entryPoint) .accessDeniedHandler(deniedHandler)) // Adding in OAuth - .oauth2ResourceServer(oauth2 -> - oauth2.jwt(jwt -> - jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())) + .oauth2ResourceServer(oauth2 -> oauth2 + // using the application's Problem Details response for invalid bearer tokens + .authenticationEntryPoint(entryPoint) + + // Converts valid JWTs and adds the user's database role + .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter)) ); return http.build(); } /** * This converts the Google JWT into a Spring authentication object - * The users email becmes the principal name + * The users email becomes the principal name * This lets controllers use principal.getName() to identify the current user - * @return a JWT authentication converter that uses the email claim + * it also laods the users database role and converts it into a spring authority + * + * @param userRepository repository used to load the authenticated user + * @return a JWT authentication converter using the email and database role */ @Bean - public JwtAuthenticationConverter jwtAuthenticationConverter() { + public JwtAuthenticationConverter jwtAuthenticationConverter(UserRepository userRepository) { + //Keeping the defualt atuhorities created from the token skope + JwtGrantedAuthoritiesConverter tokenAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); + //Using the google account email as the autehnticiated principal name + // and now contollers are able to retrieve it using principal.getName() converter.setPrincipalClaimName("email"); + converter.setJwtGrantedAuthoritiesConverter(jwt -> { + Collection authorities = new ArrayList<>(tokenAuthoritiesConverter.convert(jwt)); + String email = jwt.getClaimAsString("email"); + //This is what actually loads in the users current role from the data base + if (email != null) { + userRepository.findByEmail(email) + .map(User::getRole) + .filter(role -> role != null && !role.isBlank()) + .map(role -> new SimpleGrantedAuthority("ROLE_" + role)) + .ifPresent(authorities::add); + } + //return token authoriities and the database role authorities + return authorities; + }); + return converter; } -} +} \ No newline at end of file diff --git a/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java b/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java index c0c2d9c..d6c833b 100644 --- a/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java +++ b/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java @@ -8,7 +8,6 @@ import org.springframework.data.web.PagedModel; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; - import java.security.Principal; /** diff --git a/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java b/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java index 49c9ce9..77ae13f 100644 --- a/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java @@ -3,6 +3,7 @@ import edu.csumb.cst438.api.controller.MealPlanController; import edu.csumb.cst438.api.record.MealPlanResponse; import edu.csumb.cst438.api.service.MealPlanService; +import edu.csumb.cst438.api.repository.UserRepository; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; @@ -17,6 +18,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.web.server.ResponseStatusException; +import org.springframework.security.oauth2.jwt.JwtDecoder; import java.security.Principal; import java.time.LocalDate; @@ -30,6 +32,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + // TODO(#48): once Spring Security is on the classpath, use @WithMockUser("owner@example.com") // instead of .principal(...) and add a "no credentials -> 401 problem+json" test. @WebMvcTest(MealPlanController.class) @@ -46,6 +49,18 @@ public class MealPlanControllerTest { @MockitoBean private MealPlanService mealPlanService; + /** + * Mock repository used by SecurityConfig to load the authenticated user's database role + */ + @MockitoBean + private UserRepository userRepository; + + /** + * Mock Jwtdecoder used to simulate valid and invalid JWT tokens without contacting Google's athentication servers + */ + @MockitoBean + private JwtDecoder jwtDecoder; + private static MockHttpServletRequestBuilder json(MockHttpServletRequestBuilder request, String body) { return request.contentType(MediaType.APPLICATION_JSON).content(body); } diff --git a/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java b/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java index a6f1102..640704c 100644 --- a/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java @@ -9,6 +9,9 @@ import edu.csumb.cst438.api.entity.User; import edu.csumb.cst438.api.record.UserResponseDTO; import edu.csumb.cst438.api.service.UserService; +import edu.csumb.cst438.api.repository.UserRepository; + + import jakarta.persistence.EntityNotFoundException; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -20,6 +23,9 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.http.HttpHeaders; +import org.springframework.security.oauth2.jwt.BadJwtException; +import org.springframework.security.oauth2.jwt.JwtDecoder; import java.util.List; @@ -38,6 +44,18 @@ public class UserControllerTest { @MockitoBean private UserService userService; + /** + * Mock repository used by SecurityConfig to load the authenticated user's database role + */ + @MockitoBean + private UserRepository userRepository; + + /** + * Mock decoder used to simulate invalid JWT tokens + */ + @MockitoBean + private JwtDecoder jwtDecoder; + /** * Tests if GET /api/v1/users works with ADMIN role * @throws Exception if there is an exception @@ -154,6 +172,27 @@ void testGETUsersUnauthenticated() throws Exception{ .andExpect(jsonPath("$.instance").value("/api/v1/users")); } + /** + * Verifies that an invalid bearer token returns a 401 response with a problem details JSON bosy and the required WWW-Authenticate header + * @throws Exception if the MockMvc request fails + */ + @Test + void testInvalidBearerTokenReturnsProblemDetails() throws Exception { + when(jwtDecoder.decode("invalid-token")) + .thenThrow(new BadJwtException("Invalid bearer token")); + + mockMvc.perform(get("/api/v1/users") + .header(HttpHeaders.AUTHORIZATION, "Bearer invalid-token")) + .andExpect(status().isUnauthorized()) + .andExpect(content().contentTypeCompatibleWith( + MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(header().string( + HttpHeaders.WWW_AUTHENTICATE, "Bearer")) + .andExpect(jsonPath("$.title").value("Unauthorized")) + .andExpect(jsonPath("$.status").value(401)) + .andExpect(jsonPath("$.instance").value("/api/v1/users")); + } + /** * Tests if GET users works if a user does it * @throws Exception if there is an exception From dee9091f8968e9fee1789d2a1a8f774f3d1ef4eb Mon Sep 17 00:00:00 2001 From: Solian21 <143134407+Solian21@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:54:32 -0700 Subject: [PATCH 3/4] Delete api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.part --- .../1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.part | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.part diff --git a/api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.part b/api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.part deleted file mode 100644 index e69de29..0000000 From 30b9c47cea63e88d88152456be0e7b31bf133808 Mon Sep 17 00:00:00 2001 From: Solian21 <143134407+Solian21@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:55:06 -0700 Subject: [PATCH 4/4] Delete api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.lck --- .../1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.lck | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.lck diff --git a/api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.lck b/api/.gradle-user-home/wrapper/dists/gradle-9.7.1-bin/1w1c7tv4s851m17nbqdsro2tv/gradle-9.7.1-bin.zip.lck deleted file mode 100644 index e69de29..0000000