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

@@ -69,7 +69,7 @@ public class HelloRSocketApplicationITests {
RSocketRequester requester = this.requester.connectTcp("localhost", this.port).block();
assertThatThrownBy(() -> requester.route("message").data(Mono.empty()).retrieveMono(String.class).block())
.isNotNull();
.isNotNull();
}
}

View File

@@ -83,7 +83,7 @@ public class WebfluxX509ApplicationITest {
// @formatter:on
HttpClient httpClient = HttpClient.create()
.secure((sslContextSpec) -> sslContextSpec.sslContext(sslContextBuilder));
.secure((sslContextSpec) -> sslContextSpec.sslContext(sslContextBuilder));
ClientHttpConnector httpConnector = new ReactorClientHttpConnector(httpClient);
// @formatter:off

View File

@@ -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());
}
}

View File

@@ -51,7 +51,7 @@ class AspectJInterceptorTests {
@Test
void securedMethodNotAuthenticated() {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.service.secureMethod());
.isThrownBy(() -> this.service.secureMethod());
}
@Test
@@ -69,7 +69,7 @@ class AspectJInterceptorTests {
@Test
void securedClassNotAuthenticated() {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.securedService.secureMethod());
.isThrownBy(() -> this.securedService.secureMethod());
}
@Test

View File

@@ -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();
}
}

View File

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

View File

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

View File

@@ -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();
}
@@ -114,7 +116,7 @@ public class Saml2JavaConfigurationITests {
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")) {

View File

@@ -60,16 +60,17 @@ public class SecurityConfiguration {
@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);
}

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);
}

View File

@@ -76,9 +76,12 @@ public class ContactsPage {
}
public DeleteContactLink andHasContact(final String name, final String email) {
return this.contacts.stream().filter(byEmail(email).and(byName(name)))
.map((e) -> e.findElement(By.cssSelector("td:nth-child(4) > a"))).findFirst()
.map((e) -> new DeleteContactLink(this.webDriver, e)).get();
return this.contacts.stream()
.filter(byEmail(email).and(byName(name)))
.map((e) -> e.findElement(By.cssSelector("td:nth-child(4) > a")))
.findFirst()
.map((e) -> new DeleteContactLink(this.webDriver, e))
.get();
}
public ContactsPage andContactHasBeenRemoved(final String name, final String email) {

View File

@@ -229,7 +229,7 @@ public class DataSourcePopulator implements InitializingBean {
private void changeOwner(int contactNumber, String newOwnerUsername) {
AclImpl acl = (AclImpl) this.mutableAclService
.readAclById(new ObjectIdentityImpl(Contact.class, (long) contactNumber));
.readAclById(new ObjectIdentityImpl(Contact.class, (long) contactNumber));
acl.setOwner(new PrincipalSid(newOwnerUsername));
updateAclInTransaction(acl);
}
@@ -240,7 +240,7 @@ public class DataSourcePopulator implements InitializingBean {
private void grantPermissions(int contactNumber, String recipientUsername, Permission permission) {
AclImpl acl = (AclImpl) this.mutableAclService
.readAclById(new ObjectIdentityImpl(Contact.class, (long) contactNumber));
.readAclById(new ObjectIdentityImpl(Contact.class, (long) contactNumber));
acl.insertAce(acl.getEntries().size(), permission, new PrincipalSid(recipientUsername), true);
updateAclInTransaction(acl);
}

View File

@@ -101,8 +101,9 @@ public class DataSourcePopulator implements InitializingBean {
this.template.execute("INSERT INTO AUTHORITIES VALUES('jane','ROLE_USER');");
// Now create an ACL entry for the root directory
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("rod", "ignored",
AuthorityUtils.createAuthorityList(("ROLE_IGNORED"))));
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("rod", "ignored",
AuthorityUtils.createAuthorityList(("ROLE_IGNORED"))));
addPermission(this.documentDao, Directory.ROOT_DIRECTORY, "ROLE_USER", LEVEL_GRANT_WRITE);

View File

@@ -47,7 +47,7 @@ public class SecureDocumentDaoImpl extends DocumentDaoImpl implements SecureDocu
public String[] getUsers() {
return getJdbcTemplate().query(SELECT_FROM_USERS, (rs, rowNumber) -> rs.getString("USERNAME"))
.toArray(new String[] {});
.toArray(new String[] {});
}
public void create(AbstractElement element) {

View File

@@ -100,7 +100,7 @@ public class DmsIntegrationTests {
protected void process(String username, String password, boolean shouldBeFiltered) {
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken(username, password));
.setAuthentication(new UsernamePasswordAuthenticationToken(username, password));
System.out.println("------ Test for username: " + username + " ------");
AbstractElement[] rootElements = this.documentDao.findElements(Directory.ROOT_DIRECTORY);
assertThat(rootElements).hasSize(3);
@@ -140,7 +140,7 @@ public class DmsIntegrationTests {
if (shouldBeFiltered) {
assertThat(nonHomeConfidentialDir).withFailMessage("Found confidential directory when we should not have")
.isNull();
.isNull();
}
else {
System.out.println("Inaccessible dir....: " + nonHomeConfidentialDir.getFullName());

View File

@@ -46,7 +46,7 @@ public class SecureDmsIntegrationTests extends DmsIntegrationTests {
// and
// File
assertThat(this.jdbcTemplate.queryForObject("select count(id) from ACL_OBJECT_IDENTITY", Integer.class))
.isEqualTo(100);
.isEqualTo(100);
assertThat(this.jdbcTemplate.queryForObject("select count(id) from ACL_ENTRY", Integer.class)).isEqualTo(115);
}

View File

@@ -55,15 +55,22 @@ public class HelloWorldXmlTests {
@Test
void authenticatedUserIsSentToOriginalPage() {
final HomePage homePage = HomePage.to(this.driver, this.port).loginForm().username("user").password("password")
.submit();
final HomePage homePage = HomePage.to(this.driver, this.port)
.loginForm()
.username("user")
.password("password")
.submit();
homePage.assertAt().andTheUserNameIsDisplayed();
}
@Test
void authenticatedUserLogsOut() {
LoginPage loginPage = HomePage.to(this.driver, this.port).loginForm().username("user").password("password")
.submit().logout();
LoginPage loginPage = HomePage.to(this.driver, this.port)
.loginForm()
.username("user")
.password("password")
.submit()
.logout();
loginPage.assertAt();
loginPage = HomePage.to(this.driver, this.port);

View File

@@ -63,9 +63,11 @@ public class Saml2XmlITests {
@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();
}

View File

@@ -45,7 +45,7 @@ public class WebConfiguration implements WebMvcConfigurer, ApplicationContextAwa
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
AuthenticationPrincipalArgumentResolver principalArgumentResolver = new AuthenticationPrincipalArgumentResolver();
principalArgumentResolver
.setBeanResolver(new BeanFactoryResolver(this.context.getAutowireCapableBeanFactory()));
.setBeanResolver(new BeanFactoryResolver(this.context.getAutowireCapableBeanFactory()));
resolvers.add(principalArgumentResolver);
}