Skip to content

Commit

Permalink
Apply formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
marcusdacoregio committed Jan 17, 2024
1 parent 66e0ae2 commit fadbeb3
Show file tree
Hide file tree
Showing 35 changed files with 175 additions and 110 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ void messageWhenNotAuthenticatedThenError() {
RSocketRequester requester = this.requester.connectTcp("localhost", this.port).block();

assertThatThrownBy(() -> requester.route("message").data(Mono.empty()).retrieveMono(String.class).block())
.isNotNull();
.isNotNull();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ private WebTestClient createWebTestClientWithClientCertificate() throws KeyStore
// @formatter:on

HttpClient httpClient = HttpClient.create()
.secure((sslContextSpec) -> sslContextSpec.sslContext(sslContextBuilder));
.secure((sslContextSpec) -> sslContextSpec.sslContext(sslContextBuilder));
ClientHttpConnector httpConnector = new ReactorClientHttpConnector(httpClient);

// @formatter:off
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ public class MeController {

@GetMapping("/me")
public Mono<String> me() {
return ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication)
.map((authentication) -> "Hello, " + authentication.getName());
return ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.map((authentication) -> "Hello, " + authentication.getName());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ void publicMethod() {
@Test
void securedMethodNotAuthenticated() {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.service.secureMethod());
.isThrownBy(() -> this.service.secureMethod());
}

@Test
Expand All @@ -69,7 +69,7 @@ void securedMethodWrongRole() {
@Test
void securedClassNotAuthenticated() {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.securedService.secureMethod());
.isThrownBy(() -> this.securedService.secureMethod());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ public class DataSourceConfiguration {
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:org/springframework/security/core/userdetails/jdbc/users.ddl").build();
.addScript("classpath:org/springframework/security/core/userdetails/jdbc/users.ddl")
.build();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,16 @@ public class SecurityConfiguration {

@Bean
UserDetailsManager users(DataSource dataSource) {
UserDetails user = User.builder().username("user")
.password("{bcrypt}$2a$10$AiyMWI4UBLozgXq6itzyVuxrtofjcPzn/WS3fOrcqgzdax9jB7Io.").roles("USER").build();
UserDetails admin = User.builder().username("admin")
.password("{bcrypt}$2a$10$AiyMWI4UBLozgXq6itzyVuxrtofjcPzn/WS3fOrcqgzdax9jB7Io.").roles("USER", "ADMIN")
.build();
UserDetails user = User.builder()
.username("user")
.password("{bcrypt}$2a$10$AiyMWI4UBLozgXq6itzyVuxrtofjcPzn/WS3fOrcqgzdax9jB7Io.")
.roles("USER")
.build();
UserDetails admin = User.builder()
.username("admin")
.password("{bcrypt}$2a$10$AiyMWI4UBLozgXq6itzyVuxrtofjcPzn/WS3fOrcqgzdax9jB7Io.")
.roles("USER", "ADMIN")
.build();
JdbcUserDetailsManager users = new JdbcUserDetailsManager(dataSource);
users.createUser(user);
users.createUser(admin);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public class X509Tests {
void notCertificateThenSslHandshakeException() {
RestTemplate rest = new RestTemplate();
assertThatCode(() -> rest.getForEntity(getServerUrl(), String.class))
.hasCauseInstanceOf(SSLHandshakeException.class);
.hasCauseInstanceOf(SSLHandshakeException.class);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,11 @@ public class Saml2JavaConfigurationITests {
@BeforeEach
void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext)
.apply(SecurityMockMvcConfigurers.springSecurity()).build();
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
this.webClient = MockMvcWebClientBuilder.mockMvcSetup(this.mvc)
.withDelegate(new LocalHostWebClient(this.environment)).build();
.withDelegate(new LocalHostWebClient(this.environment))
.build();
this.webClient.getCookieManager().clearCookies();
}

Expand Down Expand Up @@ -114,7 +116,7 @@ private void performLogin() throws Exception {

private HtmlForm findForm(HtmlPage login) {
await().atMost(10, TimeUnit.SECONDS)
.until(() -> login.getForms().stream().map(HtmlForm::getId).anyMatch("form19"::equals));
.until(() -> login.getForms().stream().map(HtmlForm::getId).anyMatch("form19"::equals));
for (HtmlForm form : login.getForms()) {
try {
if (form.getId().equals("form19")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,17 @@ SecurityFilterChain app(HttpSecurity http) throws Exception {
@Bean
RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations
.fromMetadataLocation("https://dev-05937739.okta.com/app/exk46xofd8NZvFCpS5d7/sso/saml/metadata")
.registrationId("one")
.decryptionX509Credentials(
(c) -> c.add(Saml2X509Credential.decryption(this.privateKey, relyingPartyCertificate())))
.signingX509Credentials(
(c) -> c.add(Saml2X509Credential.signing(this.privateKey, relyingPartyCertificate())))
.singleLogoutServiceLocation(
"https://dev-05937739.okta.com/app/dev-05937739_springgsecuritysaml2idp_1/exk46xofd8NZvFCpS5d7/slo/saml")
.singleLogoutServiceResponseLocation("http://localhost:8080/logout/saml2/slo")
.singleLogoutServiceBinding(Saml2MessageBinding.POST).build();
.fromMetadataLocation("https://dev-05937739.okta.com/app/exk46xofd8NZvFCpS5d7/sso/saml/metadata")
.registrationId("one")
.decryptionX509Credentials(
(c) -> c.add(Saml2X509Credential.decryption(this.privateKey, relyingPartyCertificate())))
.signingX509Credentials(
(c) -> c.add(Saml2X509Credential.signing(this.privateKey, relyingPartyCertificate())))
.singleLogoutServiceLocation(
"https://dev-05937739.okta.com/app/dev-05937739_springgsecuritysaml2idp_1/exk46xofd8NZvFCpS5d7/slo/saml")
.singleLogoutServiceResponseLocation("http://localhost:8080/logout/saml2/slo")
.singleLogoutServiceBinding(Saml2MessageBinding.POST)
.build();

return new InMemoryRelyingPartyRegistrationRepository(relyingPartyRegistration);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundEx
static final class CustomUserDetails extends CustomUser implements UserDetails {

private static final List<GrantedAuthority> ROLE_USER = Collections
.unmodifiableList(AuthorityUtils.createAuthorityList("ROLE_USER"));
.unmodifiableList(AuthorityUtils.createAuthorityList("ROLE_USER"));

CustomUserDetails(CustomUser customUser) {
super(customUser);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ public class HelloSecurityExplicitITests {

@Test
void login() {
CustomUser result = this.rest.withBasicAuth("[email protected]", "password").getForObject("/user",
CustomUser.class);
CustomUser result = this.rest.withBasicAuth("[email protected]", "password")
.getForObject("/user", CustomUser.class);
assertThat(result.getEmail()).isEqualTo("[email protected]");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundEx
static final class CustomUserDetails extends CustomUser implements UserDetails {

private static final List<GrantedAuthority> ROLE_USER = Collections
.unmodifiableList(AuthorityUtils.createAuthorityList("ROLE_USER"));
.unmodifiableList(AuthorityUtils.createAuthorityList("ROLE_USER"));

CustomUserDetails(CustomUser customUser) {
super(customUser.getId(), customUser.getEmail(), customUser.getPassword());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,14 @@ public class SecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http, UserDetailsService userDetailsService) throws Exception {
http.authorizeHttpRequests((authorize) -> authorize.requestMatchers(HttpMethod.GET, "/loggedout").permitAll()
.anyRequest().authenticated())
.exceptionHandling((exceptions) -> exceptions.authenticationEntryPoint(casAuthenticationEntryPoint()))
.logout((logout) -> logout.logoutSuccessUrl("/loggedout"))
.addFilter(casAuthenticationFilter(userDetailsService))
.addFilterBefore(new SingleSignOutFilter(), CasAuthenticationFilter.class);
http.authorizeHttpRequests((authorize) -> authorize.requestMatchers(HttpMethod.GET, "/loggedout")
.permitAll()
.anyRequest()
.authenticated())
.exceptionHandling((exceptions) -> exceptions.authenticationEntryPoint(casAuthenticationEntryPoint()))
.logout((logout) -> logout.logoutSuccessUrl("/loggedout"))
.addFilter(casAuthenticationFilter(userDetailsService))
.addFilterBefore(new SingleSignOutFilter(), CasAuthenticationFilter.class);
return http.build();
}

Expand All @@ -77,8 +79,11 @@ private TicketValidator cas30ServiceTicketValidator() {

@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("casuser").password("Mellon").roles("USER")
.build();
UserDetails user = User.withDefaultPasswordEncoder()
.username("casuser")
.password("Mellon")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,13 @@ class CasLoginApplicationTests {

@Container
static GenericContainer<?> casServer = new GenericContainer<>(DockerImageName.parse("apereo/cas:6.6.6"))
.withCommand("--cas.standalone.configuration-directory=/etc/cas/config", "--server.ssl.enabled=false",
"--server.port=8080", "--cas.service-registry.core.init-from-json=true",
"--cas.service-registry.json.location=file:/etc/cas/services")
.withExposedPorts(8080).withClasspathResourceMapping("cas/services/https-1.json",
"/etc/cas/services/https-1.json", BindMode.READ_WRITE)
.waitingFor(Wait.forLogMessage(".*Ready to process requests.*", 1));
.withCommand("--cas.standalone.configuration-directory=/etc/cas/config", "--server.ssl.enabled=false",
"--server.port=8080", "--cas.service-registry.core.init-from-json=true",
"--cas.service-registry.json.location=file:/etc/cas/services")
.withExposedPorts(8080)
.withClasspathResourceMapping("cas/services/https-1.json", "/etc/cas/services/https-1.json",
BindMode.READ_WRITE)
.waitingFor(Wait.forLogMessage(".*Ready to process requests.*", 1));

@DynamicPropertySource
static void casProperties(DynamicPropertyRegistry registry) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,12 +143,12 @@ void requestAuthorizeGitHubClientWhenLinkClickedThenStatusRedirectForAuthorizati
Map<String, String> params = uriComponents.getQueryParams().toSingleValueMap();

assertThat(params.get(OAuth2ParameterNames.RESPONSE_TYPE))
.isEqualTo(OAuth2AuthorizationResponseType.CODE.getValue());
.isEqualTo(OAuth2AuthorizationResponseType.CODE.getValue());
assertThat(params.get(OAuth2ParameterNames.CLIENT_ID)).isEqualTo(clientRegistration.getClientId());
String redirectUri = AUTHORIZE_BASE_URL + "/" + clientRegistration.getRegistrationId();
assertThat(URLDecoder.decode(params.get(OAuth2ParameterNames.REDIRECT_URI), "UTF-8")).isEqualTo(redirectUri);
assertThat(URLDecoder.decode(params.get(OAuth2ParameterNames.SCOPE), "UTF-8"))
.isEqualTo(clientRegistration.getScopes().stream().collect(Collectors.joining(" ")));
.isEqualTo(clientRegistration.getScopes().stream().collect(Collectors.joining(" ")));
assertThat(params.get(OAuth2ParameterNames.STATE)).isNotNull();
}

Expand Down Expand Up @@ -185,16 +185,20 @@ void requestAuthorizationCodeGrantWhenValidAuthorizationResponseThenDisplayIndex
WebResponse response = this.followLinkDisableRedirects(clientAnchorElement);

UriComponents authorizeRequestUriComponents = UriComponentsBuilder
.fromUri(URI.create(response.getResponseHeaderValue("Location"))).build();
.fromUri(URI.create(response.getResponseHeaderValue("Location")))
.build();

Map<String, String> params = authorizeRequestUriComponents.getQueryParams().toSingleValueMap();
String code = "auth-code";
String state = URLDecoder.decode(params.get(OAuth2ParameterNames.STATE), "UTF-8");
String redirectUri = URLDecoder.decode(params.get(OAuth2ParameterNames.REDIRECT_URI), "UTF-8");

String authorizationResponseUri = UriComponentsBuilder.fromHttpUrl(redirectUri)
.queryParam(OAuth2ParameterNames.CODE, code).queryParam(OAuth2ParameterNames.STATE, state).build()
.encode().toUriString();
.queryParam(OAuth2ParameterNames.CODE, code)
.queryParam(OAuth2ParameterNames.STATE, state)
.build()
.encode()
.toUriString();

page = this.webClient.getPage(new URL(authorizationResponseUri));
this.assertIndexPage(page);
Expand All @@ -214,8 +218,11 @@ void requestAuthorizationCodeGrantWhenNoMatchingAuthorizationRequestThenDisplayL
String redirectUri = AUTHORIZE_BASE_URL + "/" + clientRegistration.getRegistrationId();

String authorizationResponseUri = UriComponentsBuilder.fromHttpUrl(redirectUri)
.queryParam(OAuth2ParameterNames.CODE, code).queryParam(OAuth2ParameterNames.STATE, state).build()
.encode().toUriString();
.queryParam(OAuth2ParameterNames.CODE, code)
.queryParam(OAuth2ParameterNames.STATE, state)
.build()
.encode()
.toUriString();

// Clear session cookie will ensure the 'session-saved'
// Authorization Request (from previous request) is not found
Expand Down Expand Up @@ -246,8 +253,11 @@ void requestAuthorizationCodeGrantWhenInvalidStateParamThenDisplayLoginPageWithE
String redirectUri = AUTHORIZE_BASE_URL + "/" + clientRegistration.getRegistrationId();

String authorizationResponseUri = UriComponentsBuilder.fromHttpUrl(redirectUri)
.queryParam(OAuth2ParameterNames.CODE, code).queryParam(OAuth2ParameterNames.STATE, state).build()
.encode().toUriString();
.queryParam(OAuth2ParameterNames.CODE, code)
.queryParam(OAuth2ParameterNames.STATE, state)
.build()
.encode()
.toUriString();

page = this.webClient.getPage(new URL(authorizationResponseUri));
assertThat(page.getBaseURL()).isEqualTo(loginErrorPageUrl);
Expand All @@ -261,8 +271,9 @@ void requestAuthorizationCodeGrantWhenInvalidStateParamThenDisplayLoginPageWithE
void requestWhenMockOAuth2LoginThenIndex() throws Exception {
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("github");
this.mvc.perform(get("/").with(oauth2Login().clientRegistration(clientRegistration)))
.andExpect(model().attribute("userName", "user")).andExpect(model().attribute("clientName", "GitHub"))
.andExpect(model().attribute("userAttributes", Collections.singletonMap("sub", "user")));
.andExpect(model().attribute("userName", "user"))
.andExpect(model().attribute("clientName", "GitHub"))
.andExpect(model().attribute("userAttributes", Collections.singletonMap("sub", "user")));
}

private void assertLoginPage(HtmlPage page) {
Expand All @@ -276,10 +287,10 @@ private void assertLoginPage(HtmlPage page) {
ClientRegistration googleClientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");
ClientRegistration githubClientRegistration = this.clientRegistrationRepository.findByRegistrationId("github");
ClientRegistration facebookClientRegistration = this.clientRegistrationRepository
.findByRegistrationId("facebook");
.findByRegistrationId("facebook");
ClientRegistration oktaClientRegistration = this.clientRegistrationRepository.findByRegistrationId("okta");
ClientRegistration springClientRegistration = this.clientRegistrationRepository
.findByRegistrationId("login-client");
.findByRegistrationId("login-client");

String baseAuthorizeUri = AUTHORIZATION_BASE_URI + "/";
String googleClientAuthorizeUri = baseAuthorizeUri + googleClientRegistration.getRegistrationId();
Expand All @@ -304,12 +315,14 @@ private void assertIndexPage(HtmlPage page) {
DomNodeList<HtmlElement> divElements = page.getBody().getElementsByTagName("div");
assertThat(divElements.get(1).asNormalizedText()).contains("User: [email protected]");
assertThat(divElements.get(4).asNormalizedText())
.contains("You are successfully logged in [email protected]");
.contains("You are successfully logged in [email protected]");
}

private HtmlAnchor getClientAnchorElement(HtmlPage page, ClientRegistration clientRegistration) {
Optional<HtmlAnchor> clientAnchorElement = page.getAnchors().stream()
.filter((e) -> e.asNormalizedText().equals(clientRegistration.getClientName())).findFirst();
Optional<HtmlAnchor> clientAnchorElement = page.getAnchors()
.stream()
.filter((e) -> e.asNormalizedText().equals(clientRegistration.getClientName()))
.findFirst();

return (clientAnchorElement.orElse(null));
}
Expand Down Expand Up @@ -350,7 +363,9 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti

private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> mockAccessTokenResponseClient() {
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(60 * 1000).build();
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.expiresIn(60 * 1000)
.build();

OAuth2AccessTokenResponseClient tokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
when(tokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
throws ServletException, IOException {
if (request.getServerName().equals("localhost") && request.getHeader("host") != null) {
UriComponents uri = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request))
.host("127.0.0.1").build();
.host("127.0.0.1")
.build();
response.sendRedirect(uri.toUriString());
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ public MockResponse dispatch(RecordedRequest request) {

private static MockResponse response(String body, int status) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setResponseCode(status).setBody(body);
.setResponseCode(status)
.setBody(body);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ public MockResponse dispatch(RecordedRequest request) {

private static MockResponse response(String body, int status) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setResponseCode(status).setBody(body);
.setResponseCode(status)
.setBody(body);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,10 @@ void messageCanNotBeCreatedWithoutAnyScope() throws Exception {

@Test
void messageCanNotBeCreatedWithScopeMessageReadAuthority() throws Exception {
this.mvc.perform(post("/message").content("Hello message")
this.mvc
.perform(post("/message").content("Hello message")
.with(opaqueToken().authorities(new SimpleGrantedAuthority("SCOPE_message:read"))))
.andExpect(status().isForbidden());
.andExpect(status().isForbidden());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,9 @@ void logoutWhenRelyingPartyInitiatedLogoutThenLoginPageWithLogoutParam() throws

@Test
void metadataWhenGetThenForwardToUrl() throws Exception {
this.mvc.perform(get("/saml/metadata")).andExpect(status().isOk())
.andExpect(forwardedUrl("/saml2/service-provider-metadata/one"));
this.mvc.perform(get("/saml/metadata"))
.andExpect(status().isOk())
.andExpect(forwardedUrl("/saml2/service-provider-metadata/one"));
}

private void performLogin() throws Exception {
Expand Down
Loading

0 comments on commit fadbeb3

Please sign in to comment.