diff --git a/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java new file mode 100644 index 0000000000..3ee08767bd --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java @@ -0,0 +1,116 @@ +package org.baeldung.java.collections; + +import static java.util.Arrays.asList; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.Assert; +import org.junit.Test; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +public class CollectionsConcatenateUnitTest { + + @Test + public void givenUsingJava8_whenConcatenatingUsingConcat_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + Collection collectionC = asList("W", "X"); + + Stream combinedStream = Stream.concat(Stream.concat(collectionA.stream(), collectionB.stream()), collectionC.stream()); + Collection collectionCombined = combinedStream.collect(Collectors.toList()); + + Assert.assertEquals(asList("S", "T", "U", "V", "W", "X"), collectionCombined); + } + + @Test + public void givenUsingJava8_whenConcatenatingUsingflatMap_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + + Stream combinedStream = Stream.of(collectionA, collectionB).flatMap(Collection::stream); + Collection collectionCombined = combinedStream.collect(Collectors.toList()); + + Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined); + } + + @Test + public void givenUsingGuava_whenConcatenatingUsingIterables_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + + Iterable combinedIterables = Iterables.unmodifiableIterable(Iterables.concat(collectionA, collectionB)); + Collection collectionCombined = Lists.newArrayList(combinedIterables); + + Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined); + } + + @Test + public void givenUsingJava7_whenConcatenatingUsingIterables_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + + Iterable combinedIterables = concat(collectionA, collectionB); + Collection collectionCombined = makeListFromIterable(combinedIterables); + Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined); + } + + public static Iterable concat(Iterable list1, Iterable list2) { + return new Iterable() { + public Iterator iterator() { + return new Iterator() { + protected Iterator listIterator = list1.iterator(); + protected Boolean checkedHasNext; + protected E nextValue; + private boolean startTheSecond; + + public void theNext() { + if (listIterator.hasNext()) { + checkedHasNext = true; + nextValue = listIterator.next(); + } else if (startTheSecond) + checkedHasNext = false; + else { + startTheSecond = true; + listIterator = list2.iterator(); + theNext(); + } + } + + public boolean hasNext() { + if (checkedHasNext == null) + theNext(); + return checkedHasNext; + } + + public E next() { + if (!hasNext()) + throw new NoSuchElementException(); + checkedHasNext = null; + return nextValue; + } + + public void remove() { + listIterator.remove(); + } + }; + } + }; + } + + public static List makeListFromIterable(Iterable iter) { + List list = new ArrayList(); + for (E item : iter) { + list.add(item); + } + return list; + } +} diff --git a/spring-security-client/README.MD b/spring-security-client/README.MD index 5ac974203b..0b0af7ffe1 100644 --- a/spring-security-client/README.MD +++ b/spring-security-client/README.MD @@ -1,2 +1,11 @@ -###The Course +========= +## Spring Security Authentication/Authorization Example Project + +##The Course The "REST With Spring" Classes: http://github.learnspringsecurity.com + +### Relevant Articles: +- [Spring Security Manual Authentication](http://www.baeldung.com/spring-security-authentication) + +### Build the Project +mvn clean install diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java index 9ade60e54c..259433f6ae 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java @@ -8,9 +8,11 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.context.annotation.Profile; @Configuration @EnableWebMvc +@Profile("!manual") public class MvcConfig extends WebMvcConfigurerAdapter { public MvcConfig() { diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java new file mode 100644 index 0000000000..d80527c30a --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java @@ -0,0 +1,22 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +@Configuration +@EnableWebMvc +@Profile("manual") +public class MvcConfigManual extends WebMvcConfigurerAdapter { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/home").setViewName("home"); + registry.addViewController("/").setViewName("home"); + registry.addViewController("/hello").setViewName("hello"); + registry.addViewController("/login").setViewName("login"); + } + +} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java new file mode 100644 index 0000000000..025001ac44 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java @@ -0,0 +1,92 @@ +package org.baeldung.config; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.WebAuthenticationDetails; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.context.annotation.Profile; + +/** + * Manually authenticate a user using Spring Security / Spring Web MVC' (upon successful account registration) + * (http://stackoverflow.com/questions/4664893/how-to-manually-set-an-authenticated-user-in-spring-security-springmvc) + * + * @author jim clayson + */ +@Controller +@Profile("manual") +public class RegistrationController { + private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class); + + @Autowired + AuthenticationManager authenticationManager; + + /** + * For demo purposes this need only be a GET request method + * + * @param request + * @param response + * @return The view. Page confirming either successful registration (and/or + * successful authentication) or failed registration. + */ + @RequestMapping(value = "/register", method = RequestMethod.GET) + public String registerAndAuthenticate(HttpServletRequest request, HttpServletResponse response) { + logger.debug("registerAndAuthenticate: attempt to register, application should manually authenticate."); + + // Mocked values. Potentially could come from an HTML registration form, + // in which case this mapping would match on an HTTP POST, rather than a GET + String username = "user"; + String password = "password"; + + String view = "registrationSuccess"; + + if (requestQualifiesForManualAuthentication()) { + try { + authenticate(username, password, request, response); + logger.debug("registerAndAuthenticate: authentication completed."); + } catch (BadCredentialsException bce) { + logger.debug("Authentication failure: bad credentials"); + bce.printStackTrace(); + view = "systemError"; // assume a low-level error, since the registration + // form would have been successfully validated + } + } + + return view; + } + + private boolean requestQualifiesForManualAuthentication() { + // Some processing to determine that the user requires a Spring Security-recognized, + // application-directed login e.g. successful account registration. + return true; + } + + private void authenticate(String username, String password, HttpServletRequest request, HttpServletResponse response) throws BadCredentialsException { + logger.debug("attempting to authenticated, manually ... "); + + // create and populate the token + AbstractAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password); + authToken.setDetails(new WebAuthenticationDetails(request)); + + // This call returns an authentication object, which holds principle and user credentials + Authentication authentication = this.authenticationManager.authenticate(authToken); + + // The security context holds the authentication object, and is stored + // in thread local scope. + SecurityContextHolder.getContext().setAuthentication(authentication); + + logger.debug("User should now be authenticated."); + } + +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java index bd6c56d38a..153cc67661 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java @@ -6,9 +6,11 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.context.annotation.Profile; @Configuration @EnableWebSecurity +@Profile("!manual") public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java new file mode 100644 index 0000000000..180a53deba --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java @@ -0,0 +1,35 @@ +package org.baeldung.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +@Profile("manual") +public class WebSecurityConfigManual extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http + .authorizeRequests() + .antMatchers("/", "/home", "/register").permitAll() + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login").permitAll() + .and() + .logout().permitAll(); + // @formatter:on + } + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); + } +} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html new file mode 100644 index 0000000000..b37731b0ed --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html @@ -0,0 +1,15 @@ + + + + Hello World! + + +

Hello [[${#httpServletRequest.remoteUser}]]!

+
+ +
+

Click here to go to the home page.

+ + + \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/home.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/home.html new file mode 100644 index 0000000000..6dbdf491c6 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/home.html @@ -0,0 +1,15 @@ + + + + Spring Security Example + + +

Welcome!

+ +

Click here to see a greeting.

+

Click here to send a dummy registration request, where the application logs you in.

+ + \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/login.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/login.html new file mode 100644 index 0000000000..3f28efac69 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/login.html @@ -0,0 +1,21 @@ + + + + Spring Security Example + + +
+ Invalid username and password. +
+
+ You have been logged out. +
+
+
+
+
+
+

Click here to go to the home page.

+ + \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationError.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationError.html new file mode 100644 index 0000000000..756cc2390d --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationError.html @@ -0,0 +1 @@ +Registration could not be completed at this time. Please try again later or contact support! \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationSuccess.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationSuccess.html new file mode 100644 index 0000000000..b1c4336f2f --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationSuccess.html @@ -0,0 +1,15 @@ + + + + Registration Success! + + +

Registration succeeded. You have been logged in by the system. Welcome [[${#httpServletRequest.remoteUser}]]!

+
+ +
+

Click here to go to the home page.

+ + + \ No newline at end of file