Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions api/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
60 changes: 57 additions & 3 deletions api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@
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;
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
Expand All @@ -27,14 +36,15 @@
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
*/
@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);
Expand All @@ -59,10 +69,54 @@ 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
// 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 becomes the principal name
* This lets controllers use principal.getName() to identify the current user
* 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(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<GrantedAuthority> 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;
Comment on lines +97 to +120

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The converter changes the principal name to email, but it never loads the user’s database role. The default converter derives permissions from token scopes; it does not turn a database ADMIN role into ROLE_ADMIN. Consequently, even a database administrator signing in with a valid Google token receives 403 from administrator endpoints. Load the matched user’s role and add the corresponding authority during authentication, as required by issue #50

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down
6 changes: 6 additions & 0 deletions api/src/main/resources/application.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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)
Expand All @@ -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);
}
Expand Down
39 changes: 39 additions & 0 deletions api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading