Apply formatting

This commit is contained in:
Marcus Hert Da Coregio
2024-01-24 10:28:39 -03:00
parent 64eb62026c
commit 923b627eda
35 changed files with 175 additions and 110 deletions

View File

@@ -48,7 +48,7 @@ public class CustomUserRepositoryUserDetailsService implements UserDetailsServic
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);

View File

@@ -36,8 +36,8 @@ public class HelloSecurityExplicitITests {
@Test
void login() {
CustomUser result = this.rest.withBasicAuth("user@example.com", "password").getForObject("/user",
CustomUser.class);
CustomUser result = this.rest.withBasicAuth("user@example.com", "password")
.getForObject("/user", CustomUser.class);
assertThat(result.getEmail()).isEqualTo("user@example.com");
}

View File

@@ -48,7 +48,7 @@ public class CustomUserRepositoryUserDetailsService implements UserDetailsServic
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());

View File

@@ -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();
}
@@ -77,8 +79,11 @@ public class SecurityConfig {
@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);
}

View File

@@ -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) {

View File

@@ -143,12 +143,12 @@ public class OAuth2LoginApplicationTests {
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();
}
@@ -185,7 +185,8 @@ public class OAuth2LoginApplicationTests {
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";
@@ -193,8 +194,11 @@ public class OAuth2LoginApplicationTests {
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);
@@ -214,8 +218,11 @@ public class OAuth2LoginApplicationTests {
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
@@ -246,8 +253,11 @@ public class OAuth2LoginApplicationTests {
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);
@@ -261,8 +271,9 @@ public class OAuth2LoginApplicationTests {
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) {
@@ -276,10 +287,10 @@ public class OAuth2LoginApplicationTests {
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();
@@ -304,12 +315,14 @@ public class OAuth2LoginApplicationTests {
DomNodeList<HtmlElement> divElements = page.getBody().getElementsByTagName("div");
assertThat(divElements.get(1).asNormalizedText()).contains("User: joeg@springsecurity.io");
assertThat(divElements.get(4).asNormalizedText())
.contains("You are successfully logged in joeg@springsecurity.io");
.contains("You are successfully logged in joeg@springsecurity.io");
}
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));
}
@@ -350,7 +363,9 @@ public class OAuth2LoginApplicationTests {
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);

View File

@@ -58,7 +58,8 @@ public class LoopbackIpRedirectFilter extends OncePerRequestFilter {
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;
}

View File

@@ -114,7 +114,8 @@ public class MockWebServerPropertySource extends PropertySource<MockWebServer> i
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);
}
}

View File

@@ -114,7 +114,8 @@ public class MockWebServerPropertySource extends PropertySource<MockWebServer> i
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);
}
}

View File

@@ -87,9 +87,10 @@ public class OAuth2ResourceServerControllerTests {
@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

View File

@@ -77,8 +77,9 @@ public class CustomUrlsApplicationITests {
@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 {

View File

@@ -82,9 +82,11 @@ public class SecurityConfiguration {
@Value("classpath:credentials/rp-private.key") RSAPrivateKey privateKey) {
Saml2X509Credential signing = Saml2X509Credential.signing(privateKey, relyingPartyCertificate());
RelyingPartyRegistration two = RelyingPartyRegistrations
.fromMetadataLocation("https://dev-05937739.okta.com/app/exk4842vmapcMkohr5d7/sso/saml/metadata")
.registrationId("two").signingX509Credentials((c) -> c.add(signing))
.singleLogoutServiceLocation("http://localhost:8080/logout/saml2/slo").build();
.fromMetadataLocation("https://dev-05937739.okta.com/app/exk4842vmapcMkohr5d7/sso/saml/metadata")
.registrationId("two")
.signingX509Credentials((c) -> c.add(signing))
.singleLogoutServiceLocation("http://localhost:8080/logout/saml2/slo")
.build();
return new InMemoryRelyingPartyRegistrationRepository(two);
}

View File

@@ -61,17 +61,22 @@ public class RefreshableRelyingPartyRegistrationRepository
@Scheduled(fixedDelay = 30, timeUnit = TimeUnit.MINUTES)
public void refreshMetadata() {
for (Map.Entry<String, Saml2RelyingPartyProperties.Registration> byRegistrationId : this.relyingPartyProperties
.getRegistration().entrySet()) {
.getRegistration()
.entrySet()) {
fetchMetadata(byRegistrationId.getKey(), byRegistrationId.getValue());
}
}
private void fetchMetadata(String registrationId, Saml2RelyingPartyProperties.Registration registration) {
RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations
.fromMetadataLocation(registration.getAssertingparty().getMetadataUri())
.signingX509Credentials((credentials) -> registration.getSigning().getCredentials().stream()
.map(this::asSigningCredential).forEach(credentials::add))
.registrationId(registrationId).build();
.fromMetadataLocation(registration.getAssertingparty().getMetadataUri())
.signingX509Credentials((credentials) -> registration.getSigning()
.getCredentials()
.stream()
.map(this::asSigningCredential)
.forEach(credentials::add))
.registrationId(registrationId)
.build();
this.relyingPartyRegistrations.put(relyingPartyRegistration.getRegistrationId(), relyingPartyRegistration);
}

View File

@@ -79,8 +79,9 @@ public class SamlExtensionFederationApplicationITests {
@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 {

View File

@@ -66,14 +66,16 @@ public class SecurityConfiguration {
Saml2X509Credential signing = Saml2X509Credential.signing(key, x509Certificate(cert));
Registration registration = properties.getRegistration().values().iterator().next();
return new InMemoryRelyingPartyRegistrationRepository(RelyingPartyRegistrations
.collectionFromMetadataLocation(registration.getAssertingparty().getMetadataUri()).stream()
.map((builder) -> builder.registrationId(UUID.randomUUID().toString())
.entityId(registration.getEntityId())
.assertionConsumerServiceLocation(registration.getAcs().getLocation())
.singleLogoutServiceLocation(registration.getSinglelogout().getUrl())
.singleLogoutServiceResponseLocation(registration.getSinglelogout().getResponseUrl())
.signingX509Credentials((credentials) -> credentials.add(signing)).build())
.collect(Collectors.toList()));
.collectionFromMetadataLocation(registration.getAssertingparty().getMetadataUri())
.stream()
.map((builder) -> builder.registrationId(UUID.randomUUID().toString())
.entityId(registration.getEntityId())
.assertionConsumerServiceLocation(registration.getAcs().getLocation())
.singleLogoutServiceLocation(registration.getSinglelogout().getUrl())
.singleLogoutServiceResponseLocation(registration.getSinglelogout().getResponseUrl())
.signingX509Credentials((credentials) -> credentials.add(signing))
.build())
.collect(Collectors.toList()));
}
X509Certificate x509Certificate(File location) {

View File

@@ -52,8 +52,11 @@ public class SecurityConfig {
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER")
.build();
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}

View File

@@ -35,15 +35,18 @@ public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests.anyRequest().authenticated())
.formLogin(withDefaults())
.sessionManagement((sessionManagement) -> sessionManagement.maximumSessions(1));
.formLogin(withDefaults())
.sessionManagement((sessionManagement) -> sessionManagement.maximumSessions(1));
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER")
.build();
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}