├── .gitignore ├── README.md ├── cas-server-with-ldap ├── pom.xml └── src │ ├── etc │ └── keys │ │ ├── jbcp_clientauth.cer │ │ ├── jbcp_clientauth.p12 │ │ ├── tomcat.keystore │ │ └── tomcat.truststore │ └── main │ ├── resources │ ├── ldif │ │ └── calendar.ldif │ └── tomcat │ │ └── server.xml │ └── webapp │ └── WEB-INF │ └── deployerConfigContext.xml ├── spring-security-cas ├── pom.xml └── src │ ├── etc │ └── keys │ │ ├── jbcp_clientauth.cer │ │ ├── jbcp_clientauth.p12 │ │ ├── tomcat.keystore │ │ └── tomcat.truststore │ └── main │ ├── java │ └── com │ │ └── example │ │ └── springsecurity │ │ ├── dataaccess │ │ ├── CalendarUserDao.java │ │ ├── EventDao.java │ │ ├── JdbcCalendarUserDao.java │ │ └── JdbcEventDao.java │ │ ├── domain │ │ ├── CalendarUser.java │ │ └── Event.java │ │ ├── service │ │ ├── CalendarService.java │ │ ├── DefaultCalendarService.java │ │ ├── UserContext.java │ │ └── UserContextStub.java │ │ └── web │ │ ├── config │ │ └── WebMvcConfig.java │ │ ├── controllers │ │ ├── DefaultController.java │ │ ├── EchoController.java │ │ ├── EventsController.java │ │ └── WelcomeController.java │ │ └── model │ │ └── CreateEventForm.java │ ├── resources │ ├── database │ │ └── h2 │ │ │ ├── calendar-data.sql │ │ │ └── calendar-schema.sql │ ├── log4j.xml │ └── tomcat │ │ └── server.xml │ └── webapp │ ├── WEB-INF │ ├── i18n │ │ └── binding.properties │ ├── mvc-config.xml │ ├── spring │ │ ├── i18n.xml │ │ ├── security-cas.xml │ │ ├── security.xml │ │ └── services.xml │ ├── views │ │ ├── errors │ │ │ └── 403.jsp │ │ ├── events │ │ │ ├── create.jsp │ │ │ ├── list.jsp │ │ │ ├── my.jsp │ │ │ └── show.jsp │ │ ├── includes │ │ │ ├── footer.jsp │ │ │ └── header.jsp │ │ ├── index.jsp │ │ └── login.jsp │ └── web.xml │ └── resources │ └── css │ ├── bootstrap.css │ └── bootstrap.min.css ├── spring-security-db ├── README.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── springsecurity │ │ │ ├── core │ │ │ └── authority │ │ │ │ └── CalendarUserAuthorityUtils.java │ │ │ ├── dataaccess │ │ │ ├── CalendarUserDao.java │ │ │ ├── EventDao.java │ │ │ ├── JdbcCalendarUserDao.java │ │ │ └── JdbcEventDao.java │ │ │ ├── domain │ │ │ ├── CalendarUser.java │ │ │ └── Event.java │ │ │ ├── service │ │ │ ├── CalendarService.java │ │ │ ├── DefaultCalendarService.java │ │ │ ├── SpringSecurityUserContext.java │ │ │ ├── UserContext.java │ │ │ └── UserContextStub.java │ │ │ └── web │ │ │ ├── authentication │ │ │ └── rememberme │ │ │ │ ├── IpAwarePersistentTokenRepository.java │ │ │ │ └── JdbcTokenRepositoryImplCleaner.java │ │ │ ├── config │ │ │ └── WebMvcConfig.java │ │ │ ├── controllers │ │ │ ├── DefaultController.java │ │ │ ├── EventsController.java │ │ │ ├── SignupController.java │ │ │ └── WelcomeController.java │ │ │ └── model │ │ │ ├── CreateEventForm.java │ │ │ └── SignupForm.java │ ├── resources │ │ ├── database │ │ │ └── h2 │ │ │ │ ├── calendar-data.sql │ │ │ │ ├── calendar-schema.sql │ │ │ │ └── security-rememberme-schema.sql │ │ └── log4j.xml │ └── webapp │ │ ├── WEB-INF │ │ ├── i18n │ │ │ └── binding.properties │ │ ├── mvc-config.xml │ │ ├── spring │ │ │ ├── cleaner.xml │ │ │ ├── i18n.xml │ │ │ ├── ipTokenRepository.xml │ │ │ ├── security.xml │ │ │ └── services.xml │ │ ├── views │ │ │ ├── errors │ │ │ │ └── 403.jsp │ │ │ ├── events │ │ │ │ ├── create.jsp │ │ │ │ ├── list.jsp │ │ │ │ ├── my.jsp │ │ │ │ └── show.jsp │ │ │ ├── includes │ │ │ │ ├── footer.jsp │ │ │ │ └── header.jsp │ │ │ ├── index.jsp │ │ │ ├── login.jsp │ │ │ └── signup │ │ │ │ └── form.jsp │ │ └── web.xml │ │ └── resources │ │ ├── css │ │ ├── bootstrap.css │ │ ├── bootstrap.min.css │ │ └── main.css │ │ └── img │ │ ├── springsource.png │ │ └── ssbooklogo.png │ └── test │ ├── java │ └── com │ │ └── example │ │ └── springsecurity │ │ └── web │ │ └── controllers │ │ ├── Video1SpringInmemoryUserdetailServiceControllerTest.java │ │ ├── Video2CustomUserDetailsServiceControllerTest.java │ │ ├── Video3JdbcUserServiceControllerTest.java │ │ └── util │ │ ├── GenericWebContextLoader.java │ │ ├── SecurityControllerTest.java │ │ ├── SecurityRequestPostProcessors.java │ │ └── WebContextLoader.java │ └── resources │ └── META-INF │ └── spring │ ├── video1-spring-inmemory-userdetailservice-config │ ├── mvc-config.xml │ ├── security.xml │ └── services.xml │ ├── video2-custom-userdetailservice-config │ ├── cleaner.xml │ ├── ipTokenRepository.xml │ ├── mvc-config.xml │ ├── security.xml │ └── services.xml │ └── video3-jdbc-user-service-config │ ├── database │ └── h2 │ │ ├── calendar-authorities.sql │ │ ├── calendar-data.sql │ │ ├── calendar-saltedsha256.sql │ │ ├── calendar-schema.sql │ │ ├── calendar-sha256.sql │ │ ├── security-groups-mappings.sql │ │ ├── security-groups-schema.sql │ │ ├── security-schema.sql │ │ ├── security-user-authorities.sql │ │ └── security-users.sql │ ├── mvc-config.xml │ ├── security.xml │ └── services.xml ├── spring-security-ldap ├── README.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── springsecurity │ │ │ ├── dataaccess │ │ │ ├── CalendarUserDao.java │ │ │ ├── EventDao.java │ │ │ ├── JdbcCalendarUserDao.java │ │ │ └── JdbcEventDao.java │ │ │ ├── domain │ │ │ ├── CalendarUser.java │ │ │ └── Event.java │ │ │ ├── ldap │ │ │ └── userdetails │ │ │ │ └── ad │ │ │ │ └── ActiveDirectoryLdapAuthoritiesPopulator.java │ │ │ ├── service │ │ │ ├── CalendarService.java │ │ │ ├── DefaultCalendarService.java │ │ │ ├── UserContext.java │ │ │ └── UserContextStub.java │ │ │ └── web │ │ │ ├── config │ │ │ └── WebMvcConfig.java │ │ │ ├── controllers │ │ │ ├── AccountController.java │ │ │ ├── DefaultController.java │ │ │ ├── EventsController.java │ │ │ └── WelcomeController.java │ │ │ └── model │ │ │ └── CreateEventForm.java │ ├── resources │ │ ├── database │ │ │ └── h2 │ │ │ │ ├── calendar-data.sql │ │ │ │ ├── calendar-schema.sql │ │ │ │ └── security-rememberme-schema.sql │ │ ├── ldif │ │ │ └── calendar.ldif │ │ └── log4j.xml │ └── webapp │ │ ├── WEB-INF │ │ ├── i18n │ │ │ └── binding.properties │ │ ├── mvc-config.xml │ │ ├── spring │ │ │ ├── cleaner.xml │ │ │ ├── i18n.xml │ │ │ ├── ipTokenRepository.xml │ │ │ ├── security.xml │ │ │ └── services.xml │ │ ├── views │ │ │ ├── errors │ │ │ │ └── 403.jsp │ │ │ ├── events │ │ │ │ ├── create.jsp │ │ │ │ ├── list.jsp │ │ │ │ ├── my.jsp │ │ │ │ └── show.jsp │ │ │ ├── includes │ │ │ │ ├── footer.jsp │ │ │ │ └── header.jsp │ │ │ ├── index.jsp │ │ │ ├── login.jsp │ │ │ └── signup │ │ │ │ └── form.jsp │ │ └── web.xml │ │ └── resources │ │ ├── css │ │ ├── bootstrap.css │ │ ├── bootstrap.min.css │ │ └── main.css │ │ └── img │ │ ├── springsource.png │ │ └── ssbooklogo.png │ └── test │ ├── java │ └── com │ │ └── example │ │ └── springsecurity │ │ └── web │ │ └── controllers │ │ ├── Video4LdapProviderControllerTest.java │ │ └── util │ │ ├── GenericWebContextLoader.java │ │ ├── LdapSecurityControllerTest.java │ │ ├── LdapSecurityRequestPostProcessors.java │ │ └── WebContextLoader.java │ └── resources │ └── META-INF │ └── spring │ └── video4-ldap-provider-config │ ├── database │ └── h2 │ │ ├── calendar-data.sql │ │ └── calendar-schema.sql │ ├── mvc-config.xml │ ├── security-ldap-explicitly.xml │ ├── security.xml │ └── services.xml └── spring-security-methodlevel-security ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── example │ │ └── springsecurity │ │ ├── authentication │ │ └── CalendarUserAuthenticationProvider.java │ │ ├── core │ │ ├── authority │ │ │ └── CalendarUserAuthorityUtils.java │ │ └── userdetails │ │ │ └── CalendarUserDetailsService.java │ │ ├── dataaccess │ │ ├── CalendarUserDao.java │ │ ├── EventDao.java │ │ ├── JdbcCalendarUserDao.java │ │ └── JdbcEventDao.java │ │ ├── domain │ │ ├── CalendarUser.java │ │ └── Event.java │ │ ├── service │ │ ├── CalendarService.java │ │ ├── DefaultCalendarService.java │ │ ├── SpringSecurityUserContext.java │ │ ├── UserContext.java │ │ └── UserContextStub.java │ │ └── web │ │ ├── config │ │ └── WebMvcConfig.java │ │ ├── controllers │ │ ├── DefaultController.java │ │ ├── EventsController.java │ │ ├── SignupController.java │ │ └── WelcomeController.java │ │ └── model │ │ ├── CreateEventForm.java │ │ └── SignupForm.java ├── resources │ ├── database │ │ └── h2 │ │ │ ├── calendar-data.sql │ │ │ └── calendar-schema.sql │ ├── log4j.xml │ └── tomcat │ │ └── server.xml └── webapp │ ├── WEB-INF │ ├── i18n │ │ └── binding.properties │ ├── mvc-config.xml │ ├── spring │ │ ├── i18n.xml │ │ ├── security.xml │ │ └── services.xml │ ├── views │ │ ├── errors │ │ │ └── 403.jsp │ │ ├── events │ │ │ ├── create.jsp │ │ │ ├── list.jsp │ │ │ ├── my.jsp │ │ │ └── show.jsp │ │ ├── includes │ │ │ ├── footer.jsp │ │ │ └── header.jsp │ │ ├── index.jsp │ │ ├── login.jsp │ │ └── signup │ │ │ └── form.jsp │ └── web.xml │ └── resources │ └── css │ ├── bootstrap.css │ └── bootstrap.min.css └── test ├── java └── com │ └── example │ └── springsecurity │ └── web │ └── controllers │ ├── GenericWebContextLoader.java │ ├── SecurityControllerTest.java │ └── WebContextLoader.java └── resources ├── META-INF └── spring │ ├── mvc-config.xml │ ├── security.xml │ └── services.xml └── log4j.xml /.gitignore: -------------------------------------------------------------------------------- 1 | spring-security-db/.settings 2 | spring-security-db/.classpath 3 | spring-security-db/.project 4 | spring-security-db/target 5 | spring-security-ldap/.settings 6 | spring-security-ldap/.classpath 7 | spring-security-ldap/.project 8 | spring-security-ldap/target 9 | spring-security-cas/.settings 10 | spring-security-cas/.classpath 11 | spring-security-cas/.project 12 | spring-security-cas/target 13 | cas-server-with-ldap/.settings 14 | cas-server-with-ldap/.classpath 15 | cas-server-with-ldap/.project 16 | cas-server-with-ldap/target 17 | spring-security-methodlevel-security/.settings 18 | spring-security-methodlevel-security/.classpath 19 | spring-security-methodlevel-security/.project 20 | spring-security-methodlevel-security/target -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Spring Security 2 | =============== 3 | 4 | [Spring Test MVC](https://github.com/SpringSource/spring-test-mvc) is a good framework for testing Spring MVC application. 5 | 6 | In this sample, we demonstrated a simple Calendar application, where a regular user can create a Event and can see others event but cannot modify them. Admin user can modify other user's event as well. 7 | 8 | We will demonstrate the Spring Security capability for Inmemory authorization provider, JDBC authorization provider, LDAP authorization provider, CAS Single sign on authorization provider. 9 | 10 | Refer to this [blog](http://krishnasblog.com/2013/02/10/spring-test-mvc-junit-testing-spring-security-layer-with-inmemorydaoimpl-2/) for more details. 11 | -------------------------------------------------------------------------------- /cas-server-with-ldap/src/etc/keys/jbcp_clientauth.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skprasadu/spring-security-examples/dadd0da3a5c41dc600a72b800a0cf4fffc1fc18f/cas-server-with-ldap/src/etc/keys/jbcp_clientauth.cer -------------------------------------------------------------------------------- /cas-server-with-ldap/src/etc/keys/jbcp_clientauth.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skprasadu/spring-security-examples/dadd0da3a5c41dc600a72b800a0cf4fffc1fc18f/cas-server-with-ldap/src/etc/keys/jbcp_clientauth.p12 -------------------------------------------------------------------------------- /cas-server-with-ldap/src/etc/keys/tomcat.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skprasadu/spring-security-examples/dadd0da3a5c41dc600a72b800a0cf4fffc1fc18f/cas-server-with-ldap/src/etc/keys/tomcat.keystore -------------------------------------------------------------------------------- /cas-server-with-ldap/src/etc/keys/tomcat.truststore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skprasadu/spring-security-examples/dadd0da3a5c41dc600a72b800a0cf4fffc1fc18f/cas-server-with-ldap/src/etc/keys/tomcat.truststore -------------------------------------------------------------------------------- /spring-security-cas/src/etc/keys/jbcp_clientauth.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skprasadu/spring-security-examples/dadd0da3a5c41dc600a72b800a0cf4fffc1fc18f/spring-security-cas/src/etc/keys/jbcp_clientauth.cer -------------------------------------------------------------------------------- /spring-security-cas/src/etc/keys/jbcp_clientauth.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skprasadu/spring-security-examples/dadd0da3a5c41dc600a72b800a0cf4fffc1fc18f/spring-security-cas/src/etc/keys/jbcp_clientauth.p12 -------------------------------------------------------------------------------- /spring-security-cas/src/etc/keys/tomcat.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skprasadu/spring-security-examples/dadd0da3a5c41dc600a72b800a0cf4fffc1fc18f/spring-security-cas/src/etc/keys/tomcat.keystore -------------------------------------------------------------------------------- /spring-security-cas/src/etc/keys/tomcat.truststore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skprasadu/spring-security-examples/dadd0da3a5c41dc600a72b800a0cf4fffc1fc18f/spring-security-cas/src/etc/keys/tomcat.truststore -------------------------------------------------------------------------------- /spring-security-cas/src/main/java/com/example/springsecurity/dataaccess/CalendarUserDao.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.dataaccess; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.dao.EmptyResultDataAccessException; 6 | 7 | import com.example.springsecurity.domain.CalendarUser; 8 | 9 | /** 10 | * An interface for managing {@link CalendarUser} instances. 11 | * 12 | * 13 | * 14 | */ 15 | public interface CalendarUserDao { 16 | 17 | /** 18 | * Gets a {@link CalendarUser} for a specific {@link CalendarUser#getId()}. 19 | * 20 | * @param id 21 | * the {@link CalendarUser#getId()} of the {@link CalendarUser} to find. 22 | * @return a {@link CalendarUser} for the given id. Cannot be null. 23 | * @throws EmptyResultDataAccessException 24 | * if the {@link CalendarUser} cannot be found 25 | */ 26 | CalendarUser getUser(int id); 27 | 28 | /** 29 | * Finds a given {@link CalendarUser} by email address. 30 | * 31 | * @param email 32 | * the email address to use to find a {@link CalendarUser}. Cannot be null. 33 | * @return a {@link CalendarUser} for the given email or null if one could not be found. 34 | * @throws IllegalArgumentException 35 | * if email is null. 36 | */ 37 | CalendarUser findUserByEmail(String email); 38 | 39 | 40 | /** 41 | * Finds any {@link CalendarUser} that has an email that starts with {@code partialEmail}. 42 | * 43 | * @param partialEmail 44 | * the email address to use to find {@link CalendarUser}s. Cannot be null or empty String. 45 | * @return a List of {@link CalendarUser}s that have an email that starts with given partialEmail. The returned value 46 | * will never be null. If no results are found an empty List will be returned. 47 | * @throws IllegalArgumentException 48 | * if email is null or empty String. 49 | */ 50 | List findUsersByEmail(String partialEmail); 51 | 52 | /** 53 | * Creates a new {@link CalendarUser}. 54 | * 55 | * @param user 56 | * the new {@link CalendarUser} to create. The {@link CalendarUser#getId()} must be null. 57 | * @return the new {@link CalendarUser#getId()}. 58 | * @throws IllegalArgumentException 59 | * if {@link CalendarUser#getId()} is non-null. 60 | */ 61 | int createUser(CalendarUser user); 62 | } 63 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/java/com/example/springsecurity/dataaccess/EventDao.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.dataaccess; 2 | 3 | import java.util.List; 4 | 5 | import com.example.springsecurity.domain.Event; 6 | import com.example.springsecurity.domain.CalendarUser; 7 | 8 | /** 9 | * An interface for managing {@link Event}'s. 10 | * 11 | * 12 | * 13 | */ 14 | public interface EventDao { 15 | 16 | /** 17 | * Given an id gets an {@link Event}. 18 | * 19 | * @param eventId 20 | * the {@link Event#getId()} 21 | * @return the {@link Event}. Cannot be null. 22 | * @throws RuntimeException 23 | * if the {@link Event} cannot be found. 24 | */ 25 | Event getEvent(int eventId); 26 | 27 | /** 28 | * Creates a {@link Event} and returns the new id for that {@link Event}. 29 | * 30 | * @param message 31 | * the {@link Event} to create. Note that the {@link Event#getId()} should be null. 32 | * @return the new id for the {@link Event} 33 | * @throws RuntimeException 34 | * if {@link Event#getId()} is non-null. 35 | */ 36 | int createEvent(Event event); 37 | 38 | /** 39 | * Finds the {@link Event}'s that are intended for the {@link CalendarUser}. 40 | * 41 | * @param userId 42 | * the {@link CalendarUser#getId()} to obtain {@link Event}'s for. 43 | * @return a non-null {@link List} of {@link Event}'s intended for the specified {@link CalendarUser}. If the 44 | * {@link CalendarUser} does not exist an empty List will be returned. 45 | */ 46 | List findForUser(int userId); 47 | 48 | /** 49 | * Gets all the available {@link Event}'s. 50 | * 51 | * @return a non-null {@link List} of {@link Event}'s 52 | */ 53 | List getEvents(); 54 | } 55 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/java/com/example/springsecurity/service/DefaultCalendarService.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.service; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import com.example.springsecurity.dataaccess.EventDao; 9 | import com.example.springsecurity.dataaccess.CalendarUserDao; 10 | import com.example.springsecurity.domain.Event; 11 | import com.example.springsecurity.domain.CalendarUser; 12 | 13 | /** 14 | * A default implementation of {@link CalendarService} that delegates to {@link EventDao} and {@link CalendarUserDao}. 15 | * 16 | * 17 | * 18 | */ 19 | @Repository 20 | public class DefaultCalendarService implements CalendarService { 21 | private final EventDao eventDao; 22 | private final CalendarUserDao userDao; 23 | 24 | @Autowired 25 | public DefaultCalendarService(EventDao eventDao, CalendarUserDao userDao) { 26 | if (eventDao == null) { 27 | throw new IllegalArgumentException("eventDao cannot be null"); 28 | } 29 | if (userDao == null) { 30 | throw new IllegalArgumentException("userDao cannot be null"); 31 | } 32 | this.eventDao = eventDao; 33 | this.userDao = userDao; 34 | } 35 | 36 | public Event getEvent(int eventId) { 37 | return eventDao.getEvent(eventId); 38 | } 39 | 40 | public int createEvent(Event event) { 41 | return eventDao.createEvent(event); 42 | } 43 | 44 | public List findForUser(int userId) { 45 | return eventDao.findForUser(userId); 46 | } 47 | 48 | public List getEvents() { 49 | return eventDao.getEvents(); 50 | } 51 | 52 | public CalendarUser getUser(int id) { 53 | return userDao.getUser(id); 54 | } 55 | 56 | public CalendarUser findUserByEmail(String email) { 57 | return userDao.findUserByEmail(email); 58 | } 59 | 60 | public List findUsersByEmail(String partialEmail) { 61 | return userDao.findUsersByEmail(partialEmail); 62 | } 63 | 64 | public int createUser(CalendarUser user) { 65 | return userDao.createUser(user); 66 | } 67 | } -------------------------------------------------------------------------------- /spring-security-cas/src/main/java/com/example/springsecurity/service/UserContext.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.service; 2 | 3 | import com.example.springsecurity.domain.CalendarUser; 4 | 5 | /** 6 | * Manages the current {@link CalendarUser}. This demonstrates how in larger applications it is good to abstract out 7 | * accessing the current user to return the application specific user rather than interacting with Spring Security 8 | * classes directly. 9 | * 10 | * 11 | * 12 | */ 13 | public interface UserContext { 14 | 15 | /** 16 | * Gets the currently logged in {@link CalendarUser} or null if there is no authenticated user. 17 | * 18 | * @return 19 | */ 20 | CalendarUser getCurrentUser(); 21 | 22 | /** 23 | * Sets the currently logged in {@link CalendarUser}. 24 | * @param user the logged in {@link CalendarUser}. Cannot be null. 25 | * @throws IllegalArgumentException if the {@link CalendarUser} is null. 26 | */ 27 | void setCurrentUser(CalendarUser user); 28 | } 29 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/java/com/example/springsecurity/service/UserContextStub.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Component; 5 | 6 | import com.example.springsecurity.dataaccess.CalendarUserDao; 7 | import com.example.springsecurity.domain.CalendarUser; 8 | 9 | /** 10 | * Returns the same user for every call to {@link #getCurrentUser()}. This is used prior to adding security, so that the 11 | * rest of the application can be used. 12 | * 13 | * 14 | */ 15 | @Component 16 | public class UserContextStub implements UserContext { 17 | private final CalendarUserDao userService; 18 | /** 19 | * The {@link CalendarUser#getId()} for the user that is representing the currently logged in user. This can be 20 | * modified using {@link #setCurrentUser(CalendarUser)} 21 | */ 22 | private int currentUserId = 0; 23 | 24 | @Autowired 25 | public UserContextStub(CalendarUserDao userService) { 26 | if (userService == null) { 27 | throw new IllegalArgumentException("userService cannot be null"); 28 | } 29 | this.userService = userService; 30 | } 31 | 32 | @Override 33 | public CalendarUser getCurrentUser() { 34 | return userService.getUser(currentUserId); 35 | } 36 | 37 | @Override 38 | public void setCurrentUser(CalendarUser user) { 39 | if (user == null) { 40 | throw new IllegalArgumentException("user cannot be null"); 41 | } 42 | Integer currentId = user.getId(); 43 | if(currentId == null) { 44 | throw new IllegalArgumentException("user.getId() cannot be null"); 45 | } 46 | this.currentUserId = currentId; 47 | } 48 | } -------------------------------------------------------------------------------- /spring-security-cas/src/main/java/com/example/springsecurity/web/controllers/EchoController.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.controllers; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.security.cas.authentication.CasAuthenticationToken; 7 | import org.springframework.security.core.context.SecurityContextHolder; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.ResponseBody; 11 | import org.springframework.web.client.RestOperations; 12 | import org.springframework.web.client.RestTemplate; 13 | 14 | /** 15 | * Demonstrates how to use a Proxy Ticket to call a service. This client will call the Calendar applications My Events 16 | * page and echo the JSON response back. 17 | * 18 | *

19 | * Note that this controller will not work until the entire Proxy Ticket authentication section has been completed. 20 | *

21 | * 22 | * 23 | * 24 | */ 25 | @Controller 26 | public class EchoController { 27 | 28 | private RestOperations restClient = new RestTemplate(); 29 | private String targetUrl; 30 | 31 | @ResponseBody 32 | @RequestMapping("/echo") 33 | public String echo() throws UnsupportedEncodingException { 34 | final CasAuthenticationToken token = (CasAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); 35 | // The proxyTicket could be cached in session and reused if we wanted to 36 | final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl); 37 | 38 | // Make a remote call using the proxy ticket 39 | return restClient.getForObject(targetUrl+"?ticket={pt}", String.class, proxyTicket); 40 | } 41 | 42 | @Value("#{environment['cas.service.host']}") 43 | public void setTargetHost(String targetHost) { 44 | this.targetUrl = "https://"+targetHost+"/calendar/events/my"; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/java/com/example/springsecurity/web/controllers/WelcomeController.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.controllers; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | 6 | /** 7 | * This displays the welcome screen that shows what will be happening in this chapter. 8 | * 9 | * 10 | * 11 | */ 12 | @Controller 13 | public class WelcomeController { 14 | 15 | @RequestMapping("/") 16 | public String welcome() { 17 | return "index"; 18 | } 19 | } -------------------------------------------------------------------------------- /spring-security-cas/src/main/java/com/example/springsecurity/web/model/CreateEventForm.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.model; 2 | 3 | import java.util.Calendar; 4 | 5 | import javax.validation.constraints.NotNull; 6 | 7 | import org.hibernate.validator.constraints.Email; 8 | import org.hibernate.validator.constraints.NotEmpty; 9 | import org.springframework.format.annotation.DateTimeFormat; 10 | 11 | import com.example.springsecurity.domain.Event; 12 | 13 | /** 14 | * A form object that is used for creating a new {@link Event}. Using a different object is one way of preventing 15 | * malicious users from filling out field that they should not (i.e. fill out a different owner field). 16 | * 17 | * 18 | * 19 | */ 20 | public class CreateEventForm { 21 | @NotEmpty(message = "Attendee Email is required") 22 | @Email(message = "Attendee Email must be a valid email") 23 | private String attendeeEmail; 24 | @NotEmpty(message = "Summary is required") 25 | private String summary; 26 | @NotEmpty(message = "Description is required") 27 | private String description; 28 | @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") 29 | @NotNull(message = "Event Date/Time is required") 30 | private Calendar when; 31 | 32 | public String getAttendeeEmail() { 33 | return attendeeEmail; 34 | } 35 | 36 | public void setAttendeeEmail(String attendeeEmail) { 37 | this.attendeeEmail = attendeeEmail; 38 | } 39 | 40 | public String getSummary() { 41 | return summary; 42 | } 43 | 44 | public void setSummary(String summary) { 45 | this.summary = summary; 46 | } 47 | 48 | public String getDescription() { 49 | return description; 50 | } 51 | 52 | public void setDescription(String description) { 53 | this.description = description; 54 | } 55 | 56 | public Calendar getWhen() { 57 | return when; 58 | } 59 | 60 | public void setWhen(Calendar when) { 61 | this.when = when; 62 | } 63 | } -------------------------------------------------------------------------------- /spring-security-cas/src/main/resources/database/h2/calendar-data.sql: -------------------------------------------------------------------------------- 1 | insert into calendar_users(id,email,password,first_name,last_name) values (0,'user1@example.com','user1','User','1'); 2 | insert into calendar_users(id,email,password,first_name,last_name) values (1,'admin1@example.com','admin1','Admin','1'); 3 | insert into calendar_users(id,email,password,first_name,last_name) values (2,'user2@example.com','user2','User','2'); 4 | 5 | insert into events (id,when,summary,description,owner,attendee) values (100,'2013-10-04 20:30:00','Birthday Party','This is going to be a great birthday',0,1); 6 | insert into events (id,when,summary,description,owner,attendee) values (101,'2013-12-23 13:00:00','Conference Call','Call with the client',2,0); 7 | insert into events (id,when,summary,description,owner,attendee) values (102,'2014-01-23 11:30:00','Lunch','Eating lunch together',1,2); -------------------------------------------------------------------------------- /spring-security-cas/src/main/resources/database/h2/calendar-schema.sql: -------------------------------------------------------------------------------- 1 | create table calendar_users ( 2 | id bigint identity, 3 | email varchar(256) not null unique, 4 | password varchar(256) not null, 5 | first_name varchar(256) not null, 6 | last_name varchar(256) not null 7 | ); 8 | 9 | create table events ( 10 | id bigint identity, 11 | when timestamp not null, 12 | summary varchar(256) not null, 13 | description varchar(500) not null, 14 | owner bigint not null, 15 | attendee bigint not null, 16 | FOREIGN KEY(owner) REFERENCES calendar_users(id), 17 | FOREIGN KEY(attendee) REFERENCES calendar_users(id) 18 | ); -------------------------------------------------------------------------------- /spring-security-cas/src/main/resources/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/webapp/WEB-INF/i18n/binding.properties: -------------------------------------------------------------------------------- 1 | typeMismatch.java.util.Date=Please enter a valid date in yyyy-MM-dd HH:mm format. 2 | typeMismatch.createEventForm.when=Please enter a valid date for Event Date/Time in yyyy-MM-dd HH:mm format. -------------------------------------------------------------------------------- /spring-security-cas/src/main/webapp/WEB-INF/mvc-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/webapp/WEB-INF/spring/i18n.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/webapp/WEB-INF/spring/security.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 25 | 26 | 27 | 28 | 29 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/webapp/WEB-INF/spring/services.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 27 | 28 | 31 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/webapp/WEB-INF/views/errors/403.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | 6 | 7 | 8 |

You are not allowed to access this page. Try logging in as admin1@example.com / admin1

9 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/webapp/WEB-INF/views/events/create.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 5 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 6 | 7 | 8 | 9 | 10 | 11 |
12 | Event Information 13 |
14 | 15 |
16 | 17 |
18 |
19 |
20 | 21 |
22 | 23 |
24 |
25 |
26 | 27 |
28 | 29 |
30 |
31 |
32 | 33 |
34 | 35 |
36 |
37 |
38 |
39 | 40 | 41 |
42 |
43 |
44 |
45 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/webapp/WEB-INF/views/events/list.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 6 | 7 | 8 | 9 | 10 |

This shows all events for all users. Once security is applied it will only be viewable to administrators.

11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
Date/TimeOwnerAttendeeSummary
No events.
40 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/webapp/WEB-INF/views/events/my.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 6 | 7 | 8 | 9 | 10 |

11 | Below you can find the events for 12 | . 13 | Once security is applied this will be the events for the currently logged in user. 14 |

15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 |
Date/TimeOwnerAttendeeSummary
No events.
44 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/webapp/WEB-INF/views/events/show.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 5 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 6 | <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 |
Owner
15 |
16 |
Attendee
17 |
18 |
When
19 | 20 |
21 |
Message Details
22 |
23 |
24 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/webapp/WEB-INF/views/includes/footer.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/webapp/WEB-INF/views/index.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | 6 | 7 | 8 |

Below you can find some highlights about myCalendar. Each sample will have a slightly different summary depending on what has been done.

9 |

Chapter 9 - CAS

10 |
    11 |
  • All Events - shows all events for all users, but only allows administrators to access the page.
  • 12 |
  • My Events - shows all events that the current user is owner or attendee.
  • 13 |
  • Create Event - will allow creating a new Event with current user as the owner.
  • 14 |
  • Logout - allows the user to logout (will not work until we enable Single Log Out)
  • 15 |
  • Echo - demonstrates Proxy Ticket Authentication (will not work till Proxy Ticket Authentication is setup)
  • 16 |
  • 17 | H2 Database Console - Allows you to interact with the database using a web console. To use it: 18 |
      19 |
    • Click the link above.
    • 20 |
    • Ensure that Generic H2 (Embedded) is selected
    • 21 |
    • Ensure that org.h2.Driver is the Driver Class
    • 22 |
    • Enter jdbc:h2:mem:dataSource as the JDBC URL
    • 23 |
    • Ensure that the username is sa
    • 24 |
    • Ensure the password is left empty
    • 25 |
    • Click Connect
    • 26 |
    27 |
  • 28 |
  • Test Single Logout - goes directly to the CAS server to test single logout
  • 29 |
30 | 31 | -------------------------------------------------------------------------------- /spring-security-cas/src/main/webapp/WEB-INF/views/login.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 |
13 | Failed to login. 14 | 15 | Reason: 16 | 17 |
18 |
19 | 20 |
21 | You have been logged out. 22 |
23 |
24 | 25 | 26 | 27 | 28 |
29 | 30 |
31 |
32 | -------------------------------------------------------------------------------- /spring-security-db/README.md: -------------------------------------------------------------------------------- 1 | Spring Security 2 | =============== 3 | 4 | To get up quickly, download the code and run the below commands, 5 | 6 | mvn clean test -Dtest=com.example.springsecurity.web.controllers.Video1SpringInmemoryUserdetailServiceControllerTest 7 | 8 | mvn clean test -Dtest=com.example.springsecurity.web.controllers.Video3JdbcUserServiceControllerTest 9 | 10 | And debug the code. -------------------------------------------------------------------------------- /spring-security-db/src/main/java/com/example/springsecurity/core/authority/CalendarUserAuthorityUtils.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.core.authority; 2 | 3 | import java.util.Collection; 4 | import java.util.List; 5 | 6 | import org.springframework.security.core.GrantedAuthority; 7 | import org.springframework.security.core.authority.AuthorityUtils; 8 | 9 | import com.example.springsecurity.domain.CalendarUser; 10 | 11 | /** 12 | * A utility class used for creating the {@link GrantedAuthority}'s given a {@link CalendarUser}. In a real solution 13 | * this would be looked up in the existing system, but for simplicity our original system had no notion of authorities. 14 | * 15 | * 16 | * 17 | */ 18 | public final class CalendarUserAuthorityUtils { 19 | private static final List ADMIN_ROLES = AuthorityUtils.createAuthorityList("ROLE_ADMIN", 20 | "ROLE_USER"); 21 | private static final List USER_ROLES = AuthorityUtils.createAuthorityList("ROLE_USER"); 22 | 23 | public static Collection createAuthorities(CalendarUser calendarUser) { 24 | String username = calendarUser.getEmail(); 25 | if (username.startsWith("admin")) { 26 | return ADMIN_ROLES; 27 | } 28 | return USER_ROLES; 29 | } 30 | 31 | private CalendarUserAuthorityUtils() { 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /spring-security-db/src/main/java/com/example/springsecurity/dataaccess/CalendarUserDao.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.dataaccess; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.dao.EmptyResultDataAccessException; 6 | 7 | import com.example.springsecurity.domain.CalendarUser; 8 | 9 | /** 10 | * An interface for managing {@link CalendarUser} instances. 11 | * 12 | * 13 | * 14 | */ 15 | public interface CalendarUserDao { 16 | 17 | /** 18 | * Gets a {@link CalendarUser} for a specific {@link CalendarUser#getId()}. 19 | * 20 | * @param id 21 | * the {@link CalendarUser#getId()} of the {@link CalendarUser} to find. 22 | * @return a {@link CalendarUser} for the given id. Cannot be null. 23 | * @throws EmptyResultDataAccessException 24 | * if the {@link CalendarUser} cannot be found 25 | */ 26 | CalendarUser getUser(int id); 27 | 28 | /** 29 | * Finds a given {@link CalendarUser} by email address. 30 | * 31 | * @param email 32 | * the email address to use to find a {@link CalendarUser}. Cannot be null. 33 | * @return a {@link CalendarUser} for the given email or null if one could not be found. 34 | * @throws IllegalArgumentException 35 | * if email is null. 36 | */ 37 | CalendarUser findUserByEmail(String email); 38 | 39 | 40 | /** 41 | * Finds any {@link CalendarUser} that has an email that starts with {@code partialEmail}. 42 | * 43 | * @param partialEmail 44 | * the email address to use to find {@link CalendarUser}s. Cannot be null or empty String. 45 | * @return a List of {@link CalendarUser}s that have an email that starts with given partialEmail. The returned value 46 | * will never be null. If no results are found an empty List will be returned. 47 | * @throws IllegalArgumentException 48 | * if email is null or empty String. 49 | */ 50 | List findUsersByEmail(String partialEmail); 51 | 52 | /** 53 | * Creates a new {@link CalendarUser}. 54 | * 55 | * @param user 56 | * the new {@link CalendarUser} to create. The {@link CalendarUser#getId()} must be null. 57 | * @return the new {@link CalendarUser#getId()}. 58 | * @throws IllegalArgumentException 59 | * if {@link CalendarUser#getId()} is non-null. 60 | */ 61 | int createUser(CalendarUser user); 62 | } 63 | -------------------------------------------------------------------------------- /spring-security-db/src/main/java/com/example/springsecurity/dataaccess/EventDao.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.dataaccess; 2 | 3 | import java.util.List; 4 | 5 | import com.example.springsecurity.domain.CalendarUser; 6 | import com.example.springsecurity.domain.Event; 7 | 8 | /** 9 | * An interface for managing {@link Event}'s. 10 | * 11 | * 12 | * 13 | */ 14 | public interface EventDao { 15 | 16 | /** 17 | * Given an id gets an {@link Event}. 18 | * 19 | * @param eventId 20 | * the {@link Event#getId()} 21 | * @return the {@link Event}. Cannot be null. 22 | * @throws RuntimeException 23 | * if the {@link Event} cannot be found. 24 | */ 25 | Event getEvent(int eventId); 26 | 27 | /** 28 | * Creates a {@link Event} and returns the new id for that {@link Event}. 29 | * 30 | * @param message 31 | * the {@link Event} to create. Note that the {@link Event#getId()} should be null. 32 | * @return the new id for the {@link Event} 33 | * @throws RuntimeException 34 | * if {@link Event#getId()} is non-null. 35 | */ 36 | int createEvent(Event event); 37 | 38 | /** 39 | * Finds the {@link Event}'s that are intended for the {@link CalendarUser}. 40 | * 41 | * @param userId 42 | * the {@link CalendarUser#getId()} to obtain {@link Event}'s for. 43 | * @return a non-null {@link List} of {@link Event}'s intended for the specified {@link CalendarUser}. If the 44 | * {@link CalendarUser} does not exist an empty List will be returned. 45 | */ 46 | List findForUser(int userId); 47 | 48 | /** 49 | * Gets all the available {@link Event}'s. 50 | * 51 | * @return a non-null {@link List} of {@link Event}'s 52 | */ 53 | List getEvents(); 54 | } 55 | -------------------------------------------------------------------------------- /spring-security-db/src/main/java/com/example/springsecurity/service/UserContext.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.service; 2 | 3 | import com.example.springsecurity.domain.CalendarUser; 4 | 5 | /** 6 | * Manages the current {@link CalendarUser}. This demonstrates how in larger applications it is good to abstract out 7 | * accessing the current user to return the application specific user rather than interacting with Spring Security 8 | * classes directly. 9 | * 10 | * 11 | * 12 | */ 13 | public interface UserContext { 14 | 15 | /** 16 | * Gets the currently logged in {@link CalendarUser} or null if there is no authenticated user. 17 | * 18 | * @return 19 | */ 20 | CalendarUser getCurrentUser(); 21 | 22 | /** 23 | * Sets the currently logged in {@link CalendarUser}. 24 | * @param user the logged in {@link CalendarUser}. Cannot be null. 25 | * @throws IllegalArgumentException if the {@link CalendarUser} is null. 26 | */ 27 | void setCurrentUser(CalendarUser user); 28 | } 29 | -------------------------------------------------------------------------------- /spring-security-db/src/main/java/com/example/springsecurity/service/UserContextStub.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | 5 | import com.example.springsecurity.dataaccess.CalendarUserDao; 6 | import com.example.springsecurity.domain.CalendarUser; 7 | 8 | /** 9 | * NOTE: This is no longer used. See {@link SpringSecurityUserContext}. 10 | * 11 | * Returns the same user for every call to {@link #getCurrentUser()}. This is used prior to adding security, so that the 12 | * rest of the application can be used. 13 | * 14 | * 15 | * @see SpringSecurityUserContext 16 | */ 17 | //@Component 18 | public class UserContextStub implements UserContext { 19 | private final CalendarUserDao userService; 20 | /** 21 | * The {@link CalendarUser#getId()} for the user that is representing the currently logged in user. This can be 22 | * modified using {@link #setCurrentUser(CalendarUser)} 23 | */ 24 | private int currentUserId = 0; 25 | 26 | @Autowired 27 | public UserContextStub(CalendarUserDao userService) { 28 | if (userService == null) { 29 | throw new IllegalArgumentException("userService cannot be null"); 30 | } 31 | this.userService = userService; 32 | } 33 | 34 | @Override 35 | public CalendarUser getCurrentUser() { 36 | return userService.getUser(currentUserId); 37 | } 38 | 39 | @Override 40 | public void setCurrentUser(CalendarUser user) { 41 | if (user == null) { 42 | throw new IllegalArgumentException("user cannot be null"); 43 | } 44 | Integer currentId = user.getId(); 45 | if(currentId == null) { 46 | throw new IllegalArgumentException("user.getId() cannot be null"); 47 | } 48 | this.currentUserId = currentId; 49 | } 50 | } -------------------------------------------------------------------------------- /spring-security-db/src/main/java/com/example/springsecurity/web/authentication/rememberme/JdbcTokenRepositoryImplCleaner.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.authentication.rememberme; 2 | 3 | import java.util.Date; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.jdbc.core.JdbcOperations; 8 | import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl; 9 | 10 | /** 11 | *

12 | * A {@link Runnable} which can be used to clean expired persistent remember me tokens generated from 13 | * {@link JdbcTokenRepositoryImpl}. Note that only a single cleanup is done in {@link #run()} so consumers must loop 14 | * over invoking the {@link #run()} method in order to perform multiple cleanups. 15 | *

16 | *

17 | * See the configuration file at src/main/webapp/WEB-INF/spring/cleaner.xml to learn how to hook in with Spring's 19 | * scheduling abstraction. 20 | *

21 | * 22 | * 23 | * 24 | */ 25 | public final class JdbcTokenRepositoryImplCleaner implements Runnable { 26 | private Logger logger = LoggerFactory.getLogger(getClass()); 27 | private final JdbcOperations jdbcOperations; 28 | private final long tokenValidityInMs; 29 | 30 | /** 31 | * 32 | * @param jdbcOperations 33 | * the {@link JdbcOperations} used to perform the cleanup. Cannot be null. 34 | * @param tokenValidityInMs 35 | * used to calculate when a token is expired. If the {@link #run()} method is invoked, tokens older than 36 | * this amount of time will be deleted. Cannot be less than 1. 37 | */ 38 | public JdbcTokenRepositoryImplCleaner(JdbcOperations jdbcOperations, long tokenValidityInMs) { 39 | if (jdbcOperations == null) { 40 | throw new IllegalArgumentException("jdbcOperations cannot be null"); 41 | } 42 | if (tokenValidityInMs < 1) { 43 | throw new IllegalArgumentException("tokenValidityInMs must be greater than 0. Got " + tokenValidityInMs); 44 | } 45 | this.jdbcOperations = jdbcOperations; 46 | this.tokenValidityInMs = tokenValidityInMs; 47 | } 48 | 49 | public void run() { 50 | long expiredInMs = System.currentTimeMillis() - tokenValidityInMs; 51 | try { 52 | jdbcOperations.update("delete from persistent_logins where last_used <= ?", new Date(expiredInMs)); 53 | }catch(Throwable t) { 54 | logger.error("Could not clean up expired persistent remember me tokens.",t); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /spring-security-db/src/main/java/com/example/springsecurity/web/controllers/WelcomeController.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.controllers; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | 6 | /** 7 | * This displays the welcome screen that shows what will be happening in this chapter. 8 | * 9 | * 10 | * 11 | */ 12 | @Controller 13 | public class WelcomeController { 14 | 15 | @RequestMapping("/") 16 | public String welcome() { 17 | return "index"; 18 | } 19 | } -------------------------------------------------------------------------------- /spring-security-db/src/main/java/com/example/springsecurity/web/model/CreateEventForm.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.model; 2 | 3 | import java.util.Calendar; 4 | 5 | import javax.validation.constraints.NotNull; 6 | 7 | import org.hibernate.validator.constraints.Email; 8 | import org.hibernate.validator.constraints.NotEmpty; 9 | import org.springframework.format.annotation.DateTimeFormat; 10 | 11 | import com.example.springsecurity.domain.Event; 12 | 13 | /** 14 | * A form object that is used for creating a new {@link Event}. Using a different object is one way of preventing 15 | * malicious users from filling out field that they should not (i.e. fill out a different owner field). 16 | * 17 | * 18 | * 19 | */ 20 | public class CreateEventForm { 21 | @NotEmpty(message = "Attendee Email is required") 22 | @Email(message = "Attendee Email must be a valid email") 23 | private String attendeeEmail; 24 | @NotEmpty(message = "Summary is required") 25 | private String summary; 26 | @NotEmpty(message = "Description is required") 27 | private String description; 28 | @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") 29 | @NotNull(message = "Event Date/Time is required") 30 | private Calendar when; 31 | 32 | public String getAttendeeEmail() { 33 | return attendeeEmail; 34 | } 35 | 36 | public void setAttendeeEmail(String attendeeEmail) { 37 | this.attendeeEmail = attendeeEmail; 38 | } 39 | 40 | public String getSummary() { 41 | return summary; 42 | } 43 | 44 | public void setSummary(String summary) { 45 | this.summary = summary; 46 | } 47 | 48 | public String getDescription() { 49 | return description; 50 | } 51 | 52 | public void setDescription(String description) { 53 | this.description = description; 54 | } 55 | 56 | public Calendar getWhen() { 57 | return when; 58 | } 59 | 60 | public void setWhen(Calendar when) { 61 | this.when = when; 62 | } 63 | } -------------------------------------------------------------------------------- /spring-security-db/src/main/java/com/example/springsecurity/web/model/SignupForm.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.model; 2 | 3 | import org.hibernate.validator.constraints.Email; 4 | import org.hibernate.validator.constraints.NotEmpty; 5 | 6 | 7 | public class SignupForm { 8 | @NotEmpty(message="First Name is required") 9 | private String firstName; 10 | @NotEmpty(message="Last Name is required") 11 | private String lastName; 12 | @Email(message="Please provide a valid email address") 13 | @NotEmpty(message="Email is required") 14 | private String email; 15 | @NotEmpty(message="Password is required") 16 | private String password; 17 | 18 | /** 19 | * Gets the email address for this user. 20 | * 21 | * @return 22 | */ 23 | public String getEmail() { 24 | return email; 25 | } 26 | 27 | /** 28 | * Gets the first name of the user. 29 | * 30 | * @return 31 | */ 32 | public String getFirstName() { 33 | return firstName; 34 | } 35 | 36 | /** 37 | * Gets the last name of the user. 38 | * 39 | * @return 40 | */ 41 | public String getLastName() { 42 | return lastName; 43 | } 44 | 45 | /** 46 | * Gets the password for this user. 47 | * 48 | * @return 49 | */ 50 | public String getPassword() { 51 | return password; 52 | } 53 | 54 | public void setEmail(String email) { 55 | this.email = email; 56 | } 57 | 58 | public void setFirstName(String firstName) { 59 | this.firstName = firstName; 60 | } 61 | public void setLastName(String lastName) { 62 | this.lastName = lastName; 63 | } 64 | 65 | public void setPassword(String password) { 66 | this.password = password; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /spring-security-db/src/main/resources/database/h2/calendar-data.sql: -------------------------------------------------------------------------------- 1 | insert into calendar_users(id,email,password,first_name,last_name) values (0,'user1@example.com','user1','User','1'); 2 | insert into calendar_users(id,email,password,first_name,last_name) values (1,'admin1@example.com','admin1','Admin','1'); 3 | insert into calendar_users(id,email,password,first_name,last_name) values (2,'user2@example.com','user2','User','2'); 4 | 5 | insert into events (id,when,summary,description,owner,attendee) values (100,'2013-10-04 20:30:00','Birthday Party','This is going to be a great birthday',0,1); 6 | insert into events (id,when,summary,description,owner,attendee) values (101,'2013-12-23 13:00:00','Conference Call','Call with the client',2,0); 7 | insert into events (id,when,summary,description,owner,attendee) values (102,'2014-01-23 11:30:00','Lunch','Eating lunch together',1,2); -------------------------------------------------------------------------------- /spring-security-db/src/main/resources/database/h2/calendar-schema.sql: -------------------------------------------------------------------------------- 1 | create table calendar_users ( 2 | id bigint identity, 3 | email varchar(256) not null unique, 4 | password varchar(256) not null, 5 | first_name varchar(256) not null, 6 | last_name varchar(256) not null 7 | ); 8 | 9 | create table events ( 10 | id bigint identity, 11 | when timestamp not null, 12 | summary varchar(256) not null, 13 | description varchar(500) not null, 14 | owner bigint not null, 15 | attendee bigint not null, 16 | FOREIGN KEY(owner) REFERENCES calendar_users(id), 17 | FOREIGN KEY(attendee) REFERENCES calendar_users(id) 18 | ); -------------------------------------------------------------------------------- /spring-security-db/src/main/resources/database/h2/security-rememberme-schema.sql: -------------------------------------------------------------------------------- 1 | create table persistent_logins ( 2 | username varchar_ignorecase(50) not null, 3 | series varchar(64) primary key, 4 | token varchar(64) not null, 5 | last_used timestamp not null 6 | ); 7 | -------------------------------------------------------------------------------- /spring-security-db/src/main/resources/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/i18n/binding.properties: -------------------------------------------------------------------------------- 1 | typeMismatch.java.util.Date=Please enter a valid date in yyyy-MM-dd HH:mm format. 2 | typeMismatch.createEventForm.when=Please enter a valid date for Event Date/Time in yyyy-MM-dd HH:mm format. -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/mvc-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/spring/cleaner.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 11 | 12 | 13 | 14 | 15 | 19 | 20 | 23 | 24 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/spring/i18n.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/spring/ipTokenRepository.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/spring/security.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 27 | 33 | 35 | 37 | 38 | 39 | 40 | 41 | 44 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/spring/services.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 28 | 29 | 32 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/views/errors/403.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | 6 | 7 | 8 |

You are not allowed to access this page. Try logging in as admin1@example.com / admin1

9 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/views/events/create.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 5 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 6 | 7 | 8 | 9 | 10 | 11 |
12 | Event Information 13 |
14 | 15 |
16 | 17 |
18 |
19 |
20 | 21 |
22 | 23 |
24 |
25 |
26 | 27 |
28 | 29 |
30 |
31 |
32 | 33 |
34 | 35 |
36 |
37 |
38 |
39 | 40 | 41 |
42 |
43 |
44 |
45 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/views/events/list.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 6 | 7 | 8 | 9 | 10 |

This shows all events for all users. Once security is applied it will only be viewable to administrators.

11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
Date/TimeOwnerAttendeeSummary
No events.
40 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/views/events/my.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 6 | 7 | 8 | 9 | 10 |

11 | Below you can find the events for 12 | . 13 | Once security is applied this will be the events for the currently logged in user. 14 |

15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 |
Date/TimeOwnerAttendeeSummary
No events.
44 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/views/events/show.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 5 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 6 | <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 |
Owner
15 |
16 |
Attendee
17 |
18 |
When
19 | 20 |
21 |
Message Details
22 |
23 |
24 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/views/includes/footer.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/views/index.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | 6 | 7 | 8 |

Below you can find some highlights about myCalendar. Each sample will have a slightly different summary depending on what has been done.

9 |

Chapter 6 - Remember Me

10 |
    11 |
  • This chapter discusses Spring Security's remember me feature. You may be interested in using a plugin like Firecookie for removing your JSESSIONID (to simulate closing the browser / session timing out).
  • 12 |
  • All Events - shows all events for all users, but only allows administrators to access the page.
  • 13 |
  • My Events - shows all events that the current user is owner or attendee.
  • 14 |
  • Create Event - will allow creating a new Event with current user as the owner.
  • 15 |
  • Logout - allows the user to logout
  • 16 |
  • 17 | H2 Database Console - Allows you to interact with the database using a web console. To use it: 18 |
      19 |
    • Click the link above.
    • 20 |
    • Ensure that Generic H2 (Embedded) is selected
    • 21 |
    • Ensure that org.h2.Driver is the Driver Class
    • 22 |
    • Enter jdbc:h2:mem:dataSource as the JDBC URL
    • 23 |
    • Ensure that the username is sa
    • 24 |
    • Ensure the password is left empty
    • 25 |
    • Click Connect
    • 26 |
    27 |
  • 28 |
29 | 30 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/views/login.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 |
13 | Failed to login. 14 | 15 | Reason: 16 | 17 |
18 |
19 | 20 |
21 | You have been logged out. 22 |
23 |
24 |

25 | 26 | 27 |

28 |

29 | 30 | 31 |

32 |

33 | 34 | 37 |

38 |

39 | 40 |

41 |
42 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/views/signup/form.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 5 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 6 | 7 | 8 | 9 | 10 | 11 |
12 | User Information 13 |

14 | 15 | 16 |

17 |

18 | 19 | 20 |

21 |

22 | 23 | 24 |

25 |

26 | 27 | 28 |

29 |

30 | 31 |

32 |
33 |
34 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | Calendar Web Application 7 | 8 | contextConfigLocation 9 | 10 | /WEB-INF/spring/services.xml 11 | /WEB-INF/spring/i18n.xml 12 | /WEB-INF/spring/security.xml 13 | /WEB-INF/spring/cleaner.xml 14 | /WEB-INF/spring/ipTokenRepository.xml 15 | 16 | 17 | 18 | org.springframework.web.context.ContextLoaderListener 19 | 20 | 21 | org.springframework.web.context.request.RequestContextListener 22 | 23 | 24 | springSecurityFilterChain 25 | org.springframework.web.filter.DelegatingFilterProxy 26 | 27 | 28 | springSecurityFilterChain 29 | /* 30 | 31 | 32 | h2 33 | org.h2.server.web.WebServlet 34 | 35 | 36 | Spring MVC Dispatcher Servlet 37 | org.springframework.web.servlet.DispatcherServlet 38 | 39 | contextConfigLocation 40 | 41 | /WEB-INF/mvc-config.xml 42 | 43 | 44 | 1 45 | 46 | 47 | h2 48 | /admin/h2/* 49 | 50 | 51 | Spring MVC Dispatcher Servlet 52 | / 53 | 54 | -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/resources/css/main.css: -------------------------------------------------------------------------------- 1 | * { 2 | margin: 0; 3 | padding: 0; 4 | } 5 | 6 | html, body { 7 | height: 100%; 8 | } 9 | body { 10 | background-color: #FFFFFF; 11 | } 12 | #header-container { 13 | color: #FFFFFF; 14 | background-color: #000000; 15 | } 16 | #header, .nav li { 17 | padding: .25em; 18 | padding-top: 2em; 19 | } 20 | .nav-account { 21 | float: right; 22 | } 23 | .nav { 24 | display: inline; 25 | } 26 | .inner { 27 | margin: 0 auto; 28 | width: 65%; 29 | padding: 1em; 30 | } 31 | .nav li:after { 32 | content: ' |'; 33 | } 34 | .nav li:last-child:after { 35 | content: ''; 36 | } 37 | 38 | .nav li { 39 | display: inline; 40 | list-style-type: none; 41 | } 42 | .nav a, th { 43 | color: #FFFFFF; 44 | } 45 | a:hover { 46 | text-decoration: none; 47 | } 48 | 49 | #title { 50 | margin: .25em 0; 51 | } 52 | 53 | #create { 54 | margin-top: 1em; 55 | float: right; 56 | } 57 | table { 58 | width: 100%; 59 | } 60 | 61 | tr:nth-child(even) { 62 | background-color: #EEEEEE; 63 | } 64 | 65 | th { 66 | background-color: #f79232; 67 | } 68 | td { 69 | padding: .25em; 70 | } 71 | #content li { 72 | margin: 1em; 73 | } 74 | legend { 75 | display: none; 76 | } 77 | fieldset { 78 | border-width: 0; 79 | } 80 | 81 | label { 82 | display: block; 83 | margin: .5em .5em .5em 0; 84 | font-weight: bold; 85 | } 86 | label[for=remember] { 87 | display: inline-block; 88 | } 89 | textarea { 90 | width: 95%; 91 | height: 10em; 92 | } 93 | input { 94 | padding: .15em; 95 | } 96 | input[type=text] { 97 | width: 25em; 98 | } 99 | #submit { 100 | margin-top: 1em; 101 | } 102 | 103 | .errors { 104 | color: red; 105 | } 106 | .success { 107 | color: green; 108 | font-weight: bold; 109 | font-size: 1.5em; 110 | } -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/resources/img/springsource.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skprasadu/spring-security-examples/dadd0da3a5c41dc600a72b800a0cf4fffc1fc18f/spring-security-db/src/main/webapp/resources/img/springsource.png -------------------------------------------------------------------------------- /spring-security-db/src/main/webapp/resources/img/ssbooklogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skprasadu/spring-security-examples/dadd0da3a5c41dc600a72b800a0cf4fffc1fc18f/spring-security-db/src/main/webapp/resources/img/ssbooklogo.png -------------------------------------------------------------------------------- /spring-security-db/src/test/java/com/example/springsecurity/web/controllers/Video1SpringInmemoryUserdetailServiceControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.controllers; 2 | 3 | import org.junit.runner.RunWith; 4 | import org.springframework.test.context.ContextConfiguration; 5 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 6 | 7 | import com.example.springsecurity.web.controllers.util.SecurityControllerTest; 8 | import com.example.springsecurity.web.controllers.util.WebContextLoader; 9 | 10 | @RunWith(SpringJUnit4ClassRunner.class) 11 | @ContextConfiguration(loader = WebContextLoader.class, value = { 12 | "classpath:/META-INF/spring/video1-spring-inmemory-userdetailservice-config/services.xml", 13 | "classpath:/META-INF/spring/video1-spring-inmemory-userdetailservice-config/security.xml", 14 | "classpath:/META-INF/spring/video1-spring-inmemory-userdetailservice-config/mvc-config.xml" }) 15 | public class Video1SpringInmemoryUserdetailServiceControllerTest extends SecurityControllerTest { 16 | } 17 | -------------------------------------------------------------------------------- /spring-security-db/src/test/java/com/example/springsecurity/web/controllers/Video2CustomUserDetailsServiceControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.controllers; 2 | 3 | import org.junit.runner.RunWith; 4 | import org.springframework.test.context.ContextConfiguration; 5 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 6 | 7 | import com.example.springsecurity.web.controllers.util.SecurityControllerTest; 8 | import com.example.springsecurity.web.controllers.util.WebContextLoader; 9 | 10 | @RunWith(SpringJUnit4ClassRunner.class) 11 | @ContextConfiguration(loader = WebContextLoader.class, value = { "classpath:/META-INF/spring/video2-custom-userdetailservice-config/services.xml", 12 | "classpath:/META-INF/spring/video2-custom-userdetailservice-config/security.xml", 13 | "classpath:/META-INF/spring/video2-custom-userdetailservice-config/mvc-config.xml", 14 | "classpath:/META-INF/spring/video2-custom-userdetailservice-config/ipTokenRepository.xml" }) 15 | public class Video2CustomUserDetailsServiceControllerTest extends SecurityControllerTest { 16 | } 17 | -------------------------------------------------------------------------------- /spring-security-db/src/test/java/com/example/springsecurity/web/controllers/Video3JdbcUserServiceControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.controllers; 2 | 3 | import org.junit.runner.RunWith; 4 | import org.springframework.test.context.ContextConfiguration; 5 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 6 | 7 | import com.example.springsecurity.web.controllers.util.SecurityControllerTest; 8 | import com.example.springsecurity.web.controllers.util.WebContextLoader; 9 | 10 | @RunWith(SpringJUnit4ClassRunner.class) 11 | @ContextConfiguration(loader = WebContextLoader.class, value = { "classpath:/META-INF/spring/video3-jdbc-user-service-config/services.xml", 12 | "classpath:/META-INF/spring/video3-jdbc-user-service-config/security.xml", 13 | "classpath:/META-INF/spring/video3-jdbc-user-service-config/mvc-config.xml" }) 14 | public class Video3JdbcUserServiceControllerTest extends SecurityControllerTest { 15 | } 16 | -------------------------------------------------------------------------------- /spring-security-db/src/test/java/com/example/springsecurity/web/controllers/util/WebContextLoader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2011 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.springsecurity.web.controllers.util; 17 | 18 | 19 | public class WebContextLoader extends GenericWebContextLoader { 20 | 21 | public WebContextLoader() { 22 | super("src/main/webapp", false); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video1-spring-inmemory-userdetailservice-config/mvc-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video1-spring-inmemory-userdetailservice-config/security.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 13 | 15 | 17 | 18 | 19 | 20 | 21 | 26 | 28 | 29 | 30 | 31 | 32 | 35 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video1-spring-inmemory-userdetailservice-config/services.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 27 | 28 | 31 | -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video2-custom-userdetailservice-config/cleaner.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 11 | 12 | 13 | 14 | 15 | 19 | 20 | 23 | 24 | -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video2-custom-userdetailservice-config/ipTokenRepository.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video2-custom-userdetailservice-config/mvc-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video2-custom-userdetailservice-config/security.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 27 | 33 | 35 | 37 | 38 | 39 | 40 | 41 | 44 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video2-custom-userdetailservice-config/services.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 28 | 29 | 32 | -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video3-jdbc-user-service-config/database/h2/calendar-authorities.sql: -------------------------------------------------------------------------------- 1 | create table calendar_user_authorities ( 2 | id bigint identity, 3 | calendar_user bigint not null, 4 | authority varchar(256) not null, 5 | ); 6 | 7 | -- user1@example.com 8 | insert into calendar_user_authorities(calendar_user, authority) select id,'ROLE_USER' from calendar_users where email='user1@example.com'; 9 | 10 | -- admin1@example.com 11 | insert into calendar_user_authorities(calendar_user, authority) select id,'ROLE_ADMIN' from calendar_users where email='admin1@example.com'; 12 | insert into calendar_user_authorities(calendar_user, authority) select id,'ROLE_USER' from calendar_users where email='admin1@example.com'; 13 | 14 | -- user2@example.com 15 | insert into calendar_user_authorities(calendar_user, authority) select id,'ROLE_USER' from calendar_users where email='user2@example.com'; 16 | -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video3-jdbc-user-service-config/database/h2/calendar-data.sql: -------------------------------------------------------------------------------- 1 | insert into calendar_users(id,email,password,first_name,last_name) values (0,'user1@example.com','user1','User','1'); 2 | insert into calendar_users(id,email,password,first_name,last_name) values (1,'admin1@example.com','admin1','Admin','1'); 3 | insert into calendar_users(id,email,password,first_name,last_name) values (2,'user2@example.com','user2','User','2'); 4 | 5 | insert into events (id,when,summary,description,owner,attendee) values (100,'2013-10-04 20:30:00','Birthday Party','This is going to be a great birthday',0,1); 6 | insert into events (id,when,summary,description,owner,attendee) values (101,'2013-12-23 13:00:00','Conference Call','Call with the client',2,0); 7 | insert into events (id,when,summary,description,owner,attendee) values (102,'2014-01-23 11:30:00','Lunch','Eating lunch together',1,2); -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video3-jdbc-user-service-config/database/h2/calendar-saltedsha256.sql: -------------------------------------------------------------------------------- 1 | update calendar_users set password = '38aab7ba97bd6bb2e51add1e5617eabfc8d13ec85c004e909eec4b70172437ae85e0c56e43fe51b0' where email = 'user1@example.com'; 2 | update calendar_users set password = '98afcd6f54569da7fea7fe4b1bf79d59dd27e559d38ee75cabd796f43058ebe15f201dfd453942e0' where email = 'admin1@example.com'; 3 | update calendar_users set password = '429d7af2097fb1a0a3a4050bff17d8189cb2244aef52476cad2fef3bcc7338078dbf73644494554a' where email = 'user2@example.com'; -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video3-jdbc-user-service-config/database/h2/calendar-schema.sql: -------------------------------------------------------------------------------- 1 | create table calendar_users ( 2 | id bigint identity, 3 | email varchar(256) not null unique, 4 | password varchar(256) not null, 5 | first_name varchar(256) not null, 6 | last_name varchar(256) not null 7 | ); 8 | 9 | create table events ( 10 | id bigint identity, 11 | when timestamp not null, 12 | summary varchar(256) not null, 13 | description varchar(500) not null, 14 | owner bigint not null, 15 | attendee bigint not null, 16 | FOREIGN KEY(owner) REFERENCES calendar_users(id), 17 | FOREIGN KEY(attendee) REFERENCES calendar_users(id) 18 | ); -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video3-jdbc-user-service-config/database/h2/calendar-sha256.sql: -------------------------------------------------------------------------------- 1 | update calendar_users set password = '0a041b9462caa4a31bac3567e0b6e6fd9100787db2ab433d96f6d178cabfce90' where email = 'user1@example.com'; 2 | update calendar_users set password = '25f43b1486ad95a1398e3eeb3d83bc4010015fcc9bedb35b432e00298d5021f7' where email = 'admin1@example.com'; 3 | update calendar_users set password = '6025d18fe48abd45168528f18a82e265dd98d421a7084aa09f61b341703901a3' where email = 'user2@example.com'; -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video3-jdbc-user-service-config/database/h2/security-groups-mappings.sql: -------------------------------------------------------------------------------- 1 | ----- 2 | -- Create the Groups 3 | insert into groups(group_name) values ('Users'); 4 | insert into groups(group_name) values ('Administrators'); 5 | 6 | ----- 7 | -- Map the Groups to Roles 8 | insert into group_authorities(group_id, authority) select id,'ROLE_USER' from groups where group_name='Users'; 9 | -- Administrators are both a ROLE_USER and ROLE_ADMIN 10 | insert into group_authorities(group_id, authority) select id,'ROLE_USER' from groups where group_name='Administrators'; 11 | insert into group_authorities(group_id, authority) select id,'ROLE_ADMIN' from groups where group_name='Administrators'; 12 | 13 | ----- 14 | -- Map the users to Groups 15 | insert into group_members(group_id, username) select id,'user1@example.com' from groups where group_name='Users'; 16 | insert into group_members(group_id, username) select id,'admin1@example.com' from groups where group_name='Administrators'; 17 | insert into group_members(group_id, username) select id,'user2@example.com' from groups where group_name='Users'; 18 | insert into group_members(group_id, username) select id,'disabled1@example.com' from groups where group_name='Users'; -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video3-jdbc-user-service-config/database/h2/security-groups-schema.sql: -------------------------------------------------------------------------------- 1 | 2 | create table groups ( 3 | id bigint generated by default as identity(start with 0) primary key, 4 | group_name varchar(256) not null 5 | ); 6 | 7 | create table group_authorities ( 8 | group_id bigint not null, 9 | authority varchar(50) not null, 10 | constraint fk_group_authorities_group foreign key(group_id) references groups(id) 11 | ); 12 | 13 | create table group_members ( 14 | id bigint generated by default as identity(start with 0) primary key, 15 | username varchar(50) not null, 16 | group_id bigint not null, 17 | constraint fk_group_members_group foreign key(group_id) references groups(id) 18 | ); -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video3-jdbc-user-service-config/database/h2/security-schema.sql: -------------------------------------------------------------------------------- 1 | -- ref. Appendix A of Spring Sec 3.1 manual 2 | 3 | create table users( 4 | username varchar(256) not null primary key, 5 | password varchar(256) not null, 6 | enabled boolean not null 7 | ); 8 | 9 | create table authorities ( 10 | username varchar(256) not null, 11 | authority varchar(256) not null, 12 | constraint fk_authorities_users foreign key(username) references users(username) 13 | ); 14 | create unique index ix_auth_username on authorities (username,authority); 15 | -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video3-jdbc-user-service-config/database/h2/security-user-authorities.sql: -------------------------------------------------------------------------------- 1 | insert into authorities(username,authority) values ('user1@example.com','ROLE_USER'); 2 | insert into authorities(username,authority) values ('admin1@example.com','ROLE_ADMIN'); 3 | insert into authorities(username,authority) values ('admin1@example.com','ROLE_USER'); 4 | insert into authorities(username,authority) values ('user2@example.com','ROLE_USER'); 5 | insert into authorities(username,authority) values ('disabled1@example.com','ROLE_USER'); -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video3-jdbc-user-service-config/database/h2/security-users.sql: -------------------------------------------------------------------------------- 1 | insert into users (username,password,enabled) values ('user1@example.com','user1',1); 2 | insert into users (username,password,enabled) values ('admin1@example.com','admin1',1); 3 | insert into users (username,password,enabled) values ('user2@example.com','admin1',1); 4 | insert into users (username,password,enabled) values ('disabled1@example.com','disabled1',0); -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video3-jdbc-user-service-config/mvc-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /spring-security-db/src/test/resources/META-INF/spring/video3-jdbc-user-service-config/services.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 33 | -------------------------------------------------------------------------------- /spring-security-ldap/README.md: -------------------------------------------------------------------------------- 1 | Spring Security 2 | =============== 3 | 4 | To get up quickly, download the code and run the below commands, 5 | 6 | mvn clean test -Dtest=com.example.springsecurity.web.controllers.Video4LdapProviderControlerTest 7 | 8 | And debug the code. -------------------------------------------------------------------------------- /spring-security-ldap/src/main/java/com/example/springsecurity/dataaccess/CalendarUserDao.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.dataaccess; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.dao.EmptyResultDataAccessException; 6 | 7 | import com.example.springsecurity.domain.CalendarUser; 8 | 9 | /** 10 | * An interface for managing {@link CalendarUser} instances. 11 | * 12 | * 13 | * 14 | */ 15 | public interface CalendarUserDao { 16 | 17 | /** 18 | * Gets a {@link CalendarUser} for a specific {@link CalendarUser#getId()}. 19 | * 20 | * @param id 21 | * the {@link CalendarUser#getId()} of the {@link CalendarUser} to find. 22 | * @return a {@link CalendarUser} for the given id. Cannot be null. 23 | * @throws EmptyResultDataAccessException 24 | * if the {@link CalendarUser} cannot be found 25 | */ 26 | CalendarUser getUser(int id); 27 | 28 | /** 29 | * Finds a given {@link CalendarUser} by email address. 30 | * 31 | * @param email 32 | * the email address to use to find a {@link CalendarUser}. Cannot be null. 33 | * @return a {@link CalendarUser} for the given email or null if one could not be found. 34 | * @throws IllegalArgumentException 35 | * if email is null. 36 | */ 37 | CalendarUser findUserByEmail(String email); 38 | 39 | 40 | /** 41 | * Finds any {@link CalendarUser} that has an email that starts with {@code partialEmail}. 42 | * 43 | * @param partialEmail 44 | * the email address to use to find {@link CalendarUser}s. Cannot be null or empty String. 45 | * @return a List of {@link CalendarUser}s that have an email that starts with given partialEmail. The returned value 46 | * will never be null. If no results are found an empty List will be returned. 47 | * @throws IllegalArgumentException 48 | * if email is null or empty String. 49 | */ 50 | List findUsersByEmail(String partialEmail); 51 | 52 | /** 53 | * Creates a new {@link CalendarUser}. 54 | * 55 | * @param user 56 | * the new {@link CalendarUser} to create. The {@link CalendarUser#getId()} must be null. 57 | * @return the new {@link CalendarUser#getId()}. 58 | * @throws IllegalArgumentException 59 | * if {@link CalendarUser#getId()} is non-null. 60 | */ 61 | int createUser(CalendarUser user); 62 | } 63 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/java/com/example/springsecurity/dataaccess/EventDao.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.dataaccess; 2 | 3 | import java.util.List; 4 | 5 | import com.example.springsecurity.domain.Event; 6 | import com.example.springsecurity.domain.CalendarUser; 7 | 8 | /** 9 | * An interface for managing {@link Event}'s. 10 | * 11 | * 12 | * 13 | */ 14 | public interface EventDao { 15 | 16 | /** 17 | * Given an id gets an {@link Event}. 18 | * 19 | * @param eventId 20 | * the {@link Event#getId()} 21 | * @return the {@link Event}. Cannot be null. 22 | * @throws RuntimeException 23 | * if the {@link Event} cannot be found. 24 | */ 25 | Event getEvent(int eventId); 26 | 27 | /** 28 | * Creates a {@link Event} and returns the new id for that {@link Event}. 29 | * 30 | * @param message 31 | * the {@link Event} to create. Note that the {@link Event#getId()} should be null. 32 | * @return the new id for the {@link Event} 33 | * @throws RuntimeException 34 | * if {@link Event#getId()} is non-null. 35 | */ 36 | int createEvent(Event event); 37 | 38 | /** 39 | * Finds the {@link Event}'s that are intended for the {@link CalendarUser}. 40 | * 41 | * @param userId 42 | * the {@link CalendarUser#getId()} to obtain {@link Event}'s for. 43 | * @return a non-null {@link List} of {@link Event}'s intended for the specified {@link CalendarUser}. If the 44 | * {@link CalendarUser} does not exist an empty List will be returned. 45 | */ 46 | List findForUser(int userId); 47 | 48 | /** 49 | * Gets all the available {@link Event}'s. 50 | * 51 | * @return a non-null {@link List} of {@link Event}'s 52 | */ 53 | List getEvents(); 54 | } 55 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/java/com/example/springsecurity/ldap/userdetails/ad/ActiveDirectoryLdapAuthoritiesPopulator.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.ldap.userdetails.ad; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.List; 6 | 7 | import org.springframework.ldap.core.DirContextOperations; 8 | import org.springframework.ldap.core.DistinguishedName; 9 | import org.springframework.ldap.core.LdapRdn; 10 | import org.springframework.security.core.GrantedAuthority; 11 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 12 | import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider; 13 | import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator; 14 | 15 | /** 16 | * An {@link LdapAuthoritiesPopulator} that is based on the {@link ActiveDirectoryLdapAuthenticationProvider}. The 17 | * implementation obtains the {@link GrantedAuthority}'s from the userData's memberOf attribute. It then uses the last 18 | * {@link LdapRdn}'s value as the {@link GrantedAuthority}. 19 | * 20 | * 21 | * @see ActiveDirectoryLdapAuthenticationProvider 22 | */ 23 | public final class ActiveDirectoryLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator { 24 | 25 | @Override 26 | public Collection getGrantedAuthorities(DirContextOperations userData, String username) { 27 | String[] groups = userData.getStringAttributes("memberOf"); 28 | List authorities = new ArrayList(); 29 | 30 | for (String group : groups) { 31 | LdapRdn authority = new DistinguishedName(group).removeLast(); 32 | authorities.add(new SimpleGrantedAuthority(authority.getValue())); 33 | } 34 | return authorities; 35 | } 36 | } -------------------------------------------------------------------------------- /spring-security-ldap/src/main/java/com/example/springsecurity/service/DefaultCalendarService.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.service; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import com.example.springsecurity.dataaccess.EventDao; 9 | import com.example.springsecurity.dataaccess.CalendarUserDao; 10 | import com.example.springsecurity.domain.Event; 11 | import com.example.springsecurity.domain.CalendarUser; 12 | 13 | /** 14 | * A default implementation of {@link CalendarService} that delegates to {@link EventDao} and {@link CalendarUserDao}. 15 | * 16 | * 17 | * 18 | */ 19 | @Repository 20 | public class DefaultCalendarService implements CalendarService { 21 | private final EventDao eventDao; 22 | private final CalendarUserDao userDao; 23 | 24 | @Autowired 25 | public DefaultCalendarService(EventDao eventDao, CalendarUserDao userDao) { 26 | if (eventDao == null) { 27 | throw new IllegalArgumentException("eventDao cannot be null"); 28 | } 29 | if (userDao == null) { 30 | throw new IllegalArgumentException("userDao cannot be null"); 31 | } 32 | this.eventDao = eventDao; 33 | this.userDao = userDao; 34 | } 35 | 36 | public Event getEvent(int eventId) { 37 | return eventDao.getEvent(eventId); 38 | } 39 | 40 | public int createEvent(Event event) { 41 | return eventDao.createEvent(event); 42 | } 43 | 44 | public List findForUser(int userId) { 45 | return eventDao.findForUser(userId); 46 | } 47 | 48 | public List getEvents() { 49 | return eventDao.getEvents(); 50 | } 51 | 52 | public CalendarUser getUser(int id) { 53 | return userDao.getUser(id); 54 | } 55 | 56 | public CalendarUser findUserByEmail(String email) { 57 | return userDao.findUserByEmail(email); 58 | } 59 | 60 | public List findUsersByEmail(String partialEmail) { 61 | return userDao.findUsersByEmail(partialEmail); 62 | } 63 | 64 | public int createUser(CalendarUser user) { 65 | return userDao.createUser(user); 66 | } 67 | } -------------------------------------------------------------------------------- /spring-security-ldap/src/main/java/com/example/springsecurity/service/UserContext.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.service; 2 | 3 | import com.example.springsecurity.domain.CalendarUser; 4 | 5 | /** 6 | * Manages the current {@link CalendarUser}. This demonstrates how in larger applications it is good to abstract out 7 | * accessing the current user to return the application specific user rather than interacting with Spring Security 8 | * classes directly. 9 | * 10 | * 11 | * 12 | */ 13 | public interface UserContext { 14 | 15 | /** 16 | * Gets the currently logged in {@link CalendarUser} or null if there is no authenticated user. 17 | * 18 | * @return 19 | */ 20 | CalendarUser getCurrentUser(); 21 | 22 | /** 23 | * Sets the currently logged in {@link CalendarUser}. 24 | * @param user the logged in {@link CalendarUser}. Cannot be null. 25 | * @throws IllegalArgumentException if the {@link CalendarUser} is null. 26 | */ 27 | void setCurrentUser(CalendarUser user); 28 | } 29 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/java/com/example/springsecurity/service/UserContextStub.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Component; 5 | 6 | import com.example.springsecurity.dataaccess.CalendarUserDao; 7 | import com.example.springsecurity.domain.CalendarUser; 8 | 9 | /** 10 | * Returns the same user for every call to {@link #getCurrentUser()}. This is used prior to adding security, so that the 11 | * rest of the application can be used. 12 | * 13 | * 14 | */ 15 | @Component 16 | public class UserContextStub implements UserContext { 17 | private final CalendarUserDao userService; 18 | /** 19 | * The {@link CalendarUser#getId()} for the user that is representing the currently logged in user. This can be 20 | * modified using {@link #setCurrentUser(CalendarUser)} 21 | */ 22 | private int currentUserId = 0; 23 | 24 | @Autowired 25 | public UserContextStub(CalendarUserDao userService) { 26 | if (userService == null) { 27 | throw new IllegalArgumentException("userService cannot be null"); 28 | } 29 | this.userService = userService; 30 | } 31 | 32 | @Override 33 | public CalendarUser getCurrentUser() { 34 | return userService.getUser(currentUserId); 35 | } 36 | 37 | @Override 38 | public void setCurrentUser(CalendarUser user) { 39 | if (user == null) { 40 | throw new IllegalArgumentException("user cannot be null"); 41 | } 42 | Integer currentId = user.getId(); 43 | if(currentId == null) { 44 | throw new IllegalArgumentException("user.getId() cannot be null"); 45 | } 46 | this.currentUserId = currentId; 47 | } 48 | } -------------------------------------------------------------------------------- /spring-security-ldap/src/main/java/com/example/springsecurity/web/controllers/AccountController.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.controllers; 2 | 3 | import org.springframework.security.core.Authentication; 4 | import org.springframework.security.core.context.SecurityContextHolder; 5 | import org.springframework.security.ldap.userdetails.InetOrgPerson; 6 | import org.springframework.security.ldap.userdetails.LdapUserDetails; 7 | import org.springframework.security.ldap.userdetails.Person; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.ui.Model; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | 12 | /** 13 | * A controller that allows for viewing of account information. 14 | * 15 | * 16 | * 17 | */ 18 | @Controller 19 | public class AccountController { 20 | @RequestMapping("/accounts/my") 21 | public String view(Model model) { 22 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 23 | if(authentication == null) { 24 | throw new IllegalStateException("authentication cannot be null. Make sure you are logged in."); 25 | } 26 | Object principal = authentication.getPrincipal(); 27 | model.addAttribute("user", principal); 28 | model.addAttribute("isLdapUserDetails", principal instanceof LdapUserDetails); 29 | model.addAttribute("isLdapPerson", principal instanceof Person); 30 | model.addAttribute("isLdapInetOrgPerson", principal instanceof InetOrgPerson); 31 | return "accounts/show"; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/java/com/example/springsecurity/web/controllers/WelcomeController.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.controllers; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | 6 | /** 7 | * This displays the welcome screen that shows what will be happening in this chapter. 8 | * 9 | * 10 | * 11 | */ 12 | @Controller 13 | public class WelcomeController { 14 | 15 | @RequestMapping("/") 16 | public String welcome() { 17 | return "index"; 18 | } 19 | } -------------------------------------------------------------------------------- /spring-security-ldap/src/main/java/com/example/springsecurity/web/model/CreateEventForm.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.model; 2 | 3 | import java.util.Calendar; 4 | 5 | import javax.validation.constraints.NotNull; 6 | 7 | import org.hibernate.validator.constraints.Email; 8 | import org.hibernate.validator.constraints.NotEmpty; 9 | import org.springframework.format.annotation.DateTimeFormat; 10 | 11 | import com.example.springsecurity.domain.Event; 12 | 13 | /** 14 | * A form object that is used for creating a new {@link Event}. Using a different object is one way of preventing 15 | * malicious users from filling out field that they should not (i.e. fill out a different owner field). 16 | * 17 | * 18 | * 19 | */ 20 | public class CreateEventForm { 21 | @NotEmpty(message = "Attendee Email is required") 22 | @Email(message = "Attendee Email must be a valid email") 23 | private String attendeeEmail; 24 | @NotEmpty(message = "Summary is required") 25 | private String summary; 26 | @NotEmpty(message = "Description is required") 27 | private String description; 28 | @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") 29 | @NotNull(message = "Event Date/Time is required") 30 | private Calendar when; 31 | 32 | public String getAttendeeEmail() { 33 | return attendeeEmail; 34 | } 35 | 36 | public void setAttendeeEmail(String attendeeEmail) { 37 | this.attendeeEmail = attendeeEmail; 38 | } 39 | 40 | public String getSummary() { 41 | return summary; 42 | } 43 | 44 | public void setSummary(String summary) { 45 | this.summary = summary; 46 | } 47 | 48 | public String getDescription() { 49 | return description; 50 | } 51 | 52 | public void setDescription(String description) { 53 | this.description = description; 54 | } 55 | 56 | public Calendar getWhen() { 57 | return when; 58 | } 59 | 60 | public void setWhen(Calendar when) { 61 | this.when = when; 62 | } 63 | } -------------------------------------------------------------------------------- /spring-security-ldap/src/main/resources/database/h2/calendar-data.sql: -------------------------------------------------------------------------------- 1 | insert into calendar_users(id,email,password,first_name,last_name) values (0,'user1@example.com','user1','User','1'); 2 | insert into calendar_users(id,email,password,first_name,last_name) values (1,'admin1@example.com','admin1','Admin','1'); 3 | insert into calendar_users(id,email,password,first_name,last_name) values (2,'user2@example.com','user2','User','2'); 4 | 5 | insert into events (id,when,summary,description,owner,attendee) values (100,'2013-10-04 20:30:00','Birthday Party','This is going to be a great birthday',0,1); 6 | insert into events (id,when,summary,description,owner,attendee) values (101,'2013-12-23 13:00:00','Conference Call','Call with the client',2,0); 7 | insert into events (id,when,summary,description,owner,attendee) values (102,'2014-01-23 11:30:00','Lunch','Eating lunch together',1,2); -------------------------------------------------------------------------------- /spring-security-ldap/src/main/resources/database/h2/calendar-schema.sql: -------------------------------------------------------------------------------- 1 | create table calendar_users ( 2 | id bigint identity, 3 | email varchar(256) not null unique, 4 | password varchar(256) not null, 5 | first_name varchar(256) not null, 6 | last_name varchar(256) not null 7 | ); 8 | 9 | create table events ( 10 | id bigint identity, 11 | when timestamp not null, 12 | summary varchar(256) not null, 13 | description varchar(500) not null, 14 | owner bigint not null, 15 | attendee bigint not null, 16 | FOREIGN KEY(owner) REFERENCES calendar_users(id), 17 | FOREIGN KEY(attendee) REFERENCES calendar_users(id) 18 | ); -------------------------------------------------------------------------------- /spring-security-ldap/src/main/resources/database/h2/security-rememberme-schema.sql: -------------------------------------------------------------------------------- 1 | create table persistent_logins ( 2 | username varchar_ignorecase(50) not null, 3 | series varchar(64) primary key, 4 | token varchar(64) not null, 5 | last_used timestamp not null 6 | ); 7 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/resources/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/i18n/binding.properties: -------------------------------------------------------------------------------- 1 | typeMismatch.java.util.Date=Please enter a valid date in yyyy-MM-dd HH:mm format. 2 | typeMismatch.createEventForm.when=Please enter a valid date for Event Date/Time in yyyy-MM-dd HH:mm format. -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/mvc-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/spring/cleaner.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 11 | 12 | 13 | 14 | 15 | 19 | 20 | 23 | 24 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/spring/i18n.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/spring/ipTokenRepository.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/spring/security.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 27 | 33 | 35 | 37 | 38 | 39 | 40 | 41 | 44 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/spring/services.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 28 | 29 | 32 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/views/errors/403.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | 6 | 7 | 8 |

You are not allowed to access this page. Try logging in as admin1@example.com / admin1

9 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/views/events/create.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 5 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 6 | 7 | 8 | 9 | 10 | 11 |
12 | Event Information 13 |
14 | 15 |
16 | 17 |
18 |
19 |
20 | 21 |
22 | 23 |
24 |
25 |
26 | 27 |
28 | 29 |
30 |
31 |
32 | 33 |
34 | 35 |
36 |
37 |
38 |
39 | 40 | 41 |
42 |
43 |
44 |
45 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/views/events/list.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 6 | 7 | 8 | 9 | 10 |

This shows all events for all users. Once security is applied it will only be viewable to administrators.

11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
Date/TimeOwnerAttendeeSummary
No events.
40 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/views/events/my.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 6 | 7 | 8 | 9 | 10 |

11 | Below you can find the events for 12 | . 13 | Once security is applied this will be the events for the currently logged in user. 14 |

15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 |
Date/TimeOwnerAttendeeSummary
No events.
44 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/views/events/show.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 5 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 6 | <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 |
Owner
15 |
16 |
Attendee
17 |
18 |
When
19 | 20 |
21 |
Message Details
22 |
23 |
24 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/views/includes/footer.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/views/index.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | 6 | 7 | 8 |

Below you can find some highlights about myCalendar. Each sample will have a slightly different summary depending on what has been done.

9 |

Chapter 6 - Remember Me

10 |
    11 |
  • This chapter discusses Spring Security's remember me feature. You may be interested in using a plugin like Firecookie for removing your JSESSIONID (to simulate closing the browser / session timing out).
  • 12 |
  • All Events - shows all events for all users, but only allows administrators to access the page.
  • 13 |
  • My Events - shows all events that the current user is owner or attendee.
  • 14 |
  • Create Event - will allow creating a new Event with current user as the owner.
  • 15 |
  • Logout - allows the user to logout
  • 16 |
  • 17 | H2 Database Console - Allows you to interact with the database using a web console. To use it: 18 |
      19 |
    • Click the link above.
    • 20 |
    • Ensure that Generic H2 (Embedded) is selected
    • 21 |
    • Ensure that org.h2.Driver is the Driver Class
    • 22 |
    • Enter jdbc:h2:mem:dataSource as the JDBC URL
    • 23 |
    • Ensure that the username is sa
    • 24 |
    • Ensure the password is left empty
    • 25 |
    • Click Connect
    • 26 |
    27 |
  • 28 |
29 | 30 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/views/login.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 |
13 | Failed to login. 14 | 15 | Reason: 16 | 17 |
18 |
19 | 20 |
21 | You have been logged out. 22 |
23 |
24 |

25 | 26 | 27 |

28 |

29 | 30 | 31 |

32 |

33 | 34 | 37 |

38 |

39 | 40 |

41 |
42 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/views/signup/form.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 5 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 6 | 7 | 8 | 9 | 10 | 11 |
12 | User Information 13 |

14 | 15 | 16 |

17 |

18 | 19 | 20 |

21 |

22 | 23 | 24 |

25 |

26 | 27 | 28 |

29 |

30 | 31 |

32 |
33 |
34 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | Calendar Web Application 7 | 8 | contextConfigLocation 9 | 10 | /WEB-INF/spring/services.xml 11 | /WEB-INF/spring/i18n.xml 12 | /WEB-INF/spring/security.xml 13 | /WEB-INF/spring/cleaner.xml 14 | /WEB-INF/spring/ipTokenRepository.xml 15 | 16 | 17 | 18 | org.springframework.web.context.ContextLoaderListener 19 | 20 | 21 | org.springframework.web.context.request.RequestContextListener 22 | 23 | 24 | springSecurityFilterChain 25 | org.springframework.web.filter.DelegatingFilterProxy 26 | 27 | 28 | springSecurityFilterChain 29 | /* 30 | 31 | 32 | h2 33 | org.h2.server.web.WebServlet 34 | 35 | 36 | Spring MVC Dispatcher Servlet 37 | org.springframework.web.servlet.DispatcherServlet 38 | 39 | contextConfigLocation 40 | 41 | /WEB-INF/mvc-config.xml 42 | 43 | 44 | 1 45 | 46 | 47 | h2 48 | /admin/h2/* 49 | 50 | 51 | Spring MVC Dispatcher Servlet 52 | / 53 | 54 | -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/resources/css/main.css: -------------------------------------------------------------------------------- 1 | * { 2 | margin: 0; 3 | padding: 0; 4 | } 5 | 6 | html, body { 7 | height: 100%; 8 | } 9 | body { 10 | background-color: #FFFFFF; 11 | } 12 | #header-container { 13 | color: #FFFFFF; 14 | background-color: #000000; 15 | } 16 | #header, .nav li { 17 | padding: .25em; 18 | padding-top: 2em; 19 | } 20 | .nav-account { 21 | float: right; 22 | } 23 | .nav { 24 | display: inline; 25 | } 26 | .inner { 27 | margin: 0 auto; 28 | width: 65%; 29 | padding: 1em; 30 | } 31 | .nav li:after { 32 | content: ' |'; 33 | } 34 | .nav li:last-child:after { 35 | content: ''; 36 | } 37 | 38 | .nav li { 39 | display: inline; 40 | list-style-type: none; 41 | } 42 | .nav a, th { 43 | color: #FFFFFF; 44 | } 45 | a:hover { 46 | text-decoration: none; 47 | } 48 | 49 | #title { 50 | margin: .25em 0; 51 | } 52 | 53 | #create { 54 | margin-top: 1em; 55 | float: right; 56 | } 57 | table { 58 | width: 100%; 59 | } 60 | 61 | tr:nth-child(even) { 62 | background-color: #EEEEEE; 63 | } 64 | 65 | th { 66 | background-color: #f79232; 67 | } 68 | td { 69 | padding: .25em; 70 | } 71 | #content li { 72 | margin: 1em; 73 | } 74 | legend { 75 | display: none; 76 | } 77 | fieldset { 78 | border-width: 0; 79 | } 80 | 81 | label { 82 | display: block; 83 | margin: .5em .5em .5em 0; 84 | font-weight: bold; 85 | } 86 | label[for=remember] { 87 | display: inline-block; 88 | } 89 | textarea { 90 | width: 95%; 91 | height: 10em; 92 | } 93 | input { 94 | padding: .15em; 95 | } 96 | input[type=text] { 97 | width: 25em; 98 | } 99 | #submit { 100 | margin-top: 1em; 101 | } 102 | 103 | .errors { 104 | color: red; 105 | } 106 | .success { 107 | color: green; 108 | font-weight: bold; 109 | font-size: 1.5em; 110 | } -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/resources/img/springsource.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skprasadu/spring-security-examples/dadd0da3a5c41dc600a72b800a0cf4fffc1fc18f/spring-security-ldap/src/main/webapp/resources/img/springsource.png -------------------------------------------------------------------------------- /spring-security-ldap/src/main/webapp/resources/img/ssbooklogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skprasadu/spring-security-examples/dadd0da3a5c41dc600a72b800a0cf4fffc1fc18f/spring-security-ldap/src/main/webapp/resources/img/ssbooklogo.png -------------------------------------------------------------------------------- /spring-security-ldap/src/test/java/com/example/springsecurity/web/controllers/Video4LdapProviderControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.controllers; 2 | 3 | import org.junit.runner.RunWith; 4 | import org.springframework.test.context.ContextConfiguration; 5 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 6 | 7 | import com.example.springsecurity.web.controllers.util.LdapSecurityControllerTest; 8 | import com.example.springsecurity.web.controllers.util.WebContextLoader; 9 | 10 | @RunWith(SpringJUnit4ClassRunner.class) 11 | @ContextConfiguration(loader = WebContextLoader.class, value = { "classpath:/META-INF/spring/video4-ldap-provider-config/services.xml", 12 | "classpath:/META-INF/spring/video4-ldap-provider-config/security.xml", 13 | "classpath:/META-INF/spring/video4-ldap-provider-config/mvc-config.xml", 14 | "classpath:/META-INF/spring/video4-ldap-provider-config/security-ldap-explicitly.xml" }) 15 | public class Video4LdapProviderControllerTest extends LdapSecurityControllerTest { 16 | } 17 | -------------------------------------------------------------------------------- /spring-security-ldap/src/test/java/com/example/springsecurity/web/controllers/util/WebContextLoader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2011 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.springsecurity.web.controllers.util; 17 | 18 | 19 | public class WebContextLoader extends GenericWebContextLoader { 20 | 21 | public WebContextLoader() { 22 | super("src/main/webapp", false); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /spring-security-ldap/src/test/resources/META-INF/spring/video4-ldap-provider-config/database/h2/calendar-data.sql: -------------------------------------------------------------------------------- 1 | insert into calendar_users(id,email,password,first_name,last_name) values (0,'user1@example.com','user1','User','1'); 2 | insert into calendar_users(id,email,password,first_name,last_name) values (1,'admin1@example.com','admin1','Admin','1'); 3 | insert into calendar_users(id,email,password,first_name,last_name) values (2,'user2@example.com','user2','User','2'); 4 | 5 | insert into events (id,when,summary,description,owner,attendee) values (100,'2013-10-04 20:30:00','Birthday Party','This is going to be a great birthday',0,1); 6 | insert into events (id,when,summary,description,owner,attendee) values (101,'2013-12-23 13:00:00','Conference Call','Call with the client',2,0); 7 | insert into events (id,when,summary,description,owner,attendee) values (102,'2014-01-23 11:30:00','Lunch','Eating lunch together',1,2); -------------------------------------------------------------------------------- /spring-security-ldap/src/test/resources/META-INF/spring/video4-ldap-provider-config/database/h2/calendar-schema.sql: -------------------------------------------------------------------------------- 1 | create table calendar_users ( 2 | id bigint identity, 3 | email varchar(256) not null unique, 4 | password varchar(256) not null, 5 | first_name varchar(256) not null, 6 | last_name varchar(256) not null 7 | ); 8 | 9 | create table events ( 10 | id bigint identity, 11 | when timestamp not null, 12 | summary varchar(256) not null, 13 | description varchar(500) not null, 14 | owner bigint not null, 15 | attendee bigint not null, 16 | FOREIGN KEY(owner) REFERENCES calendar_users(id), 17 | FOREIGN KEY(attendee) REFERENCES calendar_users(id) 18 | ); -------------------------------------------------------------------------------- /spring-security-ldap/src/test/resources/META-INF/spring/video4-ldap-provider-config/mvc-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /spring-security-ldap/src/test/resources/META-INF/spring/video4-ldap-provider-config/security-ldap-explicitly.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 8 | 9 | 10 | 11 | 12 | 13 | 15 | 16 | 17 | 18 | 19 | 21 | 22 | 23 | 24 | 25 | 26 | 28 | 29 | 31 | 32 | -------------------------------------------------------------------------------- /spring-security-ldap/src/test/resources/META-INF/spring/video4-ldap-provider-config/security.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 20 | 21 | 22 | 23 | 24 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /spring-security-ldap/src/test/resources/META-INF/spring/video4-ldap-provider-config/services.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 27 | 28 | 31 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/README.md: -------------------------------------------------------------------------------- 1 | Spring Security 2 | =============== 3 | 4 | To get up quickly, download the code and run the below commands, 5 | 6 | mvn test -Dtest=com.example.springsecurity.web.controllers.SecurityControllerTest 7 | 8 | And debug the code. -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/java/com/example/springsecurity/core/authority/CalendarUserAuthorityUtils.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.core.authority; 2 | 3 | import java.util.Collection; 4 | import java.util.List; 5 | 6 | import org.springframework.security.core.GrantedAuthority; 7 | import org.springframework.security.core.authority.AuthorityUtils; 8 | 9 | import com.example.springsecurity.domain.CalendarUser; 10 | 11 | /** 12 | * A utility class used for creating the {@link GrantedAuthority}'s given a {@link CalendarUser}. In a real solution 13 | * this would be looked up in the existing system, but for simplicity our original system had no notion of authorities. 14 | * 15 | * 16 | * 17 | */ 18 | public final class CalendarUserAuthorityUtils { 19 | private static final List ADMIN_ROLES = AuthorityUtils.createAuthorityList("ROLE_ADMIN", 20 | "ROLE_USER"); 21 | private static final List USER_ROLES = AuthorityUtils.createAuthorityList("ROLE_USER"); 22 | 23 | public static Collection createAuthorities(CalendarUser calendarUser) { 24 | String username = calendarUser.getEmail(); 25 | if (username.startsWith("admin")) { 26 | return ADMIN_ROLES; 27 | } 28 | return USER_ROLES; 29 | } 30 | 31 | private CalendarUserAuthorityUtils() { 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/java/com/example/springsecurity/dataaccess/CalendarUserDao.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.dataaccess; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.dao.EmptyResultDataAccessException; 6 | 7 | import com.example.springsecurity.domain.CalendarUser; 8 | 9 | /** 10 | * An interface for managing {@link CalendarUser} instances. 11 | * 12 | * 13 | * 14 | */ 15 | public interface CalendarUserDao { 16 | 17 | /** 18 | * Gets a {@link CalendarUser} for a specific {@link CalendarUser#getId()}. 19 | * 20 | * @param id 21 | * the {@link CalendarUser#getId()} of the {@link CalendarUser} to find. 22 | * @return a {@link CalendarUser} for the given id. Cannot be null. 23 | * @throws EmptyResultDataAccessException 24 | * if the {@link CalendarUser} cannot be found 25 | */ 26 | CalendarUser getUser(int id); 27 | 28 | /** 29 | * Finds a given {@link CalendarUser} by email address. 30 | * 31 | * @param email 32 | * the email address to use to find a {@link CalendarUser}. Cannot be null. 33 | * @return a {@link CalendarUser} for the given email or null if one could not be found. 34 | * @throws IllegalArgumentException 35 | * if email is null. 36 | */ 37 | CalendarUser findUserByEmail(String email); 38 | 39 | 40 | /** 41 | * Finds any {@link CalendarUser} that has an email that starts with {@code partialEmail}. 42 | * 43 | * @param partialEmail 44 | * the email address to use to find {@link CalendarUser}s. Cannot be null or empty String. 45 | * @return a List of {@link CalendarUser}s that have an email that starts with given partialEmail. The returned value 46 | * will never be null. If no results are found an empty List will be returned. 47 | * @throws IllegalArgumentException 48 | * if email is null or empty String. 49 | */ 50 | List findUsersByEmail(String partialEmail); 51 | 52 | /** 53 | * Creates a new {@link CalendarUser}. 54 | * 55 | * @param user 56 | * the new {@link CalendarUser} to create. The {@link CalendarUser#getId()} must be null. 57 | * @return the new {@link CalendarUser#getId()}. 58 | * @throws IllegalArgumentException 59 | * if {@link CalendarUser#getId()} is non-null. 60 | */ 61 | int createUser(CalendarUser user); 62 | } 63 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/java/com/example/springsecurity/dataaccess/EventDao.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.dataaccess; 2 | 3 | import java.util.List; 4 | 5 | import com.example.springsecurity.domain.Event; 6 | import com.example.springsecurity.domain.CalendarUser; 7 | 8 | /** 9 | * An interface for managing {@link Event}'s. 10 | * 11 | * 12 | * 13 | */ 14 | public interface EventDao { 15 | 16 | /** 17 | * Given an id gets an {@link Event}. 18 | * 19 | * @param eventId 20 | * the {@link Event#getId()} 21 | * @return the {@link Event}. Cannot be null. 22 | * @throws RuntimeException 23 | * if the {@link Event} cannot be found. 24 | */ 25 | Event getEvent(int eventId); 26 | 27 | /** 28 | * Creates a {@link Event} and returns the new id for that {@link Event}. 29 | * 30 | * @param message 31 | * the {@link Event} to create. Note that the {@link Event#getId()} should be null. 32 | * @return the new id for the {@link Event} 33 | * @throws RuntimeException 34 | * if {@link Event#getId()} is non-null. 35 | */ 36 | int createEvent(Event event); 37 | 38 | /** 39 | * Finds the {@link Event}'s that are intended for the {@link CalendarUser}. 40 | * 41 | * @param userId 42 | * the {@link CalendarUser#getId()} to obtain {@link Event}'s for. 43 | * @return a non-null {@link List} of {@link Event}'s intended for the specified {@link CalendarUser}. If the 44 | * {@link CalendarUser} does not exist an empty List will be returned. 45 | */ 46 | List findForUser(int userId); 47 | 48 | /** 49 | * Gets all the available {@link Event}'s. 50 | * 51 | * @return a non-null {@link List} of {@link Event}'s 52 | */ 53 | List getEvents(); 54 | } 55 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/java/com/example/springsecurity/service/DefaultCalendarService.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.service; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | 7 | import com.example.springsecurity.dataaccess.CalendarUserDao; 8 | import com.example.springsecurity.dataaccess.EventDao; 9 | import com.example.springsecurity.domain.CalendarUser; 10 | import com.example.springsecurity.domain.Event; 11 | 12 | /** 13 | * A default implementation of {@link CalendarService} that delegates to {@link EventDao} and {@link CalendarUserDao}. 14 | * 15 | * 16 | * 17 | */ 18 | public class DefaultCalendarService implements CalendarService { 19 | private final EventDao eventDao; 20 | private final CalendarUserDao userDao; 21 | 22 | @Autowired 23 | public DefaultCalendarService(EventDao eventDao, CalendarUserDao userDao) { 24 | if (eventDao == null) { 25 | throw new IllegalArgumentException("eventDao cannot be null"); 26 | } 27 | if (userDao == null) { 28 | throw new IllegalArgumentException("userDao cannot be null"); 29 | } 30 | this.eventDao = eventDao; 31 | this.userDao = userDao; 32 | } 33 | 34 | public Event getEvent(int eventId) { 35 | return eventDao.getEvent(eventId); 36 | } 37 | 38 | public int createEvent(Event event) { 39 | return eventDao.createEvent(event); 40 | } 41 | 42 | public List findForUser(int userId) { 43 | return eventDao.findForUser(userId); 44 | } 45 | 46 | public List getEvents() { 47 | return eventDao.getEvents(); 48 | } 49 | 50 | public CalendarUser getUser(int id) { 51 | return userDao.getUser(id); 52 | } 53 | 54 | public CalendarUser findUserByEmail(String email) { 55 | return userDao.findUserByEmail(email); 56 | } 57 | 58 | public List findUsersByEmail(String partialEmail) { 59 | return userDao.findUsersByEmail(partialEmail); 60 | } 61 | 62 | public int createUser(CalendarUser user) { 63 | return userDao.createUser(user); 64 | } 65 | } -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/java/com/example/springsecurity/service/SpringSecurityUserContext.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.service; 2 | 3 | import java.util.Collection; 4 | 5 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 6 | import org.springframework.security.core.Authentication; 7 | import org.springframework.security.core.GrantedAuthority; 8 | import org.springframework.security.core.context.SecurityContext; 9 | import org.springframework.security.core.context.SecurityContextHolder; 10 | import org.springframework.stereotype.Component; 11 | 12 | import com.example.springsecurity.core.authority.CalendarUserAuthorityUtils; 13 | import com.example.springsecurity.domain.CalendarUser; 14 | 15 | /** 16 | * An implementation of {@link UserContext} that looks up the {@link CalendarUser} using the Spring Security's 17 | * {@link Authentication} by principal name. 18 | * 19 | * 20 | * 21 | */ 22 | @Component 23 | public class SpringSecurityUserContext implements UserContext { 24 | /** 25 | * Get the {@link CalendarUser} by casting the {@link Authentication}'s principal to a {@link CalendarUser}. 26 | */ 27 | @Override 28 | public CalendarUser getCurrentUser() { 29 | SecurityContext context = SecurityContextHolder.getContext(); 30 | Authentication authentication = context.getAuthentication(); 31 | if (authentication == null) { 32 | return null; 33 | } 34 | return (CalendarUser) authentication.getPrincipal(); 35 | } 36 | 37 | /** 38 | * Sets the {@link CalendarUser} as the current {@link Authentication}'s principal. It uses 39 | */ 40 | @Override 41 | public void setCurrentUser(CalendarUser user) { 42 | if (user == null) { 43 | throw new IllegalArgumentException("user cannot be null"); 44 | } 45 | Collection authorities = CalendarUserAuthorityUtils.createAuthorities(user); 46 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, 47 | user.getPassword(),authorities); 48 | SecurityContextHolder.getContext().setAuthentication(authentication); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/java/com/example/springsecurity/service/UserContext.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.service; 2 | 3 | import com.example.springsecurity.domain.CalendarUser; 4 | 5 | /** 6 | * Manages the current {@link CalendarUser}. This demonstrates how in larger applications it is good to abstract out 7 | * accessing the current user to return the application specific user rather than interacting with Spring Security 8 | * classes directly. 9 | * 10 | * 11 | * 12 | */ 13 | public interface UserContext { 14 | 15 | /** 16 | * Gets the currently logged in {@link CalendarUser} or null if there is no authenticated user. 17 | * 18 | * @return 19 | */ 20 | CalendarUser getCurrentUser(); 21 | 22 | /** 23 | * Sets the currently logged in {@link CalendarUser}. 24 | * @param user the logged in {@link CalendarUser}. Cannot be null. 25 | * @throws IllegalArgumentException if the {@link CalendarUser} is null. 26 | */ 27 | void setCurrentUser(CalendarUser user); 28 | } 29 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/java/com/example/springsecurity/service/UserContextStub.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Component; 5 | 6 | import com.example.springsecurity.dataaccess.CalendarUserDao; 7 | import com.example.springsecurity.domain.CalendarUser; 8 | 9 | /** 10 | * NOTE: This is no longer used. See {@link SpringSecurityUserContext}. 11 | * 12 | * Returns the same user for every call to {@link #getCurrentUser()}. This is used prior to adding security, so that the 13 | * rest of the application can be used. 14 | * 15 | * 16 | * @see SpringSecurityUserContext 17 | */ 18 | //@Component 19 | public class UserContextStub implements UserContext { 20 | private final CalendarUserDao userService; 21 | /** 22 | * The {@link CalendarUser#getId()} for the user that is representing the currently logged in user. This can be 23 | * modified using {@link #setCurrentUser(CalendarUser)} 24 | */ 25 | private int currentUserId = 0; 26 | 27 | @Autowired 28 | public UserContextStub(CalendarUserDao userService) { 29 | if (userService == null) { 30 | throw new IllegalArgumentException("userService cannot be null"); 31 | } 32 | this.userService = userService; 33 | } 34 | 35 | @Override 36 | public CalendarUser getCurrentUser() { 37 | return userService.getUser(currentUserId); 38 | } 39 | 40 | @Override 41 | public void setCurrentUser(CalendarUser user) { 42 | if (user == null) { 43 | throw new IllegalArgumentException("user cannot be null"); 44 | } 45 | Integer currentId = user.getId(); 46 | if(currentId == null) { 47 | throw new IllegalArgumentException("user.getId() cannot be null"); 48 | } 49 | this.currentUserId = currentId; 50 | } 51 | } -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/java/com/example/springsecurity/web/model/CreateEventForm.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.model; 2 | 3 | import java.util.Calendar; 4 | 5 | import javax.validation.constraints.NotNull; 6 | 7 | import org.hibernate.validator.constraints.Email; 8 | import org.hibernate.validator.constraints.NotEmpty; 9 | import org.springframework.format.annotation.DateTimeFormat; 10 | 11 | import com.example.springsecurity.domain.Event; 12 | 13 | /** 14 | * A form object that is used for creating a new {@link Event}. Using a different object is one way of preventing 15 | * malicious users from filling out field that they should not (i.e. fill out a different owner field). 16 | * 17 | * 18 | * 19 | */ 20 | public class CreateEventForm { 21 | @NotEmpty(message = "Attendee Email is required") 22 | @Email(message = "Attendee Email must be a valid email") 23 | private String attendeeEmail; 24 | @NotEmpty(message = "Summary is required") 25 | private String summary; 26 | @NotEmpty(message = "Description is required") 27 | private String description; 28 | @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") 29 | @NotNull(message = "Event Date/Time is required") 30 | private Calendar when; 31 | 32 | public String getAttendeeEmail() { 33 | return attendeeEmail; 34 | } 35 | 36 | public void setAttendeeEmail(String attendeeEmail) { 37 | this.attendeeEmail = attendeeEmail; 38 | } 39 | 40 | public String getSummary() { 41 | return summary; 42 | } 43 | 44 | public void setSummary(String summary) { 45 | this.summary = summary; 46 | } 47 | 48 | public String getDescription() { 49 | return description; 50 | } 51 | 52 | public void setDescription(String description) { 53 | this.description = description; 54 | } 55 | 56 | public Calendar getWhen() { 57 | return when; 58 | } 59 | 60 | public void setWhen(Calendar when) { 61 | this.when = when; 62 | } 63 | } -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/java/com/example/springsecurity/web/model/SignupForm.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.model; 2 | 3 | import org.hibernate.validator.constraints.Email; 4 | import org.hibernate.validator.constraints.NotEmpty; 5 | 6 | 7 | public class SignupForm { 8 | @NotEmpty(message="First Name is required") 9 | private String firstName; 10 | @NotEmpty(message="Last Name is required") 11 | private String lastName; 12 | @Email(message="Please provide a valid email address") 13 | @NotEmpty(message="Email is required") 14 | private String email; 15 | @NotEmpty(message="Password is required") 16 | private String password; 17 | 18 | /** 19 | * Gets the email address for this user. 20 | * 21 | * @return 22 | */ 23 | public String getEmail() { 24 | return email; 25 | } 26 | 27 | /** 28 | * Gets the first name of the user. 29 | * 30 | * @return 31 | */ 32 | public String getFirstName() { 33 | return firstName; 34 | } 35 | 36 | /** 37 | * Gets the last name of the user. 38 | * 39 | * @return 40 | */ 41 | public String getLastName() { 42 | return lastName; 43 | } 44 | 45 | /** 46 | * Gets the password for this user. 47 | * 48 | * @return 49 | */ 50 | public String getPassword() { 51 | return password; 52 | } 53 | 54 | public void setEmail(String email) { 55 | this.email = email; 56 | } 57 | 58 | public void setFirstName(String firstName) { 59 | this.firstName = firstName; 60 | } 61 | public void setLastName(String lastName) { 62 | this.lastName = lastName; 63 | } 64 | 65 | public void setPassword(String password) { 66 | this.password = password; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/resources/database/h2/calendar-data.sql: -------------------------------------------------------------------------------- 1 | insert into calendar_users(id,email,password,first_name,last_name) values (0,'user1@example.com','user1','User','1'); 2 | insert into calendar_users(id,email,password,first_name,last_name) values (1,'admin1@example.com','admin1','Admin','1'); 3 | insert into calendar_users(id,email,password,first_name,last_name) values (2,'user2@example.com','user2','User','2'); 4 | 5 | insert into events (id,when,summary,description,owner,attendee) values (100,'2013-10-04 20:30:00','Birthday Party','This is going to be a great birthday',0,1); 6 | insert into events (id,when,summary,description,owner,attendee) values (101,'2013-12-23 13:00:00','Conference Call','Call with the client',2,0); 7 | insert into events (id,when,summary,description,owner,attendee) values (102,'2014-01-23 11:30:00','Lunch','Eating lunch together',1,2); -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/resources/database/h2/calendar-schema.sql: -------------------------------------------------------------------------------- 1 | create table calendar_users ( 2 | id bigint identity, 3 | email varchar(256) not null unique, 4 | password varchar(256) not null, 5 | first_name varchar(256) not null, 6 | last_name varchar(256) not null 7 | ); 8 | 9 | create table events ( 10 | id bigint identity, 11 | when timestamp not null, 12 | summary varchar(256) not null, 13 | description varchar(500) not null, 14 | owner bigint not null, 15 | attendee bigint not null, 16 | FOREIGN KEY(owner) REFERENCES calendar_users(id), 17 | FOREIGN KEY(attendee) REFERENCES calendar_users(id) 18 | ); -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/resources/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/i18n/binding.properties: -------------------------------------------------------------------------------- 1 | typeMismatch.java.util.Date=Please enter a valid date in yyyy-MM-dd HH:mm format. 2 | typeMismatch.createEventForm.when=Please enter a valid date for Event Date/Time in yyyy-MM-dd HH:mm format. -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/mvc-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/spring/i18n.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/spring/security.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 10 | 11 | 12 | 13 | 15 | 17 | 19 | 21 | 23 | 25 | 27 | 29 | 30 | 36 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/views/errors/403.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | 6 | 7 | 8 |

You are not allowed to access this page. Try logging in as admin1@example.com / admin1

9 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/views/events/create.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 5 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 6 | 7 | 8 | 9 | 10 | 11 |
12 | Event Information 13 |
14 | 15 |
16 | 17 |
18 |
19 |
20 | 21 |
22 | 23 |
24 |
25 |
26 | 27 |
28 | 29 |
30 |
31 |
32 | 33 |
34 | 35 |
36 |
37 |
38 |
39 | 40 | 41 |
42 |
43 |
44 |
45 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/views/events/list.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 6 | 7 | 8 | 9 | 10 |

This shows all events for all users. Once security is applied it will only be viewable to administrators.

11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
Date/TimeOwnerAttendeeSummary
No events.
40 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/views/events/my.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 6 | 7 | 8 | 9 | 10 |

11 | Below you can find the events for 12 | . 13 | Notice it is updated depending on which user you are logged in as. 14 |

15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 |
Date/TimeOwnerAttendeeSummary
No events.
44 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/views/events/show.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 5 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 6 | <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 |
Owner
15 |
16 |
Attendee
17 |
18 |
When
19 | 20 |
21 |
Message Details
22 |
23 |
24 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/views/includes/footer.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/views/index.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | 6 | 7 | 8 |

Below you can find some highlights about myCalendar. Each sample will have a slightly different summary depending on what has been done.

9 |

Chapter 10

10 |
    11 |
  • This chapter demonstrates fine grained access control
  • 12 |
  • All Events - shows all events for all users, but only allows administrators to access the page.
  • 13 |
  • My Events - shows all events for the current user's events.
  • 14 |
  • My Events (userId=0) - shows all events that are associated to user1@example.com.
  • 15 |
  • My Events (userId=1) - shows all events that are associated to admin1@exmple.com.
  • 16 |
  • Lunch Event
  • 17 | 18 |
  • Create Event - Allows creating an Event with the current user.
  • 19 |
    20 |
  • Logout - we haven't discussed it yet, but you can logout using j_spring_security_logout. Later in in this chapter we will discuss how to customize logout and provide a logout link.
  • 21 | 22 |
  • 23 | H2 Database Console - Allows you to interact with the database using a web console. To use it: 24 |
      25 |
    • Click the link above.
    • 26 |
    • Ensure that Generic H2 (Embedded) is selected
    • 27 |
    • Ensure that org.h2.Driver is the Driver Class
    • 28 |
    • Enter jdbc:h2:mem:dataSource as the JDBC URL
    • 29 |
    • Ensure that the username is sa
    • 30 |
    • Ensure the password is left empty
    • 31 |
    • Click Connect
    • 32 |
    33 |
  • 34 |
    35 |
36 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/views/login.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 |
13 | Failed to login. 14 | 15 | Reason: 16 | 17 |
18 |
19 | 20 |
21 | You have been logged out. 22 |
23 |
24 | 25 | 26 | 27 | 28 |
29 | 30 |
31 |
32 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/views/signup/form.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 3 | pageEncoding="ISO-8859-1"%> 4 | <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 5 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 6 | 7 | 8 | 9 | 10 | 11 |
12 | User Information 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 |
24 |
25 |
26 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | Calendar Web Application 7 | 8 | contextConfigLocation 9 | 10 | /WEB-INF/spring/services.xml 11 | /WEB-INF/spring/i18n.xml 12 | /WEB-INF/spring/security.xml 13 | 14 | 15 | 16 | org.springframework.web.context.ContextLoaderListener 17 | 18 | 19 | springSecurityFilterChain 20 | org.springframework.web.filter.DelegatingFilterProxy 21 | 22 | 23 | springSecurityFilterChain 24 | /* 25 | 26 | 27 | h2 28 | org.h2.server.web.WebServlet 29 | 30 | 31 | Spring MVC Dispatcher Servlet 32 | org.springframework.web.servlet.DispatcherServlet 33 | 34 | contextConfigLocation 35 | 36 | /WEB-INF/mvc-config.xml 37 | 38 | 39 | 1 40 | 41 | 42 | h2 43 | /admin/h2/* 44 | 45 | 46 | Spring MVC Dispatcher Servlet 47 | / 48 | 49 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/test/java/com/example/springsecurity/web/controllers/SecurityControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.controllers; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.access.AccessDeniedException; 7 | import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; 8 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 9 | import org.springframework.security.core.Authentication; 10 | import org.springframework.security.core.context.SecurityContext; 11 | import org.springframework.security.core.context.SecurityContextHolder; 12 | import org.springframework.test.context.ContextConfiguration; 13 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 14 | 15 | import com.example.springsecurity.service.CalendarService; 16 | 17 | @RunWith(SpringJUnit4ClassRunner.class) 18 | @ContextConfiguration(loader = WebContextLoader.class, value = { "classpath:/META-INF/spring/services.xml", 19 | "classpath:/META-INF/spring/security.xml", 20 | "classpath:/META-INF/spring/mvc-config.xml" }) 21 | public class SecurityControllerTest { 22 | 23 | @Autowired 24 | CalendarService calendarService; 25 | 26 | @Test 27 | public void testMyEvents() throws Exception { 28 | Authentication auth = new UsernamePasswordAuthenticationToken("user1@example.com", "user1"); 29 | SecurityContext securityContext = SecurityContextHolder.getContext(); 30 | securityContext.setAuthentication(auth); 31 | 32 | calendarService.findForUser(0); 33 | SecurityContextHolder.clearContext(); 34 | } 35 | 36 | @Test(expected = AuthenticationCredentialsNotFoundException.class) 37 | public void testForbiddenEvents() throws Exception { 38 | calendarService.findForUser(0); 39 | } 40 | 41 | @Test(expected=AccessDeniedException.class) 42 | public void testWrongUserEvents() throws Exception { 43 | Authentication auth = new UsernamePasswordAuthenticationToken("user2@example.com", "user2"); 44 | SecurityContext securityContext = SecurityContextHolder.getContext(); 45 | securityContext.setAuthentication(auth); 46 | 47 | calendarService.findForUser(0); 48 | SecurityContextHolder.clearContext(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/test/java/com/example/springsecurity/web/controllers/WebContextLoader.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecurity.web.controllers; 2 | 3 | /* 4 | * Copyright 2011 the original author or authors. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | 20 | 21 | public class WebContextLoader extends GenericWebContextLoader { 22 | 23 | public WebContextLoader() { 24 | super("src/main/webapp", false); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/test/resources/META-INF/spring/mvc-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/test/resources/META-INF/spring/security.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 10 | 11 | 12 | 13 | 15 | 17 | 19 | 21 | 23 | 25 | 27 | 29 | 30 | 36 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /spring-security-methodlevel-security/src/test/resources/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | --------------------------------------------------------------------------------