Skip to content

Commit

Permalink
Have tests pass offline
Browse files Browse the repository at this point in the history
  • Loading branch information
ch4mpy committed Nov 9, 2023
1 parent 8782f78 commit 15820ca
Show file tree
Hide file tree
Showing 17 changed files with 165 additions and 102 deletions.
12 changes: 0 additions & 12 deletions samples/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -163,18 +163,6 @@
</excludes>
</configuration>
<executions>
<execution>
<id>pre-integration-test</id>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>post-integration-test</id>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ com:
- /login/**
- /oauth2/**
- /bff/**
cors:
- path: /bff/**
allowed-origin-patterns:
- ${gateway-uri}
- https://localhost/
csrf: cookie-accessible-from-js
login-path: /ui/
post-login-redirect-path: /ui/
Expand All @@ -91,6 +96,11 @@ com:
- /actuator/health/readiness
- /actuator/health/liveness
- /favicon.ico
cors:
- path: /login-options
allowed-origin-patterns:
- ${gateway-uri}
- https://localhost/

logging:
level:
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,17 @@ com:
- /users/me
- /actuator/health/readiness
- /actuator/health/liveness
cors:
- path: /**
allowed-origin-patterns:
- ${gateway-uri}
- https://localhost/

logging:
level:
org:
springframework:
boot: DEBUG
boot: INFO
security: DEBUG

---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,17 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.test.web.servlet.MockMvc;

import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication;
import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcTestConf;

@SpringBootTest
@AutoConfigureMockMvc
@Import({ AddonsWebmvcTestConf.class })
class C4GreetingApiApplicationTests {

@Autowired
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
package com.c4soft.springaddons.tutorials;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
Expand All @@ -16,14 +12,10 @@
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
Expand All @@ -39,7 +31,7 @@

@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureWebTestClient
@Import(ReactiveClientApplicationTest.TestSecurityConf.class)
@Import(TestSecurityConf.class)
class ReactiveClientApplicationTest {
static final AnonymousAuthenticationToken ANONYMOUS =
new AnonymousAuthenticationToken("anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
Expand Down Expand Up @@ -71,15 +63,20 @@ void givenUserIsAuthenticated_whenGetIndex_thenIsOk(OidcLoginMutator identityMut
static Stream<OidcLoginMutator> identityMutators() {
Instant iat = Instant.now();
Instant exp = iat.plusSeconds(42);
return Stream.of(
SecurityMockServerConfigurers.mockOidcLogin().oidcUser(
new DefaultOidcUser(
List.of(new SimpleGrantedAuthority("NICE"), new SimpleGrantedAuthority("AUTHOR")),
new OidcIdToken("test.token", iat, exp, Map.of(JwtClaimNames.SUB, "ch4mp")))),
SecurityMockServerConfigurers.mockOidcLogin().oidcUser(
new DefaultOidcUser(
List.of(new SimpleGrantedAuthority("UNCLE"), new SimpleGrantedAuthority("SKIPPER")),
new OidcIdToken("test.token", iat, exp, Map.of(JwtClaimNames.SUB, "tonton-pirate")))));
return Stream
.of(
SecurityMockServerConfigurers
.mockOidcLogin()
.oidcUser(
new DefaultOidcUser(
List.of(new SimpleGrantedAuthority("NICE"), new SimpleGrantedAuthority("AUTHOR")),
new OidcIdToken("test.token", iat, exp, Map.of(JwtClaimNames.SUB, "ch4mp")))),
SecurityMockServerConfigurers
.mockOidcLogin()
.oidcUser(
new DefaultOidcUser(
List.of(new SimpleGrantedAuthority("UNCLE"), new SimpleGrantedAuthority("SKIPPER")),
new OidcIdToken("test.token", iat, exp, Map.of(JwtClaimNames.SUB, "tonton-pirate")))));
}

@ParameterizedTest
Expand Down Expand Up @@ -118,7 +115,12 @@ void givenUserIsAuthenticatedWithAnnotation_whenGetLogin_thenIsRedirected() thro

@Test
void givenUserIsAnonymous_whenGetNice_thenIsRedirected() throws Exception {
webTestClient.mutateWith(SecurityMockServerConfigurers.mockAuthentication(ANONYMOUS)).get().uri("/nice.html").exchange().expectStatus()
webTestClient
.mutateWith(SecurityMockServerConfigurers.mockAuthentication(ANONYMOUS))
.get()
.uri("/nice.html")
.exchange()
.expectStatus()
.is3xxRedirection();
}

Expand All @@ -130,8 +132,13 @@ void givenUserIsAnonymousAnnotation_whenGetNice_thenIsRedirected() throws Except

@Test
void givenUserIsNice_whenGetNice_thenIsOk() throws Exception {
webTestClient.mutateWith(SecurityMockServerConfigurers.mockOidcLogin().authorities(new SimpleGrantedAuthority("NICE"))).get().uri("/nice.html")
.exchange().expectStatus().isOk();
webTestClient
.mutateWith(SecurityMockServerConfigurers.mockOidcLogin().authorities(new SimpleGrantedAuthority("NICE")))
.get()
.uri("/nice.html")
.exchange()
.expectStatus()
.isOk();
}

@Test
Expand All @@ -150,15 +157,4 @@ void givenUserIsNotNice_whenGetNice_thenIsForbidden() throws Exception {
void givenUserIsNotNiceAnnotation_whenGetNice_thenIsForbidden() throws Exception {
webTestClient.get().uri("/nice.html").exchange().expectStatus().isForbidden();
}

@TestConfiguration
static class TestSecurityConf {
@Bean
InMemoryReactiveClientRegistrationRepository clientRegistrationRepository() {
final var clientRegistrationRepository = mock(InMemoryReactiveClientRegistrationRepository.class);
when(clientRegistrationRepository.iterator()).thenReturn(new ArrayList<ClientRegistration>().iterator());
when(clientRegistrationRepository.spliterator()).thenReturn(new ArrayList<ClientRegistration>().spliterator());
return clientRegistrationRepository;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.c4soft.springaddons.tutorials;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.ArrayList;

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;

import reactor.core.publisher.Mono;

@TestConfiguration
class TestSecurityConf {
@Bean
InMemoryReactiveClientRegistrationRepository clientRegistrationRepository() {
final var clientRegistrationRepository = mock(InMemoryReactiveClientRegistrationRepository.class);
when(clientRegistrationRepository.iterator()).thenReturn(new ArrayList<ClientRegistration>().iterator());
when(clientRegistrationRepository.spliterator()).thenReturn(new ArrayList<ClientRegistration>().spliterator());
when(clientRegistrationRepository.findByRegistrationId(anyString()))
.thenAnswer(
invocation -> Mono
.just(
ClientRegistration
.withRegistrationId(invocation.getArgument(0))
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.clientId(invocation.getArgument(0))
.redirectUri("http://localhost:8080/oauth2/code/%s".formatted(invocation.getArgument(0).toString()))
.authorizationUri("https://localhost:8443/auth")
.tokenUri("https://localhost:8443/token")
.build()));
return clientRegistrationRepository;
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
scheme: http
origins: ${scheme}://localhost:4200
keycloak-port: 8442
keycloak-issuer: https://oidc.c4-soft.com/auth/realms/master
keycloak-issuer: https://oidc.c4-soft.com/auth/realms/spring-addons
keycloak-secret: change-me
cognito-issuer: https://cognito-idp.us-west-2.amazonaws.com/us-west-2_RzhmgLwjl
cognito-secret: change-me
Expand All @@ -21,7 +21,7 @@ spring:
oauth2:
resourceserver:
opaquetoken:
client-id: spring-addons-confidential
client-id: spring-addons-bff
client-secret: ${keycloak-secret}
introspection-uri: ${keycloak-issuer}/protocol/openid-connect/token/introspect

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"ROLE_AUTHORIZED_PERSONNEL"
]
},
"iss": "https://oidc.c4-soft.com/auth/realms/master",
"iss": "https://oidc.c4-soft.com/auth/realms/spring-addons",
"sub": "oauth2|c4-soft|4dd56dbb-71ef-4fe2-9358-3ae3240a9e94",
"aud": [
"demo.c4-soft.com",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"PIRATE"
]
},
"iss": "https://oidc.c4-soft.com/auth/realms/master",
"iss": "https://oidc.c4-soft.com/auth/realms/spring-addons",
"sub": "oauth2|c4-soft|4dd56dbb-71ef-4fe2-9358-3ae3240a9e90",
"aud": [
"demo.c4-soft.com",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.RedirectView;
Expand Down Expand Up @@ -80,7 +81,7 @@ public String getGreeting(HttpServletRequest request, Authentication auth, Model
return "greet";
}

@GetMapping("/logout-idp")
@PostMapping("/logout-idp")
@PreAuthorize("isAuthenticated()")
public RedirectView logout(
@RequestParam("clientRegistrationId") String clientRegistrationId,
Expand All @@ -105,7 +106,7 @@ public RedirectView logout(
return new RedirectView(logoutUri);
}

@GetMapping("/bulk-logout-idps")
@PostMapping("/bulk-logout-idps")
@PreAuthorize("isAuthenticated()")
public RedirectView bulkLogout(HttpServletRequest request) {
final var authorizedClientIds = MultiTenantOAuth2PrincipalSupport.getAuthenticationsByClientRegistrationId(request.getSession()).entrySet().iterator();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,29 +1,21 @@
package com.c4soft.springaddons.tutorials;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.ArrayList;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
@Import(ServletClientApplicationTests.TestSecurityConf.class)
@Import(TestSecurityConf.class)
class ServletClientApplicationTests {

@Autowired
Expand Down Expand Up @@ -71,23 +63,13 @@ void givenUserIsAnonymous_whenGetNice_thenIsRedirected() throws Exception {

@Test
void givenUserIsNice_whenGetNice_thenIsOk() throws Exception {
mockMvc.perform(get("/nice.html").with(SecurityMockMvcRequestPostProcessors.oauth2Login().authorities(new SimpleGrantedAuthority("NICE"))))
mockMvc
.perform(get("/nice.html").with(SecurityMockMvcRequestPostProcessors.oauth2Login().authorities(new SimpleGrantedAuthority("NICE"))))
.andExpect(status().isOk());
}

@Test
void givenUserIsNotNice_whenGetNice_thenIsForbidden() throws Exception {
mockMvc.perform(get("/nice.html").with(SecurityMockMvcRequestPostProcessors.oauth2Login())).andExpect(status().isForbidden());
}

@TestConfiguration
static class TestSecurityConf {
@Bean
InMemoryClientRegistrationRepository clientRegistrationRepository() {
final var clientRegistrationRepository = mock(InMemoryClientRegistrationRepository.class);
when(clientRegistrationRepository.iterator()).thenReturn(new ArrayList<ClientRegistration>().iterator());
when(clientRegistrationRepository.spliterator()).thenReturn(new ArrayList<ClientRegistration>().spliterator());
return clientRegistrationRepository;
}
}
}
Loading

0 comments on commit 15820ca

Please sign in to comment.