├── .gitignore ├── src ├── main │ ├── java │ │ └── ltistarter │ │ │ ├── model │ │ │ ├── README.md │ │ │ ├── BaseEntity.java │ │ │ ├── ConfigEntity.java │ │ │ ├── LmsPluginsEntity.java │ │ │ ├── LtiMembershipEntity.java │ │ │ ├── KeyRequestEntity.java │ │ │ ├── SSOKeyEntity.java │ │ │ ├── LtiServiceEntity.java │ │ │ ├── LtiLinkEntity.java │ │ │ ├── LtiContextEntity.java │ │ │ ├── LtiKeyEntity.java │ │ │ ├── ProfileEntity.java │ │ │ ├── LtiUserEntity.java │ │ │ └── LtiResultEntity.java │ │ │ ├── oauth │ │ │ ├── MyOAuthNonceServices.java │ │ │ ├── ZeroLeggedOAuthProviderProcessingFilter.java │ │ │ ├── MyOAuthProcessingFilterEntryPointImpl.java │ │ │ ├── MyConsumerDetailsService.java │ │ │ ├── OAuthUtils.java │ │ │ └── MyOAuthAuthenticationHandler.java │ │ │ ├── ServletInitializer.java │ │ │ ├── controllers │ │ │ ├── OpenController.java │ │ │ ├── OAuthController.java │ │ │ ├── BasicController.java │ │ │ ├── HomeController.java │ │ │ ├── LTI2Controller.java │ │ │ ├── BaseController.java │ │ │ ├── FormController.java │ │ │ └── LTIController.java │ │ │ ├── repository │ │ │ ├── LtiLinkRepository.java │ │ │ ├── LtiUserRepository.java │ │ │ ├── LtiMembershipRepository.java │ │ │ ├── ProfileRepository.java │ │ │ ├── KeyRequestRepository.java │ │ │ ├── LtiServiceRepository.java │ │ │ ├── LtiResultRepository.java │ │ │ ├── SSOKeyRepository.java │ │ │ ├── LtiKeyRepository.java │ │ │ ├── LtiContextRepository.java │ │ │ ├── ConfigRepository.java │ │ │ └── AllRepositories.java │ │ │ ├── database │ │ │ └── DatabasePreload.java │ │ │ ├── lti │ │ │ ├── LTIOAuthProviderProcessingFilter.java │ │ │ ├── LTIConsumerDetailsService.java │ │ │ └── LTIOAuthAuthenticationHandler.java │ │ │ ├── config │ │ │ └── ApplicationConfig.java │ │ │ └── Application.java │ └── resources │ │ ├── logback-sample.xml │ │ ├── templates │ │ ├── login.html │ │ ├── register.html │ │ └── home.html │ │ └── application.properties └── test │ └── java │ └── ltistarter │ ├── ApplicationTests.java │ ├── BaseApplicationTest.java │ ├── oauth │ └── OAuth1LibraryTests.java │ ├── controllers │ └── AppControllersTest.java │ └── lti │ └── LTITests.java ├── LICENSE_HEADER ├── README.md ├── pom.xml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | # editor (intellij) 3 | .idea/ 4 | *.iml 5 | # Mobile Tools for Java (J2ME) 6 | .mtj.tmp/ 7 | # Package Files # 8 | *.jar 9 | *.war 10 | *.ear 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/README.md: -------------------------------------------------------------------------------- 1 | WARNING 2 | ======= 3 | These entities are from the tsugi project and should be kept in alignment with that project. Do not change these unless you really know what you are doing! 4 | 5 | tsugi (https://github.com/csev/tsugi) is a Multi-tenant learning tool hosting platform (http://www.tsugi.org) 6 | 7 | Aaron Zeckoski (azeckoski @ vt.edu) 8 | -------------------------------------------------------------------------------- /LICENSE_HEADER: -------------------------------------------------------------------------------- 1 | Copyright ${year} ${holder} 2 | Licensed under the Apache License, Version 2.0 (the "License"); 3 | you may not use this file except in compliance with the License. 4 | You may obtain a copy of the License at 5 | 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | 8 | Unless required by applicable law or agreed to in writing, software 9 | distributed under the License is distributed on an "AS IS" BASIS, 10 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | See the License for the specific language governing permissions and 12 | limitations under the License. -------------------------------------------------------------------------------- /src/main/resources/logback-sample.xml: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/oauth/MyOAuthNonceServices.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.oauth; 16 | 17 | import org.springframework.security.oauth.provider.nonce.InMemoryNonceServices; 18 | import org.springframework.stereotype.Component; 19 | 20 | @Component 21 | public class MyOAuthNonceServices extends InMemoryNonceServices { 22 | 23 | @Override 24 | public long getValidityWindowSeconds() { 25 | return 1200; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/ServletInitializer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter; 16 | 17 | import org.springframework.boot.builder.SpringApplicationBuilder; 18 | import org.springframework.boot.context.web.SpringBootServletInitializer; 19 | 20 | public class ServletInitializer extends SpringBootServletInitializer { 21 | 22 | @Override 23 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 24 | return application.sources(Application.class); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/resources/templates/login.html: -------------------------------------------------------------------------------- 1 | 17 | 18 | 19 | 20 | 21 | LTI Starter LOGIN 22 | 23 | 24 | 25 |

Simple login page

26 | 27 |

Wrong user or password

28 | 29 |
30 | : 31 |
32 | : 33 |
34 | 35 |
36 | 37 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/controllers/OpenController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.controllers; 16 | 17 | import org.springframework.stereotype.Controller; 18 | import org.springframework.ui.Model; 19 | import org.springframework.web.bind.annotation.RequestMapping; 20 | 21 | import javax.servlet.http.HttpServletRequest; 22 | import java.security.Principal; 23 | 24 | /** 25 | * This controller should be protected by no auth (it is public access) 26 | */ 27 | @Controller 28 | @RequestMapping("/open") 29 | public class OpenController extends BaseController { 30 | 31 | @RequestMapping({"", "/"}) 32 | public String home(HttpServletRequest req, Principal principal, Model model) { 33 | commonModelPopulate(req, principal, model); 34 | model.addAttribute("name", "open (no auth)"); 35 | return "home"; // name of the template 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /src/main/resources/templates/register.html: -------------------------------------------------------------------------------- 1 | 17 | 18 | 19 | 21 | 22 | LTI 2.0 Tool Registration 23 | 24 | 36 | 37 | 38 | 39 |

LTI 2.0 Registration

40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/repository/LtiLinkRepository.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.repository; 16 | 17 | import ltistarter.model.LtiLinkEntity; 18 | import org.springframework.data.repository.PagingAndSortingRepository; 19 | import org.springframework.transaction.annotation.Transactional; 20 | 21 | @Transactional 22 | public interface LtiLinkRepository extends PagingAndSortingRepository { 23 | /* Add custom crud methods here 24 | * If you need a custom implementation of the methods then see docs for steps to add it 25 | * http://docs.spring.io/spring-data/data-commons/docs/current/reference/html/repositories.html 26 | * Can also write a custom query like so: 27 | * @Query("SELECT u FROM User u WHERE u.alias IS NOT NULL") 28 | * List findAliased(); 29 | * OR: 30 | * @Query("SELECT u FROM User u WHERE u.alias = ?1") 31 | * List findWithAlias(String alias); 32 | */ 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/repository/LtiUserRepository.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.repository; 16 | 17 | import ltistarter.model.LtiUserEntity; 18 | import org.springframework.data.repository.PagingAndSortingRepository; 19 | import org.springframework.transaction.annotation.Transactional; 20 | 21 | @Transactional 22 | public interface LtiUserRepository extends PagingAndSortingRepository { 23 | /* Add custom crud methods here 24 | * If you need a custom implementation of the methods then see docs for steps to add it 25 | * http://docs.spring.io/spring-data/data-commons/docs/current/reference/html/repositories.html 26 | * Can also write a custom query like so: 27 | * @Query("SELECT u FROM User u WHERE u.alias IS NOT NULL") 28 | * List findAliased(); 29 | * OR: 30 | * @Query("SELECT u FROM User u WHERE u.alias = ?1") 31 | * List findWithAlias(String alias); 32 | */ 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/controllers/OAuthController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.controllers; 16 | 17 | import org.springframework.stereotype.Controller; 18 | import org.springframework.ui.Model; 19 | import org.springframework.web.bind.annotation.RequestMapping; 20 | 21 | import javax.servlet.http.HttpServletRequest; 22 | import java.security.Principal; 23 | 24 | /** 25 | * This controller should be protected by OAuth 1.0a (on the /oauth path) 26 | * Key "key" and secret "secret" 27 | */ 28 | @Controller 29 | @RequestMapping("/oauth") 30 | public class OAuthController extends BaseController { 31 | 32 | @RequestMapping({"", "/"}) 33 | public String home(HttpServletRequest req, Principal principal, Model model) { 34 | commonModelPopulate(req, principal, model); 35 | model.addAttribute("name", "oauth"); 36 | req.getSession().setAttribute("login", "basic"); 37 | return "home"; // name of the template 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /src/main/java/ltistarter/repository/LtiMembershipRepository.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.repository; 16 | 17 | import ltistarter.model.LtiMembershipEntity; 18 | import org.springframework.data.repository.PagingAndSortingRepository; 19 | import org.springframework.transaction.annotation.Transactional; 20 | 21 | @Transactional 22 | public interface LtiMembershipRepository extends PagingAndSortingRepository { 23 | /* Add custom crud methods here 24 | * If you need a custom implementation of the methods then see docs for steps to add it 25 | * http://docs.spring.io/spring-data/data-commons/docs/current/reference/html/repositories.html 26 | * Can also write a custom query like so: 27 | * @Query("SELECT u FROM User u WHERE u.alias IS NOT NULL") 28 | * List findAliased(); 29 | * OR: 30 | * @Query("SELECT u FROM User u WHERE u.alias = ?1") 31 | * List findWithAlias(String alias); 32 | */ 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/controllers/BasicController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.controllers; 16 | 17 | import org.springframework.stereotype.Controller; 18 | import org.springframework.ui.Model; 19 | import org.springframework.web.bind.annotation.RequestMapping; 20 | 21 | import javax.servlet.http.HttpServletRequest; 22 | import java.security.Principal; 23 | 24 | /** 25 | * This controller should be protected by basic auth authentication (on the /basic path) 26 | * Username and password controlled in application.properties 27 | */ 28 | @Controller 29 | @RequestMapping("/basic") 30 | public class BasicController extends BaseController { 31 | 32 | @RequestMapping({"", "/"}) 33 | public String home(HttpServletRequest req, Principal principal, Model model) { 34 | commonModelPopulate(req, principal, model); 35 | model.addAttribute("name", "basic"); 36 | req.getSession().setAttribute("login", "basic"); 37 | return "home"; // name of the template 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /src/main/java/ltistarter/repository/ProfileRepository.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.repository; 16 | 17 | import ltistarter.model.ProfileEntity; 18 | import org.springframework.data.repository.PagingAndSortingRepository; 19 | import org.springframework.transaction.annotation.Transactional; 20 | 21 | @Transactional 22 | public interface ProfileRepository extends PagingAndSortingRepository { 23 | /* Add custom crud methods here 24 | * If you need a custom implementation of the methods then see docs for steps to add it 25 | * http://docs.spring.io/spring-data/data-commons/docs/current/reference/html/repositories.html 26 | * Can also write a custom query like so: 27 | * @Query("SELECT u FROM User u WHERE u.alias IS NOT NULL") 28 | * List findAliased(); 29 | * OR: 30 | * @Query("SELECT u FROM User u WHERE u.alias = ?1") 31 | * List findWithAlias(String alias); 32 | */ 33 | 34 | ProfileEntity findByProfileKey(String profileKey); 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/controllers/HomeController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.controllers; 16 | 17 | import org.springframework.stereotype.Controller; 18 | import org.springframework.ui.Model; 19 | import org.springframework.web.bind.annotation.RequestMapping; 20 | import org.springframework.web.bind.annotation.RequestMethod; 21 | 22 | import javax.servlet.http.HttpServletRequest; 23 | import java.security.Principal; 24 | 25 | /** 26 | * This is the default home (i.e. root or "/") controller which should be wide open 27 | * (no security) 28 | */ 29 | @Controller 30 | public class HomeController extends BaseController { 31 | 32 | @RequestMapping(method = RequestMethod.GET) 33 | public String index(HttpServletRequest req, Principal principal, Model model) { 34 | log.info("HOME: " + req); 35 | commonModelPopulate(req, principal, model); 36 | model.addAttribute("name", "HOME"); 37 | counterService.increment("home"); 38 | return "home"; // name of the template 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /src/main/java/ltistarter/repository/KeyRequestRepository.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.repository; 16 | 17 | import ltistarter.model.KeyRequestEntity; 18 | import org.springframework.data.repository.PagingAndSortingRepository; 19 | import org.springframework.transaction.annotation.Transactional; 20 | 21 | @Transactional 22 | public interface KeyRequestRepository extends PagingAndSortingRepository { 23 | /* Add custom crud methods here 24 | * If you need a custom implementation of the methods then see docs for steps to add it 25 | * http://docs.spring.io/spring-data/data-commons/docs/current/reference/html/repositories.html 26 | * Can also write a custom query like so: 27 | * @Query("SELECT u FROM User u WHERE u.alias IS NOT NULL") 28 | * List findAliased(); 29 | * OR: 30 | * @Query("SELECT u FROM User u WHERE u.alias = ?1") 31 | * List findWithAlias(String alias); 32 | */ 33 | 34 | public KeyRequestEntity findByUser_UserId(long userId); 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/ltistarter/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter; 16 | 17 | import ltistarter.model.ConfigEntity; 18 | import ltistarter.repository.ConfigRepository; 19 | import org.junit.Test; 20 | import org.junit.runner.RunWith; 21 | import org.springframework.beans.factory.annotation.Autowired; 22 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 23 | import org.springframework.transaction.annotation.Transactional; 24 | 25 | import static org.junit.Assert.assertNotNull; 26 | 27 | @RunWith(SpringJUnit4ClassRunner.class) 28 | public class ApplicationTests extends BaseApplicationTest { 29 | 30 | @Autowired 31 | @SuppressWarnings({"SpringJavaAutowiredMembersInspection", "SpringJavaAutowiringInspection"}) 32 | ConfigRepository configRepository; 33 | 34 | @Test 35 | @Transactional 36 | public void testConfig() { 37 | assertNotNull(applicationConfig); 38 | assertNotNull(configRepository); 39 | configRepository.save(new ConfigEntity("test.thing", "Value")); 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | LTI 1 and 2 java starter app 2 | ============================ 3 | 4 | IMS LTI 1 and 2 based starter (sample) application written using Java and Spring Boot 5 | 6 | The goal is to have a Java based web app which can serve as the basis (or starting point) for building a fully compliant LTI 1 or 2 based tool without having to manage the complexities of LTI 2 or come up with a strategy for handling the various types of data storage. 7 | 8 | Parts based on the data structures and code in tsugi (https://github.com/csev/tsugi) which is a Multi-tenant learning tool hosting platform (http://www.tsugi.org) 9 | 10 | Build 11 | ----- 12 | This will produce a starter.war file in the *target* directory which can be placed into any standard servlet container. 13 | 14 | mvn install 15 | 16 | Quick Run 17 | --------- 18 | You can run the app in place to try it out without having to install and deploy a servlet container. 19 | 20 | mvn clean install spring-boot:run 21 | 22 | Then go to the following default URL: 23 | 24 | http://localhost:8080/ 25 | 26 | You can access the H2 console for default in-memory DB (JDBC URL: **jdbc:h2:mem:AZ**, username: **sa**, password: *(blank)*) at: 27 | 28 | http://localhost:8080/console 29 | 30 | Customizing 31 | ----------- 32 | Use the application.properties to control various aspects of the Spring Boot application (like setup your own database connection). 33 | Use the logback.xml to adjust and control logging. 34 | 35 | Debugging 36 | --------- 37 | To enable the debugging port (localhost:8000) when using spring-boot:run, use the maven profile: **-Pdebug**. Then you can attach any remote debugger (eclipse, intellij, etc.) to localhost:8000. NOTE that the application will pause until you connect the debugger to it. 38 | 39 | mvn clean install spring-boot:run -Pdebug 40 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/repository/LtiServiceRepository.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.repository; 16 | 17 | import ltistarter.model.LtiServiceEntity; 18 | import org.springframework.data.repository.PagingAndSortingRepository; 19 | import org.springframework.transaction.annotation.Transactional; 20 | 21 | /** 22 | * NOTE: use of this interface magic makes all subclass-based (CGLIB) proxies fail 23 | */ 24 | @Transactional 25 | public interface LtiServiceRepository extends PagingAndSortingRepository { 26 | /* Add custom crud methods here 27 | * If you need a custom implementation of the methods then see docs for steps to add it 28 | * http://docs.spring.io/spring-data/data-commons/docs/current/reference/html/repositories.html 29 | * Can also write a custom query like so: 30 | * @Query("SELECT u FROM User u WHERE u.alias IS NOT NULL") 31 | * List findAliased(); 32 | * OR: 33 | * @Query("SELECT u FROM User u WHERE u.alias = ?1") 34 | * List findWithAlias(String alias); 35 | */ 36 | 37 | /** 38 | * @param key the unique key 39 | * @return the LtiServiceEntity OR null if there is no entity matching this key 40 | */ 41 | LtiServiceEntity findByServiceKey(String key); 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/repository/LtiResultRepository.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.repository; 16 | 17 | import ltistarter.model.LtiResultEntity; 18 | import org.springframework.data.repository.PagingAndSortingRepository; 19 | import org.springframework.transaction.annotation.Transactional; 20 | 21 | /** 22 | * NOTE: use of this interface magic makes all subclass-based (CGLIB) proxies fail 23 | */ 24 | @Transactional 25 | public interface LtiResultRepository extends PagingAndSortingRepository { 26 | /* Add custom crud methods here 27 | * If you need a custom implementation of the methods then see docs for steps to add it 28 | * http://docs.spring.io/spring-data/data-commons/docs/current/reference/html/repositories.html 29 | * Can also write a custom query like so: 30 | * @Query("SELECT u FROM User u WHERE u.alias IS NOT NULL") 31 | * List findAliased(); 32 | * OR: 33 | * @Query("SELECT u FROM User u WHERE u.alias = ?1") 34 | * List findWithAlias(String alias); 35 | */ 36 | 37 | /** 38 | * @param sourcedid the unique sourcedid key 39 | * @return the LtiResultEntity OR null if there is no entity matching this key 40 | */ 41 | LtiResultEntity findBySourcedid(String sourcedid); 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/repository/SSOKeyRepository.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.repository; 16 | 17 | import ltistarter.model.SSOKeyEntity; 18 | import org.springframework.data.repository.PagingAndSortingRepository; 19 | import org.springframework.transaction.annotation.Transactional; 20 | 21 | @Transactional 22 | public interface SSOKeyRepository extends PagingAndSortingRepository { 23 | /* Add custom crud methods here 24 | * If you need a custom implementation of the methods then see docs for steps to add it 25 | * http://docs.spring.io/spring-data/data-commons/docs/current/reference/html/repositories.html 26 | * Can also write a custom query like so: 27 | * @Query("SELECT u FROM User u WHERE u.alias IS NOT NULL") 28 | * List findAliased(); 29 | * OR: 30 | * @Query("SELECT u FROM User u WHERE u.alias = ?1") 31 | * List findWithAlias(String alias); 32 | */ 33 | 34 | /** 35 | * @param key the unique key 36 | * @return the SSOKeyEntity OR null if there is no entity matching this key 37 | */ 38 | SSOKeyEntity findByKeyKey(String key); 39 | 40 | /** 41 | * @param key the unique key 42 | * @return the number of keys removed (0 or 1) 43 | */ 44 | int deleteByKeyKey(String key); 45 | } 46 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # ---------------------------------------- 2 | # CORE PROPERTIES 3 | # ---------------------------------------- 4 | 5 | # SPRING CONFIG (ConfigFileApplicationListener) 6 | # config file name (default to 'application') 7 | #spring.config.name= 8 | # location of config file 9 | #spring.config.location= 10 | 11 | #spring.application.name=ltistarter 12 | #server.port=8080 13 | 14 | ## thymeleaf base settings 15 | spring.thymeleaf.mode=HTML5 16 | #spring.thymeleaf.encoding=UTF-8 17 | 18 | # INTERNATIONALIZATION (MessageSourceAutoConfiguration) 19 | #spring.messages.basename=messages 20 | #spring.messages.cacheSeconds=-1 21 | #spring.messages.encoding=UTF-8 22 | 23 | ## Logging settings 24 | #logging.path=/var/logs 25 | #logging.file=myapp.log 26 | #logging.level.ltistarter=DEBUG 27 | #logging.level.org.springframework.web=DEBUG 28 | #logging.level.org.hibernate=ERROR 29 | 30 | ## Database connection (MySQL) 31 | #spring.jpa.generate-ddl=true 32 | # ddl-auto: none, validate, update, create-drop 33 | #spring.jpa.show-sql=true 34 | spring.jpa.hibernate.ddl-auto=update 35 | spring.datasource.url=jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE 36 | spring.datasource.driverClassName=org.h2.Driver 37 | spring.datasource.username=sa 38 | spring.datasource.password= 39 | spring.jpa.database-platform=org.hibernate.dialect.H2Dialect 40 | #spring.datasource.url=jdbc:mysql://localhost/test 41 | #spring.datasource.username=dbuser 42 | #spring.datasource.password=dbpass 43 | #spring.datasource.driverClassName=com.mysql.jdbc.Driver 44 | # populate using data.sql 45 | #spring.datasource.initialize=true 46 | # a schema (DDL) script resource reference 47 | #spring.datasource.schema= 48 | #spring.datasource.separator=; 49 | #spring.datasource.continueOnError=false 50 | 51 | ### Settings for development ONLY 52 | http.mappers.json-pretty-print=true 53 | http.mappers.json-sort-keys=true 54 | spring.thymeleaf.cache=false 55 | #logging.level.org.springframework.security=DEBUG 56 | #spring.jpa.show-sql=true 57 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/repository/LtiKeyRepository.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.repository; 16 | 17 | import ltistarter.model.LtiKeyEntity; 18 | import org.springframework.data.repository.PagingAndSortingRepository; 19 | import org.springframework.transaction.annotation.Transactional; 20 | 21 | /** 22 | * NOTE: use of this interface magic makes all subclass-based (CGLIB) proxies fail 23 | */ 24 | @Transactional 25 | public interface LtiKeyRepository extends PagingAndSortingRepository { 26 | /* Add custom crud methods here 27 | * If you need a custom implementation of the methods then see docs for steps to add it 28 | * http://docs.spring.io/spring-data/data-commons/docs/current/reference/html/repositories.html 29 | * Can also write a custom query like so: 30 | * @Query("SELECT u FROM User u WHERE u.alias IS NOT NULL") 31 | * List findAliased(); 32 | * OR: 33 | * @Query("SELECT u FROM User u WHERE u.alias = ?1") 34 | * List findWithAlias(String alias); 35 | */ 36 | 37 | /** 38 | * @param key the unique key 39 | * @return the LtiKeyEntity OR null if there is no entity matching this key 40 | */ 41 | LtiKeyEntity findByKeyKey(String key); 42 | 43 | /** 44 | * @param key the unique key 45 | * @return the number of keys removed (0 or 1) 46 | */ 47 | int deleteByKeyKey(String key); 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/repository/LtiContextRepository.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.repository; 16 | 17 | import ltistarter.model.LtiContextEntity; 18 | import org.springframework.data.repository.PagingAndSortingRepository; 19 | import org.springframework.transaction.annotation.Transactional; 20 | 21 | /** 22 | * NOTE: use of this interface magic makes all subclass-based (CGLIB) proxies fail 23 | */ 24 | @Transactional 25 | public interface LtiContextRepository extends PagingAndSortingRepository { 26 | /* Add custom crud methods here 27 | * If you need a custom implementation of the methods then see docs for steps to add it 28 | * http://docs.spring.io/spring-data/data-commons/docs/current/reference/html/repositories.html 29 | * Can also write a custom query like so: 30 | * @Query("SELECT u FROM User u WHERE u.alias IS NOT NULL") 31 | * List findAliased(); 32 | * OR: 33 | * @Query("SELECT u FROM User u WHERE u.alias = ?1") 34 | * List findWithAlias(String alias); 35 | */ 36 | 37 | /** 38 | * @param key the unique key 39 | * @return the LtiContextEntity OR null if there is no entity matching this key 40 | */ 41 | LtiContextEntity findByContextKey(String key); 42 | 43 | /** 44 | * @param key the unique key 45 | * @return the number of keys removed (0 or 1) 46 | */ 47 | int deleteByContextKey(String key); 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/oauth/ZeroLeggedOAuthProviderProcessingFilter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.oauth; 16 | 17 | import org.springframework.security.oauth.provider.OAuthAuthenticationHandler; 18 | import org.springframework.security.oauth.provider.OAuthProcessingFilterEntryPoint; 19 | import org.springframework.security.oauth.provider.filter.ProtectedResourceProcessingFilter; 20 | import org.springframework.security.oauth.provider.token.OAuthProviderTokenServices; 21 | 22 | /** 23 | * Zero Legged OAuth processing servlet filter 24 | */ 25 | public class ZeroLeggedOAuthProviderProcessingFilter extends ProtectedResourceProcessingFilter { 26 | 27 | public ZeroLeggedOAuthProviderProcessingFilter(MyConsumerDetailsService oAuthConsumerDetailsService, MyOAuthNonceServices oAuthNonceServices, OAuthProcessingFilterEntryPoint oAuthProcessingFilterEntryPoint, OAuthAuthenticationHandler oAuthAuthenticationHandler, OAuthProviderTokenServices oAuthProviderTokenServices, boolean testing) { 28 | super(); 29 | setAuthenticationEntryPoint(oAuthProcessingFilterEntryPoint); 30 | setAuthHandler(oAuthAuthenticationHandler); 31 | setConsumerDetailsService(oAuthConsumerDetailsService); 32 | setNonceServices(oAuthNonceServices); 33 | setTokenServices(oAuthProviderTokenServices); 34 | if (testing) { 35 | setIgnoreMissingCredentials(true); // die if OAuth params are not included 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/repository/ConfigRepository.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.repository; 16 | 17 | import ltistarter.model.ConfigEntity; 18 | import org.springframework.cache.annotation.Cacheable; 19 | import org.springframework.data.repository.PagingAndSortingRepository; 20 | import org.springframework.transaction.annotation.Transactional; 21 | 22 | /** 23 | * NOTE: use of this interface magic makes all subclass-based (CGLIB) proxies fail 24 | */ 25 | @Transactional 26 | public interface ConfigRepository extends PagingAndSortingRepository { 27 | /* Add custom crud methods here 28 | * If you need a custom implementation of the methods then see docs for steps to add it 29 | * http://docs.spring.io/spring-data/data-commons/docs/current/reference/html/repositories.html 30 | * Can also write a custom query like so: 31 | * @Query("SELECT u FROM User u WHERE u.alias IS NOT NULL") 32 | * List findAliased(); 33 | * OR: 34 | * @Query("SELECT u FROM User u WHERE u.alias = ?1") 35 | * List findWithAlias(String alias); 36 | */ 37 | 38 | /** 39 | * @param name the config name (e.g. app.config) 40 | * @return the count of config items with this exact name 41 | */ 42 | public int countByName(String name); 43 | 44 | /** 45 | * @param name the config name (e.g. app.config) 46 | * @return the config item (or null if none found) 47 | */ 48 | @Cacheable(value = "configs", key = "#name") 49 | public ConfigEntity findByName(String name); 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/controllers/LTI2Controller.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.controllers; 16 | 17 | import ltistarter.lti.LTIRequest; 18 | import org.springframework.stereotype.Controller; 19 | import org.springframework.ui.Model; 20 | import org.springframework.web.bind.annotation.RequestMapping; 21 | 22 | import javax.servlet.http.HttpServletRequest; 23 | import java.security.Principal; 24 | 25 | /** 26 | * This LTI controller should be protected by OAuth 1.0a and is here for cases 27 | * where we need lti2 specific processing that can't be done under the lti path 28 | */ 29 | @Controller 30 | @RequestMapping("/lti2") 31 | public class LTI2Controller extends BaseController { 32 | 33 | @RequestMapping({"", "/"}) 34 | public String home(HttpServletRequest req, Principal principal, Model model) { 35 | commonModelPopulate(req, principal, model); 36 | model.addAttribute("name", "lti2"); 37 | req.getSession().setAttribute("login", "oauth"); 38 | LTIRequest ltiRequest = LTIRequest.getInstance(); 39 | if (ltiRequest != null) { 40 | model.addAttribute("lti", true); 41 | model.addAttribute("ltiVersion", ltiRequest.getLtiVersion()); 42 | model.addAttribute("ltiContext", ltiRequest.getLtiContextId()); 43 | model.addAttribute("ltiUser", ltiRequest.getLtiUserDisplayName()); 44 | model.addAttribute("ltiLink", ltiRequest.getLtiLinkId()); 45 | } 46 | //noinspection SpringMVCViewInspection 47 | return "home"; // name of the template 48 | } 49 | 50 | } -------------------------------------------------------------------------------- /src/main/java/ltistarter/oauth/MyOAuthProcessingFilterEntryPointImpl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.oauth; 16 | 17 | import org.slf4j.Logger; 18 | import org.slf4j.LoggerFactory; 19 | import org.springframework.security.core.AuthenticationException; 20 | import org.springframework.security.oauth.provider.OAuthProcessingFilterEntryPoint; 21 | import org.springframework.stereotype.Component; 22 | 23 | import javax.servlet.ServletException; 24 | import javax.servlet.http.HttpServletRequest; 25 | import javax.servlet.http.HttpServletResponse; 26 | import java.io.IOException; 27 | 28 | /** 29 | * Shows how to handle OAuth failures in a special way if desired (just logs it for now) 30 | */ 31 | @Component 32 | public class MyOAuthProcessingFilterEntryPointImpl extends OAuthProcessingFilterEntryPoint { 33 | 34 | final static Logger log = LoggerFactory.getLogger(MyOAuthProcessingFilterEntryPointImpl.class); 35 | 36 | @Override 37 | public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { 38 | log.info("OAuth FILTER Failure (commence), req=" + request + ", ex=" + authException); 39 | // Called when there is an OAuth Auth failure, authException may be InsufficientAuthenticationException 40 | super.commence(request, response, authException); 41 | /* 42 | response.setCharacterEncoding("UTF-8"); 43 | response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 44 | response.setContentType(MediaType.APPLICATION_JSON.getType()); 45 | response.getWriter().println("{\"Unauthorized\":\"" + authException + "\"}"); 46 | */ 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/controllers/BaseController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.controllers; 16 | 17 | import org.slf4j.Logger; 18 | import org.slf4j.LoggerFactory; 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | import org.springframework.boot.actuate.metrics.CounterService; 21 | import org.springframework.ui.Model; 22 | 23 | import javax.servlet.http.HttpServletRequest; 24 | import java.security.Principal; 25 | import java.util.Date; 26 | 27 | /** 28 | * Common controller methods 29 | */ 30 | public class BaseController { 31 | 32 | final static Logger log = LoggerFactory.getLogger(BaseController.class); 33 | 34 | @Autowired 35 | @SuppressWarnings("SpringJavaAutowiringInspection") 36 | CounterService counterService; 37 | 38 | /** 39 | * Just populate some common model stuff for less repeating 40 | * 41 | * @param req the request 42 | * @param principal the current security principal (if there is one) 43 | * @param model the model 44 | */ 45 | void commonModelPopulate(HttpServletRequest req, Principal principal, Model model) { 46 | model.addAttribute("today", new Date()); 47 | // TODO real user and pass 48 | model.addAttribute("basicUser", "admin"); 49 | model.addAttribute("basicPass", "admin"); 50 | // TODO real key and secret? 51 | model.addAttribute("oauthKey", "key"); 52 | model.addAttribute("oauthSecret", "secret"); 53 | // a little extra request handling stuff 54 | model.addAttribute("req", req); 55 | model.addAttribute("reqURI", req.getMethod() + " " + req.getRequestURI()); 56 | // current user 57 | model.addAttribute("username", principal != null ? principal.getName() : "ANONYMOUS"); 58 | } 59 | 60 | } -------------------------------------------------------------------------------- /src/main/java/ltistarter/controllers/FormController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.controllers; 16 | 17 | import org.springframework.stereotype.Controller; 18 | import org.springframework.ui.Model; 19 | import org.springframework.web.bind.annotation.RequestMapping; 20 | import org.springframework.web.bind.annotation.RequestMethod; 21 | 22 | import javax.servlet.http.HttpServletRequest; 23 | import java.security.Principal; 24 | 25 | /** 26 | * This controller should be protected by basic auth authentication (on the /basic path) 27 | * Username and password controlled in application.properties 28 | */ 29 | @Controller 30 | @RequestMapping("/form") 31 | public class FormController extends BaseController { 32 | 33 | @RequestMapping({"", "/"}) 34 | public String home(HttpServletRequest req, Principal principal, Model model) { 35 | commonModelPopulate(req, principal, model); 36 | model.addAttribute("name", "form"); 37 | model.addAttribute("canLogout", true); 38 | req.getSession().setAttribute("login", "form"); 39 | return "home"; // name of the template 40 | } 41 | 42 | @RequestMapping(value = "/login", method = RequestMethod.GET) 43 | public String login(HttpServletRequest req) { 44 | log.info("login: " + req); 45 | return "login"; 46 | } 47 | 48 | // Login form with error 49 | @RequestMapping(value = "/login", params = "error=true") 50 | public String loginError(HttpServletRequest req, Model model) { 51 | log.info("login-error: " + req); 52 | model.addAttribute("loginError", true); 53 | return "login"; 54 | } 55 | 56 | /* 57 | @RequestMapping("/logout") 58 | public void logout(HttpServletRequest req) { 59 | log.info("logout: " + req); 60 | }*/ 61 | 62 | } -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/BaseEntity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.model; 16 | 17 | import org.apache.commons.lang3.StringUtils; 18 | 19 | import javax.persistence.*; 20 | import java.sql.Timestamp; 21 | 22 | /** 23 | * Specialty class which handles the created_at and updated_at fields automatically 24 | */ 25 | @MappedSuperclass 26 | public class BaseEntity { 27 | 28 | @Column(name = "created_at", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP") 29 | Timestamp createdAt; 30 | 31 | @Column(name = "updated_at") 32 | Timestamp updatedAt; 33 | 34 | @Version 35 | @Column(name = "entity_version") 36 | int version; 37 | 38 | @PrePersist 39 | void preCreate() { 40 | this.createdAt = this.updatedAt = new Timestamp(System.currentTimeMillis()); 41 | } 42 | 43 | @PreUpdate 44 | void preUpdate() { 45 | this.updatedAt = new Timestamp(System.currentTimeMillis()); 46 | } 47 | 48 | public Timestamp getCreatedAt() { 49 | return createdAt; 50 | } 51 | 52 | public void setCreatedAt(Timestamp createdAt) { 53 | this.createdAt = createdAt; 54 | } 55 | 56 | public Timestamp getUpdatedAt() { 57 | return updatedAt; 58 | } 59 | 60 | public void setUpdatedAt(Timestamp updatedAt) { 61 | this.updatedAt = updatedAt; 62 | } 63 | 64 | public int getVersion() { 65 | return version; 66 | } 67 | 68 | public void setVersion(int version) { 69 | this.version = version; 70 | } 71 | 72 | public static String makeSHA256(String text) { 73 | String encode = null; 74 | if (StringUtils.isNotBlank(text)) { 75 | encode = org.apache.commons.codec.digest.DigestUtils.sha256Hex(text); 76 | } 77 | return encode; 78 | } 79 | 80 | } -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/ConfigEntity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.model; 16 | 17 | import javax.persistence.*; 18 | 19 | @Entity 20 | @Table(name = "config") 21 | public class ConfigEntity extends BaseEntity { 22 | @Id 23 | @GeneratedValue(strategy = GenerationType.AUTO) 24 | @Column(name = "config_id", nullable = false, insertable = true, updatable = true) 25 | private long id; 26 | @Basic 27 | @Column(name = "config_name", nullable = false, insertable = true, updatable = true, length = 255) 28 | private String name; 29 | @Basic 30 | @Column(name = "config_value", nullable = true, insertable = true, updatable = true, length = 4096) 31 | private String value; 32 | 33 | public ConfigEntity() { 34 | } 35 | 36 | public ConfigEntity(String name, String value) { 37 | assert name != null; 38 | this.name = name; 39 | this.value = value; 40 | } 41 | 42 | public long getId() { 43 | return id; 44 | } 45 | 46 | public void setId(long id) { 47 | this.id = id; 48 | } 49 | 50 | public String getName() { 51 | return name; 52 | } 53 | 54 | public void setName(String name) { 55 | this.name = name; 56 | } 57 | 58 | public String getValue() { 59 | return value; 60 | } 61 | 62 | public void setValue(String value) { 63 | this.value = value; 64 | } 65 | 66 | @Override 67 | public boolean equals(Object o) { 68 | if (this == o) return true; 69 | if (o == null || getClass() != o.getClass()) return false; 70 | 71 | ConfigEntity that = (ConfigEntity) o; 72 | 73 | if (id != that.id) return false; 74 | if (!name.equals(that.name)) return false; 75 | 76 | return true; 77 | } 78 | 79 | @Override 80 | public int hashCode() { 81 | int result = (int) (id ^ (id >>> 32)); 82 | result = 31 * result + name.hashCode(); 83 | return result; 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/oauth/MyConsumerDetailsService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.oauth; 16 | 17 | import org.slf4j.Logger; 18 | import org.slf4j.LoggerFactory; 19 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 20 | import org.springframework.security.oauth.common.OAuthException; 21 | import org.springframework.security.oauth.common.signature.SharedConsumerSecretImpl; 22 | import org.springframework.security.oauth.provider.BaseConsumerDetails; 23 | import org.springframework.security.oauth.provider.ConsumerDetails; 24 | import org.springframework.security.oauth.provider.ConsumerDetailsService; 25 | import org.springframework.stereotype.Component; 26 | 27 | /** 28 | * Sample consumer details service which verifies the key and secret, 29 | * In our case the key is "key" and secret is "secret" 30 | */ 31 | @Component 32 | public class MyConsumerDetailsService implements ConsumerDetailsService { 33 | 34 | final static Logger log = LoggerFactory.getLogger(MyConsumerDetailsService.class); 35 | 36 | @Override 37 | public ConsumerDetails loadConsumerByConsumerKey(String consumerKey) throws OAuthException { 38 | BaseConsumerDetails cd; 39 | // NOTE: really lookup the key and secret, for the sample here we just hardcoded 40 | if ("key".equals(consumerKey)) { 41 | // allow this oauth request 42 | cd = new BaseConsumerDetails(); 43 | cd.setConsumerKey(consumerKey); 44 | cd.setSignatureSecret(new SharedConsumerSecretImpl("secret")); 45 | cd.setConsumerName("Sample"); 46 | cd.setRequiredToObtainAuthenticatedToken(false); // no token required (0-legged) 47 | cd.getAuthorities().add(new SimpleGrantedAuthority("ROLE_OAUTH")); // add the ROLE_OAUTH (can add others as well) 48 | log.info("OAuth check SUCCESS, consumer key: " + consumerKey); 49 | } else { 50 | // deny - failed to match 51 | throw new OAuthException("For this example, key must be 'key'"); 52 | } 53 | return cd; 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/controllers/LTIController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.controllers; 16 | 17 | import ltistarter.lti.LTIRequest; 18 | import org.springframework.stereotype.Controller; 19 | import org.springframework.ui.Model; 20 | import org.springframework.web.bind.annotation.RequestMapping; 21 | 22 | import javax.servlet.http.HttpServletRequest; 23 | import java.security.Principal; 24 | 25 | /** 26 | * This LTI controller should be protected by OAuth 1.0a (on the /oauth path) 27 | * This will handle LTI 1 and 2 (many of the paths ONLY make sense for LTI2 though) 28 | * Sample Key "key" and secret "secret" 29 | */ 30 | @Controller 31 | @RequestMapping("/lti") 32 | public class LTIController extends BaseController { 33 | 34 | @RequestMapping({"", "/"}) 35 | public String home(HttpServletRequest req, Principal principal, Model model) { 36 | commonModelPopulate(req, principal, model); 37 | model.addAttribute("name", "lti"); 38 | req.getSession().setAttribute("login", "oauth"); 39 | LTIRequest ltiRequest = LTIRequest.getInstance(); 40 | if (ltiRequest != null) { 41 | model.addAttribute("lti", true); 42 | model.addAttribute("ltiVersion", ltiRequest.getLtiVersion()); 43 | model.addAttribute("ltiContext", ltiRequest.getLtiContextId()); 44 | model.addAttribute("ltiUser", ltiRequest.getLtiUserDisplayName()); 45 | model.addAttribute("ltiLink", ltiRequest.getLtiLinkId()); 46 | } 47 | //noinspection SpringMVCViewInspection 48 | return "home"; // name of the template 49 | } 50 | 51 | @RequestMapping({"/register"}) 52 | public String register(HttpServletRequest req, Model model) { 53 | LTIRequest ltiRequest = LTIRequest.getInstanceOrDie(); 54 | if (ltiRequest.checkValidToolRegistration()) { // throws exception on failure 55 | model.addAttribute("validToolRegistration", true); 56 | // TODO process it! 57 | } 58 | //noinspection SpringMVCViewInspection 59 | return "register"; // name of the template 60 | } 61 | 62 | } -------------------------------------------------------------------------------- /src/main/java/ltistarter/repository/AllRepositories.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.repository; 16 | 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.stereotype.Component; 19 | 20 | import javax.persistence.EntityManager; 21 | import javax.persistence.PersistenceContext; 22 | 23 | /** 24 | * Special service to give access to all the repositories in one place 25 | *

26 | * This is just here to make it a little easier to get access to the full set of repositories instead of always injecting 27 | * the lot of them (reduces code duplication) 28 | */ 29 | @SuppressWarnings("SpringJavaAutowiringInspection") 30 | @Component 31 | public class AllRepositories { 32 | 33 | @Autowired 34 | public ConfigRepository configs; 35 | 36 | @Autowired 37 | public KeyRequestRepository keyRequests; 38 | 39 | @Autowired 40 | public LtiContextRepository contexts; 41 | 42 | @Autowired 43 | public LtiKeyRepository keys; 44 | 45 | @Autowired 46 | public LtiLinkRepository links; 47 | 48 | @Autowired 49 | public LtiMembershipRepository members; 50 | 51 | @Autowired 52 | public LtiResultRepository results; 53 | 54 | @Autowired 55 | public LtiServiceRepository services; 56 | 57 | @Autowired 58 | public LtiUserRepository users; 59 | 60 | @Autowired 61 | public ProfileRepository profiles; 62 | 63 | @Autowired 64 | public SSOKeyRepository ssoKeys; 65 | 66 | @PersistenceContext 67 | public EntityManager entityManager; 68 | 69 | /** 70 | * @return a version of the entity manager which is transactional for cases where we cannot use the @Transactional annotation 71 | * or we are not operating in a service method 72 | */ 73 | public EntityManager getTransactionalEntityManager() { 74 | /* Need a transactional entity manager and for some reason the normal one is NOT, without this we get: 75 | * java.lang.IllegalStateException: No transactional EntityManager available 76 | * http://forum.spring.io/forum/spring-projects/roo/88329-entitymanager-problem 77 | * http://stackoverflow.com/questions/14522691/java-lang-illegalstateexception-no-transactional-entitymanager-available 78 | */ 79 | return entityManager.getEntityManagerFactory().createEntityManager(); 80 | } 81 | 82 | /** 83 | * Do NOT construct this class manually 84 | */ 85 | protected AllRepositories() { 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/database/DatabasePreload.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.database; 16 | 17 | import ltistarter.config.ApplicationConfig; 18 | import ltistarter.model.LtiKeyEntity; 19 | import ltistarter.model.LtiUserEntity; 20 | import ltistarter.model.ProfileEntity; 21 | import ltistarter.repository.LtiKeyRepository; 22 | import ltistarter.repository.LtiUserRepository; 23 | import ltistarter.repository.ProfileRepository; 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | import org.springframework.beans.factory.annotation.Autowired; 27 | import org.springframework.context.annotation.Profile; 28 | import org.springframework.stereotype.Component; 29 | 30 | import javax.annotation.PostConstruct; 31 | 32 | /** 33 | * Check if the database has initial data in it, 34 | * if it is empty on startup then we populate it with some initial data 35 | */ 36 | @Component 37 | @Profile("!testing") 38 | // only load this when running the application (not for unit tests which have the 'testing' profile active) 39 | public class DatabasePreload { 40 | 41 | final static Logger log = LoggerFactory.getLogger(DatabasePreload.class); 42 | 43 | @Autowired 44 | ApplicationConfig applicationConfig; 45 | 46 | @Autowired 47 | @SuppressWarnings({"SpringJavaAutowiredMembersInspection", "SpringJavaAutowiringInspection"}) 48 | LtiKeyRepository ltiKeyRepository; 49 | @Autowired 50 | @SuppressWarnings({"SpringJavaAutowiredMembersInspection", "SpringJavaAutowiringInspection"}) 51 | LtiUserRepository ltiUserRepository; 52 | @Autowired 53 | @SuppressWarnings({"SpringJavaAutowiredMembersInspection", "SpringJavaAutowiringInspection"}) 54 | ProfileRepository profileRepository; 55 | 56 | @PostConstruct 57 | public void init() { 58 | if (ltiKeyRepository.count() > 0) { 59 | // done, no preloading 60 | log.info("INIT - no preload"); 61 | } else { 62 | // preload the sample data 63 | log.info("INIT - preloaded keys and user"); 64 | // create our sample key 65 | ltiKeyRepository.save(new LtiKeyEntity("key", "secret")); 66 | // create our sample user 67 | LtiUserEntity user = ltiUserRepository.save(new LtiUserEntity("azeckoski", null)); 68 | ProfileEntity profile = profileRepository.save(new ProfileEntity("AaronZeckoski", null, "azeckoski@test.com")); 69 | // now add profile to the user 70 | user.setProfile(profile); 71 | profile.getUsers().add(user); 72 | ltiUserRepository.save(user); 73 | } 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/LmsPluginsEntity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.model; 16 | 17 | import javax.persistence.*; 18 | 19 | @Entity 20 | @Table(name = "lms_plugins") 21 | public class LmsPluginsEntity extends BaseEntity { 22 | @Id 23 | @GeneratedValue(strategy = GenerationType.AUTO) 24 | @Column(name = "plugin_id", nullable = false, insertable = true, updatable = true) 25 | private long pluginId; 26 | @Basic 27 | @Column(name = "plugin_path", nullable = false, insertable = true, updatable = true, length = 255) 28 | private String pluginPath; 29 | @Basic 30 | @Column(name = "plugin_version", nullable = false, insertable = true, updatable = true) 31 | private long pluginVersion; 32 | @Basic 33 | @Column(name = "title", nullable = true, insertable = true, updatable = true, length = 4096) 34 | private String title; 35 | @Basic 36 | @Column(name = "json", nullable = true, insertable = true, updatable = true, length = 65535) 37 | private String json; 38 | 39 | public long getPluginId() { 40 | return pluginId; 41 | } 42 | 43 | public void setPluginId(long pluginId) { 44 | this.pluginId = pluginId; 45 | } 46 | 47 | public String getPluginPath() { 48 | return pluginPath; 49 | } 50 | 51 | public void setPluginPath(String pluginPath) { 52 | this.pluginPath = pluginPath; 53 | } 54 | 55 | public long getPluginVersion() { 56 | return pluginVersion; 57 | } 58 | 59 | public void setPluginVersion(long version) { 60 | this.pluginVersion = version; 61 | } 62 | 63 | public String getTitle() { 64 | return title; 65 | } 66 | 67 | public void setTitle(String title) { 68 | this.title = title; 69 | } 70 | 71 | public String getJson() { 72 | return json; 73 | } 74 | 75 | public void setJson(String json) { 76 | this.json = json; 77 | } 78 | 79 | @Override 80 | public boolean equals(Object o) { 81 | if (this == o) return true; 82 | if (o == null || getClass() != o.getClass()) return false; 83 | 84 | LmsPluginsEntity that = (LmsPluginsEntity) o; 85 | 86 | if (pluginId != that.pluginId) return false; 87 | if (pluginVersion != that.pluginVersion) return false; 88 | if (pluginPath != null ? !pluginPath.equals(that.pluginPath) : that.pluginPath != null) return false; 89 | 90 | return true; 91 | } 92 | 93 | @Override 94 | public int hashCode() { 95 | int result = (int) pluginId; 96 | result = 31 * result + (pluginPath != null ? pluginPath.hashCode() : 0); 97 | result = 31 * result + (int) (pluginVersion ^ (pluginVersion >>> 32)); 98 | return result; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/lti/LTIOAuthProviderProcessingFilter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.lti; 16 | 17 | import ltistarter.oauth.MyOAuthNonceServices; 18 | import org.springframework.security.oauth.provider.OAuthProcessingFilterEntryPoint; 19 | import org.springframework.security.oauth.provider.filter.ProtectedResourceProcessingFilter; 20 | import org.springframework.security.oauth.provider.token.OAuthProviderTokenServices; 21 | 22 | import javax.servlet.FilterChain; 23 | import javax.servlet.ServletException; 24 | import javax.servlet.ServletRequest; 25 | import javax.servlet.ServletResponse; 26 | import javax.servlet.http.HttpServletRequest; 27 | import java.io.IOException; 28 | 29 | /** 30 | * LTI compatible Zero Legged OAuth processing servlet filter 31 | */ 32 | public class LTIOAuthProviderProcessingFilter extends ProtectedResourceProcessingFilter { 33 | 34 | LTIDataService ltiDataService; 35 | 36 | public LTIOAuthProviderProcessingFilter(LTIDataService ltiDataService, LTIConsumerDetailsService oAuthConsumerDetailsService, MyOAuthNonceServices oAuthNonceServices, OAuthProcessingFilterEntryPoint oAuthProcessingFilterEntryPoint, LTIOAuthAuthenticationHandler oAuthAuthenticationHandler, OAuthProviderTokenServices oAuthProviderTokenServices) { 37 | super(); 38 | assert ltiDataService != null; 39 | this.ltiDataService = ltiDataService; 40 | setAuthenticationEntryPoint(oAuthProcessingFilterEntryPoint); 41 | setAuthHandler(oAuthAuthenticationHandler); 42 | setConsumerDetailsService(oAuthConsumerDetailsService); 43 | setNonceServices(oAuthNonceServices); 44 | setTokenServices(oAuthProviderTokenServices); 45 | //setIgnoreMissingCredentials(false); // die if OAuth params are not included 46 | } 47 | 48 | @Override 49 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { 50 | // NOTE: tsugi handles failures by just allowing the request to continue - since we have a dedicated endpoint for launches the LTIRequest object will throw an IllegalStateException is the LTI request is invalid somehow 51 | if (!(servletRequest instanceof HttpServletRequest)) { 52 | throw new IllegalStateException("LTI request MUST be an HttpServletRequest (cannot only be a ServletRequest)"); 53 | } 54 | HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; 55 | // load and initialize the LTI request object (loads and validates the data) 56 | LTIRequest ltiRequest = new LTIRequest(httpServletRequest, ltiDataService, true); // IllegalStateException if invalid 57 | httpServletRequest.setAttribute("LTI", true); // indicate this request is an LTI one 58 | httpServletRequest.setAttribute("lti_valid", ltiRequest.isLoaded() && ltiRequest.isComplete()); // is LTI request totally valid and complete 59 | httpServletRequest.setAttribute(LTIRequest.class.getName(), ltiRequest); // make the LTI data accessible later in the request if needed 60 | super.doFilter(servletRequest, servletResponse, chain); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/oauth/OAuthUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.oauth; 16 | 17 | import org.slf4j.Logger; 18 | import org.slf4j.LoggerFactory; 19 | import org.springframework.http.ResponseEntity; 20 | import org.springframework.security.oauth.common.signature.SharedConsumerSecretImpl; 21 | import org.springframework.security.oauth.consumer.BaseProtectedResourceDetails; 22 | import org.springframework.security.oauth.consumer.client.OAuthRestTemplate; 23 | import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; 24 | import org.springframework.security.oauth2.client.OAuth2RestTemplate; 25 | import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails; 26 | import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest; 27 | import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider; 28 | import org.springframework.security.oauth2.common.AuthenticationScheme; 29 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 30 | 31 | import java.util.Map; 32 | 33 | /** 34 | * OAuth handling utils 35 | */ 36 | public class OAuthUtils { 37 | 38 | final static Logger log = LoggerFactory.getLogger(OAuthUtils.class); 39 | 40 | public static ResponseEntity sendOAuth1Request(String url, String consumerKey, String sharedSecret, Map params, Map headers) { 41 | assert url != null; 42 | assert consumerKey != null; 43 | assert sharedSecret != null; 44 | BaseProtectedResourceDetails prd = new BaseProtectedResourceDetails(); 45 | prd.setId("oauth"); 46 | prd.setConsumerKey(consumerKey); 47 | prd.setSharedSecret(new SharedConsumerSecretImpl(sharedSecret)); 48 | prd.setAdditionalParameters(params); 49 | prd.setAdditionalRequestHeaders(headers); 50 | OAuthRestTemplate restTemplate = new OAuthRestTemplate(prd); 51 | ResponseEntity response = restTemplate.postForEntity(url, params, String.class, (Map) null); 52 | return response; 53 | } 54 | 55 | public static ResponseEntity sendOAuth2Request(String url, String clientId, String clientSecret, String accessTokenURI, Map params) { 56 | assert url != null; 57 | assert clientId != null; 58 | assert clientSecret != null; 59 | AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider(); 60 | BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails(); 61 | resource.setClientAuthenticationScheme(AuthenticationScheme.form); 62 | resource.setClientId(clientId); 63 | resource.setClientSecret(clientSecret); 64 | resource.setAccessTokenUri(accessTokenURI); 65 | resource.setGrantType("access"); 66 | OAuth2AccessToken accessToken = provider.obtainAccessToken(resource, new DefaultAccessTokenRequest()); 67 | OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource, new DefaultOAuth2ClientContext(accessToken)); 68 | ResponseEntity response = restTemplate.postForEntity(url, params, String.class, (Map) null); 69 | return response; 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/lti/LTIConsumerDetailsService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.lti; 16 | 17 | import ltistarter.model.LtiKeyEntity; 18 | import ltistarter.repository.LtiKeyRepository; 19 | import org.apache.commons.lang3.StringUtils; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 24 | import org.springframework.security.oauth.common.OAuthException; 25 | import org.springframework.security.oauth.common.signature.SharedConsumerSecretImpl; 26 | import org.springframework.security.oauth.provider.BaseConsumerDetails; 27 | import org.springframework.security.oauth.provider.ConsumerDetails; 28 | import org.springframework.security.oauth.provider.ConsumerDetailsService; 29 | import org.springframework.stereotype.Component; 30 | 31 | /** 32 | * Sample consumer details service which verifies the key and secret using the LTI key DB. 33 | * Populates the ConsumerDetails.consumerName with the ID of the LtiKeyEntity if a match is found 34 | * and grants the OAUTH and LTI Authority Roles 35 | */ 36 | @Component 37 | public class LTIConsumerDetailsService implements ConsumerDetailsService { 38 | 39 | final static Logger log = LoggerFactory.getLogger(LTIConsumerDetailsService.class); 40 | 41 | @Autowired 42 | @SuppressWarnings("SpringJavaAutowiringInspection") 43 | LtiKeyRepository ltiKeyRepository; 44 | 45 | @Override 46 | public ConsumerDetails loadConsumerByConsumerKey(String consumerKey) throws OAuthException { 47 | consumerKey = StringUtils.trimToNull(consumerKey); 48 | assert StringUtils.isNotEmpty(consumerKey) : "consumerKey must be set and not null"; 49 | //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); 50 | //assert request != null : "request must be available for this to make sense"; 51 | BaseConsumerDetails cd; 52 | LtiKeyEntity ltiKey = ltiKeyRepository.findByKeyKey(consumerKey); 53 | if (ltiKey == null) { 54 | // no matching key found 55 | throw new OAuthException("No matching lti key record was found for " + consumerKey); 56 | } else { 57 | cd = new BaseConsumerDetails(); 58 | cd.setConsumerKey(consumerKey); 59 | // If there is a new_secret it means an LTI2 re-registration is in progress 60 | if (StringUtils.isNotBlank(ltiKey.getNewSecret()) && !StringUtils.equals(ltiKey.getSecret(), ltiKey.getNewSecret())) { 61 | log.info("LTI 2 re-registration in progress - new_secret is not blank"); 62 | // TODO do we need to do anything here? 63 | } 64 | cd.setSignatureSecret(new SharedConsumerSecretImpl(ltiKey.getSecret())); 65 | cd.setConsumerName(String.valueOf(ltiKey.getKeyId())); 66 | cd.setRequiredToObtainAuthenticatedToken(false); // no token required (0-legged) 67 | cd.getAuthorities().add(new SimpleGrantedAuthority("ROLE_OAUTH")); // add the ROLE_OAUTH (can add others as well) 68 | cd.getAuthorities().add(new SimpleGrantedAuthority("ROLE_LTI")); 69 | log.info("LTI check SUCCESS, consumer key: " + consumerKey); 70 | } 71 | return cd; 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/LtiMembershipEntity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.model; 16 | 17 | import javax.persistence.*; 18 | 19 | @Entity 20 | @Table(name = "lti_membership") 21 | public class LtiMembershipEntity extends BaseEntity { 22 | 23 | public final static int ROLE_STUDENT = 0; 24 | public final static int ROLE_INTRUCTOR = 1; 25 | 26 | @Id 27 | @GeneratedValue(strategy = GenerationType.AUTO) 28 | @Column(name = "membership_id", nullable = false, insertable = true, updatable = true) 29 | private long membershipId; 30 | @Basic 31 | @Column(name = "role", nullable = true, insertable = true, updatable = true) 32 | private Integer role; 33 | @Basic 34 | @Column(name = "role_override", nullable = true, insertable = true, updatable = true) 35 | private Integer roleOverride; 36 | 37 | @ManyToOne(fetch = FetchType.LAZY, optional = false) 38 | @JoinColumn(name = "context_id") 39 | private LtiContextEntity context; 40 | @ManyToOne(fetch = FetchType.LAZY, optional = false) 41 | @JoinColumn(name = "user_id") 42 | private LtiUserEntity user; 43 | 44 | protected LtiMembershipEntity() { 45 | } 46 | 47 | public LtiMembershipEntity(LtiContextEntity context, LtiUserEntity user, Integer role) { 48 | assert user != null; 49 | assert context != null; 50 | this.user = user; 51 | this.context = context; 52 | this.role = role; 53 | } 54 | 55 | public long getMembershipId() { 56 | return membershipId; 57 | } 58 | 59 | public void setMembershipId(long membershipId) { 60 | this.membershipId = membershipId; 61 | } 62 | 63 | public Integer getRole() { 64 | return role; 65 | } 66 | 67 | public void setRole(Integer role) { 68 | this.role = role; 69 | } 70 | 71 | public Integer getRoleOverride() { 72 | return roleOverride; 73 | } 74 | 75 | public void setRoleOverride(Integer roleOverride) { 76 | this.roleOverride = roleOverride; 77 | } 78 | 79 | public LtiContextEntity getContext() { 80 | return context; 81 | } 82 | 83 | public void setContext(LtiContextEntity context) { 84 | this.context = context; 85 | } 86 | 87 | public LtiUserEntity getUser() { 88 | return user; 89 | } 90 | 91 | public void setUser(LtiUserEntity user) { 92 | this.user = user; 93 | } 94 | 95 | @Override 96 | public boolean equals(Object o) { 97 | if (this == o) return true; 98 | if (o == null || getClass() != o.getClass()) return false; 99 | 100 | LtiMembershipEntity that = (LtiMembershipEntity) o; 101 | 102 | if (context.getContextId() != that.context.getContextId()) return false; 103 | if (membershipId != that.membershipId) return false; 104 | if (user.getUserId() != that.user.getUserId()) return false; 105 | if (role != null ? !role.equals(that.role) : that.role != null) return false; 106 | 107 | return true; 108 | } 109 | 110 | @Override 111 | public int hashCode() { 112 | int result = (int) membershipId; 113 | result = 31 * result + (int) context.getContextId(); 114 | result = 31 * result + (int) user.getUserId(); 115 | result = 31 * result + (role != null ? role.hashCode() : 0); 116 | return result; 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/KeyRequestEntity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.model; 16 | 17 | import javax.persistence.*; 18 | 19 | @Entity 20 | @Table(name = "key_request") 21 | public class KeyRequestEntity extends BaseEntity { 22 | @Id 23 | @GeneratedValue(strategy = GenerationType.AUTO) 24 | @Column(name = "request_id", nullable = false, insertable = true, updatable = true) 25 | private long requestId; 26 | @Basic 27 | @Column(name = "title", nullable = false, insertable = true, updatable = true, length = 4096) 28 | private String title; 29 | @Basic 30 | @Column(name = "notes", nullable = true, insertable = true, updatable = true, length = 65535) 31 | private String notes; 32 | @Basic 33 | @Column(name = "admin", nullable = true, insertable = true, updatable = true, length = 65535) 34 | private String admin; 35 | @Basic 36 | @Column(name = "state", nullable = true, insertable = true, updatable = true) 37 | private Short state; 38 | @Basic 39 | @Column(name = "lti", nullable = true, insertable = true, updatable = true) 40 | private Byte lti; 41 | @Basic 42 | @Column(name = "json", nullable = true, insertable = true, updatable = true, length = 65535) 43 | private String json; 44 | 45 | @ManyToOne 46 | @JoinColumn(name = "user_id", referencedColumnName = "user_id", nullable = false, insertable = false, updatable = false) 47 | private LtiUserEntity user; 48 | 49 | public long getRequestId() { 50 | return requestId; 51 | } 52 | 53 | public void setRequestId(long requestId) { 54 | this.requestId = requestId; 55 | } 56 | 57 | public String getTitle() { 58 | return title; 59 | } 60 | 61 | public void setTitle(String title) { 62 | this.title = title; 63 | } 64 | 65 | public String getNotes() { 66 | return notes; 67 | } 68 | 69 | public void setNotes(String notes) { 70 | this.notes = notes; 71 | } 72 | 73 | public String getAdmin() { 74 | return admin; 75 | } 76 | 77 | public void setAdmin(String admin) { 78 | this.admin = admin; 79 | } 80 | 81 | public Short getState() { 82 | return state; 83 | } 84 | 85 | public void setState(Short state) { 86 | this.state = state; 87 | } 88 | 89 | public Byte getLti() { 90 | return lti; 91 | } 92 | 93 | public void setLti(Byte lti) { 94 | this.lti = lti; 95 | } 96 | 97 | public String getJson() { 98 | return json; 99 | } 100 | 101 | public void setJson(String json) { 102 | this.json = json; 103 | } 104 | 105 | public LtiUserEntity getUser() { 106 | return user; 107 | } 108 | 109 | public void setUser(LtiUserEntity user) { 110 | this.user = user; 111 | } 112 | 113 | @Override 114 | public boolean equals(Object o) { 115 | if (this == o) return true; 116 | if (o == null || getClass() != o.getClass()) return false; 117 | 118 | KeyRequestEntity that = (KeyRequestEntity) o; 119 | 120 | if (requestId != that.requestId) return false; 121 | if (title != null ? !title.equals(that.title) : that.title != null) return false; 122 | 123 | return true; 124 | } 125 | 126 | @Override 127 | public int hashCode() { 128 | int result = (int) requestId; 129 | result = 31 * result + (title != null ? title.hashCode() : 0); 130 | return result; 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /src/main/resources/templates/home.html: -------------------------------------------------------------------------------- 1 | 17 | 18 | 19 | 21 | 22 | LTI Starter 23 | 24 | 25 | 26 |

Hello Spring Boot User ! ()

27 | 28 |
Request URI:
29 |

30 | 31 |

OPEN: Home(/) | /open
32 | 33 |
34 |
35 | 36 |
37 |
User: AZ
38 |
Roles: [ROLE_USER, ROLE_ADMIN]
39 |
Login:
40 |
41 |
42 | This content is only shown to LTI users (ROLE_LTI). 43 |
Context:
44 |
Version:
45 |
User:
46 |
Link:
47 |
48 |
49 | This content is only shown to administrators (ROLE_ADMIN). 50 |
51 |
52 | This content is only shown to users (ROLE_USER). 53 |
54 |
55 | You have been logged out. 56 |
57 | 58 | 71 |
72 |

Form Login endpoint

73 | 74 |
Username: , Password:
75 | 76 | 77 |

Basic Auth endpoint

78 | 79 |
Username: , Password:
80 | 81 | 82 |

Oauth 1.0 endpoint

83 | 84 |
Consumer Key: , Secret:
85 | 86 | 87 |

LTI 1.0 provider endpoint

88 | 89 |
Consumer Key: , Secret:
90 | 91 |
92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/SSOKeyEntity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.model; 16 | 17 | import org.apache.commons.lang3.StringUtils; 18 | 19 | import javax.persistence.*; 20 | 21 | @Entity 22 | @Table(name = "sso_key") 23 | public class SSOKeyEntity extends BaseEntity { 24 | public static String SOURCE_FACEBOOK = "Facebook"; 25 | public static String SOURCE_GOOGLE = "Google"; 26 | public static String SOURCE_LINKEDIN = "LinkedIn"; 27 | 28 | @Id 29 | @GeneratedValue(strategy = GenerationType.AUTO) 30 | @Column(name = "key_id", nullable = false, insertable = true, updatable = true) 31 | private long keyId; 32 | @Basic 33 | @Column(name = "key_sha256", unique = true, nullable = false, insertable = true, updatable = true, length = 64) 34 | private String keySha256; 35 | @Basic 36 | @Column(name = "key_key", unique = true, nullable = false, insertable = true, updatable = true, length = 4096) 37 | private String keyKey; 38 | @Basic 39 | @Column(name = "source", nullable = false, insertable = true, updatable = true, length = 255) 40 | private String source; 41 | @Basic 42 | @Column(name = "json", nullable = true, insertable = true, updatable = true, length = 65535) 43 | private String json; 44 | 45 | @ManyToOne(fetch = FetchType.LAZY, optional = true) 46 | private ProfileEntity profile; 47 | 48 | protected SSOKeyEntity() { 49 | } 50 | 51 | /** 52 | * @param key the SSO key (from google, facebook, linkedin, etc.) 53 | * @param source the source of this key (google, facebook, linkedin, etc.) 54 | */ 55 | public SSOKeyEntity(String key, String source) { 56 | assert StringUtils.isNotBlank(key); 57 | this.keyKey = key; 58 | this.keySha256 = makeSHA256(key); 59 | this.source = source; 60 | } 61 | 62 | public long getKeyId() { 63 | return keyId; 64 | } 65 | 66 | public void setKeyId(long keyId) { 67 | this.keyId = keyId; 68 | } 69 | 70 | public String getKeySha256() { 71 | return keySha256; 72 | } 73 | 74 | public void setKeySha256(String keySha256) { 75 | this.keySha256 = keySha256; 76 | } 77 | 78 | public String getKeyKey() { 79 | return keyKey; 80 | } 81 | 82 | public void setKeyKey(String keyKey) { 83 | this.keyKey = keyKey; 84 | } 85 | 86 | public String getJson() { 87 | return json; 88 | } 89 | 90 | public void setJson(String json) { 91 | this.json = json; 92 | } 93 | 94 | public String getSource() { 95 | return source; 96 | } 97 | 98 | public void setSource(String source) { 99 | this.source = source; 100 | } 101 | 102 | public ProfileEntity getProfile() { 103 | return profile; 104 | } 105 | 106 | public void setProfile(ProfileEntity profile) { 107 | this.profile = profile; 108 | } 109 | 110 | @Override 111 | public boolean equals(Object o) { 112 | if (this == o) return true; 113 | if (o == null || getClass() != o.getClass()) return false; 114 | 115 | SSOKeyEntity that = (SSOKeyEntity) o; 116 | 117 | if (keyId != that.keyId) return false; 118 | if (keyKey != null ? !keyKey.equals(that.keyKey) : that.keyKey != null) return false; 119 | if (keySha256 != null ? !keySha256.equals(that.keySha256) : that.keySha256 != null) return false; 120 | 121 | return true; 122 | } 123 | 124 | @Override 125 | public int hashCode() { 126 | int result = (int) keyId; 127 | result = 31 * result + (keySha256 != null ? keySha256.hashCode() : 0); 128 | result = 31 * result + (keyKey != null ? keyKey.hashCode() : 0); 129 | return result; 130 | } 131 | 132 | } 133 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/lti/LTIOAuthAuthenticationHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.lti; 16 | 17 | import ltistarter.oauth.MyOAuthAuthenticationHandler; 18 | import org.apache.commons.lang3.StringUtils; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 22 | import org.springframework.security.core.Authentication; 23 | import org.springframework.security.core.GrantedAuthority; 24 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 25 | import org.springframework.security.oauth.provider.ConsumerAuthentication; 26 | import org.springframework.security.oauth.provider.OAuthAuthenticationHandler; 27 | import org.springframework.security.oauth.provider.token.OAuthAccessProviderToken; 28 | import org.springframework.stereotype.Component; 29 | 30 | import javax.annotation.PostConstruct; 31 | import javax.servlet.http.HttpServletRequest; 32 | import java.security.Principal; 33 | import java.util.Collection; 34 | import java.util.HashSet; 35 | 36 | @Component 37 | public class LTIOAuthAuthenticationHandler implements OAuthAuthenticationHandler { 38 | 39 | final static Logger log = LoggerFactory.getLogger(LTIOAuthAuthenticationHandler.class); 40 | 41 | public static SimpleGrantedAuthority userGA = new SimpleGrantedAuthority("ROLE_USER"); 42 | public static SimpleGrantedAuthority learnerGA = new SimpleGrantedAuthority("ROLE_LEARNER"); 43 | public static SimpleGrantedAuthority instructorGA = new SimpleGrantedAuthority("ROLE_INSTRUCTOR"); 44 | public static SimpleGrantedAuthority adminGA = new SimpleGrantedAuthority("ROLE_ADMIN"); 45 | 46 | @PostConstruct 47 | public void init() { 48 | log.info("INIT"); 49 | } 50 | 51 | @Override 52 | public Authentication createAuthentication(HttpServletRequest request, ConsumerAuthentication authentication, OAuthAccessProviderToken authToken) { 53 | Collection authorities = new HashSet<>(authentication.getAuthorities()); 54 | LTIRequest ltiRequest = (LTIRequest) request.getAttribute(LTIRequest.class.getName()); 55 | if (ltiRequest == null) { 56 | throw new IllegalStateException("Cannot create authentication for LTI because the LTIRequest is null"); 57 | } 58 | 59 | // attempt to create a user Authority 60 | String username = ltiRequest.getLtiUserId(); 61 | if (StringUtils.isBlank(username)) { 62 | username = authentication.getName(); 63 | } 64 | 65 | // set appropriate permissions for this user based on LTI data 66 | if (ltiRequest.getUser() != null) { 67 | authorities.add(userGA); 68 | } 69 | if (ltiRequest.isRoleAdministrator()) { 70 | authorities.add(adminGA); 71 | } 72 | if (ltiRequest.isRoleInstructor()) { 73 | authorities.add(instructorGA); 74 | } 75 | if (ltiRequest.isRoleLearner()) { 76 | authorities.add(learnerGA); 77 | } 78 | 79 | // TODO store lti context and user id in the principal 80 | Principal principal = new MyOAuthAuthenticationHandler.NamedOAuthPrincipal(username, authorities, 81 | authentication.getConsumerCredentials().getConsumerKey(), 82 | authentication.getConsumerCredentials().getSignature(), 83 | authentication.getConsumerCredentials().getSignatureMethod(), 84 | authentication.getConsumerCredentials().getSignatureBaseString(), 85 | authentication.getConsumerCredentials().getToken() 86 | ); 87 | Authentication auth = new UsernamePasswordAuthenticationToken(principal, null, authorities); 88 | log.info("createAuthentication generated LTI auth principal (" + principal + "): req=" + request); 89 | return auth; 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /src/test/java/ltistarter/BaseApplicationTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter; 16 | 17 | import ltistarter.config.ApplicationConfig; 18 | import ltistarter.oauth.MyOAuthAuthenticationHandler; 19 | import org.apache.commons.lang3.StringUtils; 20 | import org.junit.Test; 21 | import org.springframework.beans.factory.annotation.Autowired; 22 | import org.springframework.boot.test.SpringApplicationConfiguration; 23 | import org.springframework.mock.web.MockHttpSession; 24 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 25 | import org.springframework.security.core.Authentication; 26 | import org.springframework.security.core.GrantedAuthority; 27 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 28 | import org.springframework.security.core.context.SecurityContextHolder; 29 | import org.springframework.security.web.context.HttpSessionSecurityContextRepository; 30 | import org.springframework.test.context.ActiveProfiles; 31 | import org.springframework.test.context.web.WebAppConfiguration; 32 | import org.springframework.web.context.ConfigurableWebApplicationContext; 33 | 34 | import javax.annotation.PostConstruct; 35 | import java.security.Principal; 36 | import java.util.Collection; 37 | import java.util.HashSet; 38 | 39 | import static org.junit.Assert.assertNotNull; 40 | import static org.junit.Assert.assertTrue; 41 | 42 | @SpringApplicationConfiguration(classes = Application.class) 43 | @WebAppConfiguration 44 | @ActiveProfiles("testing") // make the active profile "testing" 45 | public abstract class BaseApplicationTest { 46 | 47 | @Autowired 48 | @SuppressWarnings("SpringJavaAutowiredMembersInspection") 49 | public ApplicationConfig applicationConfig; 50 | 51 | @Autowired 52 | @SuppressWarnings("SpringJavaAutowiredMembersInspection") 53 | public ConfigurableWebApplicationContext context; 54 | 55 | @PostConstruct 56 | public void init() { 57 | applicationConfig.getEnvironment().setActiveProfiles("testing"); 58 | } 59 | 60 | @Test 61 | public void checkSpring() { 62 | assertNotNull(context); 63 | assertNotNull(applicationConfig); 64 | assertTrue(applicationConfig.getEnvironment().acceptsProfiles("testing")); 65 | } 66 | 67 | /** 68 | * Makes a new session which contains authentication roles, 69 | * this allows us to test requests with varying types of security 70 | * 71 | * @param username the username to set for the session 72 | * @param roles all the roles to grant for this session 73 | * @return the session object to pass to mockMvc (e.g. mockMvc.perform(get("/").session(session)) 74 | */ 75 | public MockHttpSession makeAuthSession(String username, String... roles) { 76 | if (StringUtils.isEmpty(username)) { 77 | username = "azeckoski"; 78 | } 79 | MockHttpSession session = new MockHttpSession(); 80 | session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); 81 | Collection authorities = new HashSet<>(); 82 | if (roles != null && roles.length > 0) { 83 | for (String role : roles) { 84 | authorities.add(new SimpleGrantedAuthority(role)); 85 | } 86 | } 87 | //Authentication authToken = new UsernamePasswordAuthenticationToken("azeckoski", "password", authorities); // causes a NPE when it tries to access the Principal 88 | Principal principal = new MyOAuthAuthenticationHandler.NamedOAuthPrincipal(username, authorities, 89 | "key", "signature", "HMAC-SHA-1", "signaturebase", "token"); 90 | Authentication authToken = new UsernamePasswordAuthenticationToken(principal, null, authorities); 91 | SecurityContextHolder.getContext().setAuthentication(authToken); 92 | return session; 93 | } 94 | 95 | } -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/LtiServiceEntity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.model; 16 | 17 | import org.apache.commons.lang3.StringUtils; 18 | 19 | import javax.persistence.*; 20 | import java.util.Set; 21 | 22 | @Entity 23 | @Table(name = "lti_service") 24 | public class LtiServiceEntity extends BaseEntity { 25 | @Id 26 | @GeneratedValue(strategy = GenerationType.AUTO) 27 | @Column(name = "service_id", nullable = false, insertable = true, updatable = true) 28 | private long serviceId; 29 | @Basic 30 | @Column(name = "service_sha256", nullable = false, insertable = true, updatable = true, length = 64) 31 | private String serviceSha256; 32 | @Basic 33 | @Column(name = "service_key", nullable = false, insertable = true, updatable = true, length = 4096) 34 | private String serviceKey; 35 | @Basic 36 | @Column(name = "format", nullable = true, insertable = true, updatable = true, length = 1024) 37 | private String format; 38 | @Basic 39 | @Column(name = "json", nullable = true, insertable = true, updatable = true, length = 65535) 40 | private String json; 41 | 42 | @ManyToOne(fetch = FetchType.LAZY, optional = false) 43 | @JoinColumn(name = "key_id") 44 | private LtiKeyEntity ltiKey; 45 | @OneToMany(mappedBy = "service", fetch = FetchType.LAZY) 46 | private Set results; 47 | 48 | protected LtiServiceEntity() { 49 | } 50 | 51 | /** 52 | * @param serviceKey the unique external key 53 | * @param key the key which this service is part of 54 | * @param format [OPTIONAL] format or null if there is none 55 | */ 56 | public LtiServiceEntity(String serviceKey, LtiKeyEntity key, String format) { 57 | assert StringUtils.isNotBlank(serviceKey); 58 | assert key != null; 59 | this.serviceKey = serviceKey; 60 | this.serviceSha256 = makeSHA256(serviceKey); 61 | this.ltiKey = key; 62 | this.format = format; 63 | } 64 | 65 | public long getServiceId() { 66 | return serviceId; 67 | } 68 | 69 | public void setServiceId(long serviceId) { 70 | this.serviceId = serviceId; 71 | } 72 | 73 | public String getServiceSha256() { 74 | return serviceSha256; 75 | } 76 | 77 | public void setServiceSha256(String serviceSha256) { 78 | this.serviceSha256 = serviceSha256; 79 | } 80 | 81 | public String getServiceKey() { 82 | return serviceKey; 83 | } 84 | 85 | public void setServiceKey(String serviceKey) { 86 | this.serviceKey = serviceKey; 87 | } 88 | 89 | public String getFormat() { 90 | return format; 91 | } 92 | 93 | public void setFormat(String format) { 94 | this.format = format; 95 | } 96 | 97 | public String getJson() { 98 | return json; 99 | } 100 | 101 | public void setJson(String json) { 102 | this.json = json; 103 | } 104 | 105 | public Set getResults() { 106 | return results; 107 | } 108 | 109 | public void setResults(Set results) { 110 | this.results = results; 111 | } 112 | 113 | public LtiKeyEntity getLtiKey() { 114 | return ltiKey; 115 | } 116 | 117 | public void setLtiKey(LtiKeyEntity ltiKey) { 118 | this.ltiKey = ltiKey; 119 | } 120 | 121 | @Override 122 | public boolean equals(Object o) { 123 | if (this == o) return true; 124 | if (o == null || getClass() != o.getClass()) return false; 125 | 126 | LtiServiceEntity that = (LtiServiceEntity) o; 127 | 128 | if (serviceId != that.serviceId) return false; 129 | if (serviceKey != null ? !serviceKey.equals(that.serviceKey) : that.serviceKey != null) return false; 130 | if (serviceSha256 != null ? !serviceSha256.equals(that.serviceSha256) : that.serviceSha256 != null) 131 | return false; 132 | 133 | return true; 134 | } 135 | 136 | @Override 137 | public int hashCode() { 138 | int result = (int) serviceId; 139 | result = 31 * result + (serviceSha256 != null ? serviceSha256.hashCode() : 0); 140 | result = 31 * result + (serviceKey != null ? serviceKey.hashCode() : 0); 141 | return result; 142 | } 143 | 144 | } 145 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/oauth/MyOAuthAuthenticationHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.oauth; 16 | 17 | import org.apache.commons.lang3.StringUtils; 18 | import org.slf4j.Logger; 19 | import org.slf4j.LoggerFactory; 20 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 21 | import org.springframework.security.core.Authentication; 22 | import org.springframework.security.core.GrantedAuthority; 23 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 24 | import org.springframework.security.oauth.provider.ConsumerAuthentication; 25 | import org.springframework.security.oauth.provider.ConsumerCredentials; 26 | import org.springframework.security.oauth.provider.OAuthAuthenticationHandler; 27 | import org.springframework.security.oauth.provider.token.OAuthAccessProviderToken; 28 | import org.springframework.stereotype.Component; 29 | 30 | import javax.annotation.PostConstruct; 31 | import javax.servlet.http.HttpServletRequest; 32 | import java.security.Principal; 33 | import java.util.Collection; 34 | import java.util.HashSet; 35 | 36 | @Component 37 | public class MyOAuthAuthenticationHandler implements OAuthAuthenticationHandler { 38 | 39 | final static Logger log = LoggerFactory.getLogger(MyOAuthAuthenticationHandler.class); 40 | 41 | public static SimpleGrantedAuthority userGA = new SimpleGrantedAuthority("ROLE_USER"); 42 | public static SimpleGrantedAuthority adminGA = new SimpleGrantedAuthority("ROLE_ADMIN"); 43 | 44 | @PostConstruct 45 | public void init() { 46 | log.info("INIT"); 47 | } 48 | 49 | @Override 50 | public Authentication createAuthentication(HttpServletRequest request, ConsumerAuthentication authentication, OAuthAccessProviderToken authToken) { 51 | Collection authorities = new HashSet<>(authentication.getAuthorities()); 52 | // attempt to create a user Authority 53 | String username = request.getParameter("username"); 54 | if (StringUtils.isBlank(username)) { 55 | username = authentication.getName(); 56 | } 57 | 58 | // NOTE: you should replace this block with your real rules for determining OAUTH ADMIN roles 59 | if (username.equals("admin")) { 60 | authorities.add(userGA); 61 | authorities.add(adminGA); 62 | } else { 63 | authorities.add(userGA); 64 | } 65 | 66 | Principal principal = new NamedOAuthPrincipal(username, authorities, 67 | authentication.getConsumerCredentials().getConsumerKey(), 68 | authentication.getConsumerCredentials().getSignature(), 69 | authentication.getConsumerCredentials().getSignatureMethod(), 70 | authentication.getConsumerCredentials().getSignatureBaseString(), 71 | authentication.getConsumerCredentials().getToken() 72 | ); 73 | Authentication auth = new UsernamePasswordAuthenticationToken(principal, null, authorities); 74 | log.info("createAuthentication generated auth principal (" + principal + "): req=" + request); 75 | return auth; 76 | } 77 | 78 | public static class NamedOAuthPrincipal extends ConsumerCredentials implements Principal { 79 | public String name; 80 | public Collection authorities; 81 | 82 | public NamedOAuthPrincipal(String name, Collection authorities, String consumerKey, String signature, String signatureMethod, String signatureBaseString, String token) { 83 | super(consumerKey, signature, signatureMethod, signatureBaseString, token); 84 | this.name = name; 85 | this.authorities = authorities; 86 | } 87 | 88 | @Override 89 | public String getName() { 90 | return name; 91 | } 92 | 93 | public Collection getAuthorities() { 94 | return authorities; 95 | } 96 | 97 | @Override 98 | public String toString() { 99 | return "NamedOAuthPrincipal{" + 100 | "name='" + name + '\'' + 101 | ", key='" + getConsumerKey() + '\'' + 102 | ", base='" + getSignatureBaseString() + '\'' + 103 | "}"; 104 | } 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/LtiLinkEntity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.model; 16 | 17 | import org.apache.commons.lang3.StringUtils; 18 | 19 | import javax.persistence.*; 20 | import java.util.Set; 21 | 22 | @Entity 23 | @Table(name = "lti_link") 24 | public class LtiLinkEntity extends BaseEntity { 25 | @Id 26 | @GeneratedValue(strategy = GenerationType.AUTO) 27 | @Column(name = "link_id", nullable = false, insertable = true, updatable = true) 28 | private long linkId; 29 | @Basic 30 | @Column(name = "link_sha256", nullable = false, insertable = true, updatable = true, length = 64) 31 | private String linkSha256; 32 | @Basic 33 | @Column(name = "link_key", nullable = false, insertable = true, updatable = true, length = 4096) 34 | private String linkKey; 35 | @Basic 36 | @Column(name = "title", nullable = true, insertable = true, updatable = true, length = 4096) 37 | private String title; 38 | @Basic 39 | @Column(name = "json", nullable = true, insertable = true, updatable = true, length = 65535) 40 | private String json; 41 | @Basic 42 | @Column(nullable = true, length = 65535) 43 | private String settings; 44 | 45 | @ManyToOne(fetch = FetchType.LAZY, optional = false) 46 | @JoinColumn(name = "context_id") 47 | private LtiContextEntity context; 48 | @OneToMany(mappedBy = "link", fetch = FetchType.LAZY) 49 | private Set results; 50 | 51 | protected LtiLinkEntity() { 52 | } 53 | 54 | /** 55 | * @param linkKey the external id for this link 56 | * @param context the LTI context 57 | * @param title OPTIONAL title of this link (null for none) 58 | */ 59 | public LtiLinkEntity(String linkKey, LtiContextEntity context, String title) { 60 | assert StringUtils.isNotBlank(linkKey); 61 | assert context != null; 62 | this.linkKey = linkKey; 63 | this.linkSha256 = makeSHA256(linkKey); 64 | this.context = context; 65 | this.title = title; 66 | } 67 | 68 | public long getLinkId() { 69 | return linkId; 70 | } 71 | 72 | public void setLinkId(long linkId) { 73 | this.linkId = linkId; 74 | } 75 | 76 | public String getLinkSha256() { 77 | return linkSha256; 78 | } 79 | 80 | public void setLinkSha256(String linkSha256) { 81 | this.linkSha256 = linkSha256; 82 | } 83 | 84 | public String getLinkKey() { 85 | return linkKey; 86 | } 87 | 88 | public void setLinkKey(String linkKey) { 89 | this.linkKey = linkKey; 90 | } 91 | 92 | public String getTitle() { 93 | return title; 94 | } 95 | 96 | public void setTitle(String title) { 97 | this.title = title; 98 | } 99 | 100 | public String getJson() { 101 | return json; 102 | } 103 | 104 | public void setJson(String json) { 105 | this.json = json; 106 | } 107 | 108 | public String getSettings() { 109 | return settings; 110 | } 111 | 112 | public void setSettings(String settings) { 113 | this.settings = settings; 114 | } 115 | 116 | public LtiContextEntity getContext() { 117 | return context; 118 | } 119 | 120 | public void setContext(LtiContextEntity context) { 121 | this.context = context; 122 | } 123 | 124 | public Set getResults() { 125 | return results; 126 | } 127 | 128 | public void setResults(Set results) { 129 | this.results = results; 130 | } 131 | 132 | @Override 133 | public boolean equals(Object o) { 134 | if (this == o) return true; 135 | if (o == null || getClass() != o.getClass()) return false; 136 | 137 | LtiLinkEntity that = (LtiLinkEntity) o; 138 | 139 | if (linkId != that.linkId) return false; 140 | if (linkKey != null ? !linkKey.equals(that.linkKey) : that.linkKey != null) return false; 141 | if (linkSha256 != null ? !linkSha256.equals(that.linkSha256) : that.linkSha256 != null) return false; 142 | 143 | return true; 144 | } 145 | 146 | @Override 147 | public int hashCode() { 148 | int result = (int) linkId; 149 | result = 31 * result + (linkSha256 != null ? linkSha256.hashCode() : 0); 150 | result = 31 * result + (linkKey != null ? linkKey.hashCode() : 0); 151 | return result; 152 | } 153 | 154 | } 155 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/LtiContextEntity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.model; 16 | 17 | import org.apache.commons.lang3.StringUtils; 18 | 19 | import javax.persistence.*; 20 | import java.util.Set; 21 | 22 | @Entity 23 | @Table(name = "lti_context") 24 | public class LtiContextEntity extends BaseEntity { 25 | @Id 26 | @GeneratedValue(strategy = GenerationType.AUTO) 27 | @Column(name = "context_id", nullable = false, insertable = true, updatable = true) 28 | private long contextId; 29 | @Basic 30 | @Column(name = "context_sha256", nullable = false, insertable = true, updatable = true, length = 64) 31 | private String contextSha256; 32 | @Basic 33 | @Column(name = "context_key", nullable = false, insertable = true, updatable = true, length = 4096) 34 | private String contextKey; 35 | @Basic 36 | @Column(name = "title", nullable = true, insertable = true, updatable = true, length = 4096) 37 | private String title; 38 | @Basic 39 | @Column(name = "json", nullable = true, insertable = true, updatable = true, length = 65535) 40 | private String json; 41 | @Basic 42 | @Column(nullable = true, length = 65535) 43 | private String settings; 44 | 45 | @ManyToOne(fetch = FetchType.LAZY, optional = false) 46 | @JoinColumn(name = "key_id", referencedColumnName = "key_id", nullable = false) 47 | private LtiKeyEntity ltiKey; 48 | 49 | @OneToMany(mappedBy = "context") 50 | private Set links; 51 | @OneToMany(mappedBy = "context") 52 | private Set memberships; 53 | 54 | public LtiContextEntity() { 55 | } 56 | 57 | public LtiContextEntity(String contextKey, LtiKeyEntity ltiKey, String title, String json) { 58 | assert StringUtils.isNotBlank(contextKey); 59 | assert ltiKey != null; 60 | this.contextKey = contextKey; 61 | this.contextSha256 = makeSHA256(contextKey); 62 | this.ltiKey = ltiKey; 63 | this.title = title; 64 | this.json = json; 65 | } 66 | 67 | public long getContextId() { 68 | return contextId; 69 | } 70 | 71 | public void setContextId(long contextId) { 72 | this.contextId = contextId; 73 | } 74 | 75 | public String getContextSha256() { 76 | return contextSha256; 77 | } 78 | 79 | public void setContextSha256(String contextSha256) { 80 | this.contextSha256 = contextSha256; 81 | } 82 | 83 | public String getContextKey() { 84 | return contextKey; 85 | } 86 | 87 | public void setContextKey(String contextKey) { 88 | this.contextKey = contextKey; 89 | } 90 | 91 | public String getTitle() { 92 | return title; 93 | } 94 | 95 | public void setTitle(String title) { 96 | this.title = title; 97 | } 98 | 99 | public String getJson() { 100 | return json; 101 | } 102 | 103 | public void setJson(String json) { 104 | this.json = json; 105 | } 106 | 107 | public String getSettings() { 108 | return settings; 109 | } 110 | 111 | public void setSettings(String settings) { 112 | this.settings = settings; 113 | } 114 | 115 | public LtiKeyEntity getLtiKey() { 116 | return ltiKey; 117 | } 118 | 119 | public void setLtiKey(LtiKeyEntity ltiKey) { 120 | this.ltiKey = ltiKey; 121 | } 122 | 123 | public Set getLinks() { 124 | return links; 125 | } 126 | 127 | public void setLinks(Set links) { 128 | this.links = links; 129 | } 130 | 131 | public Set getMemberships() { 132 | return memberships; 133 | } 134 | 135 | public void setMemberships(Set memberships) { 136 | this.memberships = memberships; 137 | } 138 | 139 | @Override 140 | public boolean equals(Object o) { 141 | if (this == o) return true; 142 | if (o == null || getClass() != o.getClass()) return false; 143 | 144 | LtiContextEntity that = (LtiContextEntity) o; 145 | 146 | if (contextId != that.contextId) return false; 147 | if (contextKey != null ? !contextKey.equals(that.contextKey) : that.contextKey != null) return false; 148 | if (contextSha256 != null ? !contextSha256.equals(that.contextSha256) : that.contextSha256 != null) 149 | return false; 150 | 151 | return true; 152 | } 153 | 154 | @Override 155 | public int hashCode() { 156 | int result = (int) contextId; 157 | result = 31 * result + (contextSha256 != null ? contextSha256.hashCode() : 0); 158 | result = 31 * result + (contextKey != null ? contextKey.hashCode() : 0); 159 | return result; 160 | } 161 | 162 | } 163 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/config/ApplicationConfig.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.config; 16 | 17 | import ltistarter.model.ConfigEntity; 18 | import ltistarter.repository.ConfigRepository; 19 | import org.apache.commons.lang3.ArrayUtils; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | import org.springframework.beans.BeansException; 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.context.ApplicationContext; 25 | import org.springframework.context.ApplicationContextAware; 26 | import org.springframework.core.convert.ConversionService; 27 | import org.springframework.core.env.ConfigurableEnvironment; 28 | import org.springframework.stereotype.Component; 29 | 30 | import javax.annotation.PostConstruct; 31 | import javax.annotation.PreDestroy; 32 | import javax.annotation.Resource; 33 | 34 | /** 35 | * Allows for easy access to the application configuration, 36 | * merges config settings from spring and local application config 37 | */ 38 | @Component 39 | public class ApplicationConfig implements ApplicationContextAware { 40 | 41 | final static Logger log = LoggerFactory.getLogger(ApplicationConfig.class); 42 | private volatile static ApplicationContext context; 43 | private volatile static ApplicationConfig config; 44 | 45 | @Autowired 46 | ConfigurableEnvironment env; 47 | 48 | @Resource(name = "defaultConversionService") 49 | @SuppressWarnings("SpringJavaAutowiringInspection") 50 | ConversionService conversionService; 51 | 52 | @Autowired 53 | @SuppressWarnings("SpringJavaAutowiringInspection") 54 | ConfigRepository configRepository; 55 | 56 | @PostConstruct 57 | public void init() { 58 | log.info("INIT"); 59 | //log.info("profiles active: " + ArrayUtils.toString(env.getActiveProfiles())); 60 | //log.info("profiles default: " + ArrayUtils.toString(env.getDefaultProfiles())); 61 | env.setActiveProfiles("dev", "testing"); 62 | config = this; 63 | log.info("Config INIT: profiles active: " + ArrayUtils.toString(env.getActiveProfiles())); 64 | } 65 | 66 | @PreDestroy 67 | public void shutdown() { 68 | context = null; 69 | config = null; 70 | log.info("DESTROY"); 71 | } 72 | 73 | // DELEGATED from the spring Environment (easier config access) 74 | 75 | public ConfigurableEnvironment getEnvironment() { 76 | return env; 77 | } 78 | 79 | /** 80 | * Return whether the given property key is available for resolution, i.e., 81 | * the value for the given key is not {@code null}. 82 | */ 83 | public boolean containsProperty(String key) { 84 | assert key != null; 85 | boolean contains = env.containsProperty(key); 86 | if (!contains) { 87 | ConfigEntity ce = configRepository.findByName(key); 88 | contains = (ce != null); 89 | } 90 | return contains; 91 | } 92 | 93 | /** 94 | * Return the property value associated with the given key, or 95 | * {@code defaultValue} if the key cannot be resolved. 96 | * 97 | * @param key the property name to resolve 98 | * @param defaultValue the default value to return if no value is found 99 | */ 100 | public String getProperty(String key, String defaultValue) { 101 | return getProperty(key, String.class, defaultValue); 102 | } 103 | 104 | /** 105 | * Return the property value associated with the given key, or 106 | * {@code defaultValue} if the key cannot be resolved. 107 | * 108 | * @param key the property name to resolve 109 | * @param targetType the expected type of the property value 110 | * @param defaultValue the default value to return if no value is found 111 | */ 112 | public T getProperty(String key, Class targetType, T defaultValue) { 113 | assert key != null; 114 | assert targetType != null; 115 | T property = env.getProperty(key, targetType, defaultValue); 116 | // check for database override 117 | ConfigEntity ce = configRepository.findByName(key); 118 | if (ce != null) { 119 | try { 120 | property = conversionService.convert(ce.getValue(), targetType); 121 | } catch (Exception e) { 122 | property = defaultValue; 123 | log.warn("Failed to convert config (" + ce.getValue() + ") into a (" + targetType + "), using default (" + defaultValue + "): " + e); 124 | } 125 | } 126 | return property; 127 | } 128 | 129 | @Override 130 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 131 | context = applicationContext; 132 | } 133 | 134 | /** 135 | * @return the current service instance the spring application context (only populated after init) 136 | */ 137 | public static ApplicationContext getContext() { 138 | return context; 139 | } 140 | 141 | /** 142 | * @return the current service instance of the config object (only populated after init) 143 | */ 144 | public static ApplicationConfig getInstance() { 145 | return config; 146 | } 147 | 148 | } 149 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/LtiKeyEntity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.model; 16 | 17 | import org.apache.commons.lang3.StringUtils; 18 | 19 | import javax.persistence.*; 20 | import java.util.Set; 21 | 22 | @Entity 23 | @Table(name = "lti_key") 24 | public class LtiKeyEntity extends BaseEntity { 25 | @Id 26 | @GeneratedValue(strategy = GenerationType.AUTO) 27 | @Column(name = "key_id", nullable = false) 28 | private long keyId; 29 | @Basic 30 | @Column(name = "key_sha256", unique = true, nullable = false, insertable = true, updatable = true, length = 64) 31 | private String keySha256; 32 | @Basic 33 | @Column(name = "key_key", unique = true, nullable = false, insertable = true, updatable = true, length = 4096) 34 | private String keyKey; 35 | @Basic 36 | @Column(name = "secret", nullable = false, insertable = true, updatable = true, length = 4096) 37 | private String secret; 38 | @Basic 39 | @Column(name = "new_secret", nullable = true, length = 4096) 40 | private String newSecret; 41 | @Basic 42 | @Column(name = "json", nullable = true, length = 65535) 43 | private String json; 44 | @Basic 45 | @Column(nullable = true, length = 65535) 46 | private String settings; 47 | @Basic 48 | @Column(name = "consumer_profile", nullable = true, length = 65535) 49 | private String consumerProfile; 50 | @Basic 51 | @Column(name = "new_consumer_profile", nullable = true, length = 65535) 52 | private String newConsumerProfile; 53 | 54 | @OneToMany(mappedBy = "ltiKey", fetch = FetchType.LAZY) 55 | private Set contexts; 56 | @OneToMany(mappedBy = "ltiKey", fetch = FetchType.LAZY) 57 | private Set services; 58 | 59 | protected LtiKeyEntity() { 60 | } 61 | 62 | /** 63 | * @param key the key 64 | * @param secret [OPTIONAL] secret (can be null) 65 | */ 66 | public LtiKeyEntity(String key, String secret) { 67 | assert StringUtils.isNotBlank(key); 68 | this.keyKey = key; 69 | this.keySha256 = makeSHA256(key); 70 | if (StringUtils.isNotBlank(secret)) { 71 | this.secret = secret; 72 | } 73 | } 74 | 75 | public long getKeyId() { 76 | return keyId; 77 | } 78 | 79 | public void setKeyId(long keyId) { 80 | this.keyId = keyId; 81 | } 82 | 83 | public String getKeySha256() { 84 | return keySha256; 85 | } 86 | 87 | public void setKeySha256(String keySha256) { 88 | this.keySha256 = keySha256; 89 | } 90 | 91 | public String getKeyKey() { 92 | return keyKey; 93 | } 94 | 95 | public void setKeyKey(String keyKey) { 96 | this.keyKey = keyKey; 97 | } 98 | 99 | public String getSecret() { 100 | return secret; 101 | } 102 | 103 | public void setSecret(String secret) { 104 | this.secret = secret; 105 | } 106 | 107 | public String getJson() { 108 | return json; 109 | } 110 | 111 | public void setJson(String json) { 112 | this.json = json; 113 | } 114 | 115 | public String getSettings() { 116 | return settings; 117 | } 118 | 119 | public void setSettings(String settings) { 120 | this.settings = settings; 121 | } 122 | 123 | public Set getContexts() { 124 | return contexts; 125 | } 126 | 127 | public void setContexts(Set contexts) { 128 | this.contexts = contexts; 129 | } 130 | 131 | public Set getServices() { 132 | return services; 133 | } 134 | 135 | public void setServices(Set services) { 136 | this.services = services; 137 | } 138 | 139 | public String getNewSecret() { 140 | return newSecret; 141 | } 142 | 143 | public void setNewSecret(String newSecret) { 144 | this.newSecret = newSecret; 145 | } 146 | 147 | public String getConsumerProfile() { 148 | return consumerProfile; 149 | } 150 | 151 | public void setConsumerProfile(String consumerProfile) { 152 | this.consumerProfile = consumerProfile; 153 | } 154 | 155 | public String getNewConsumerProfile() { 156 | return newConsumerProfile; 157 | } 158 | 159 | public void setNewConsumerProfile(String newConsumerProfile) { 160 | this.newConsumerProfile = newConsumerProfile; 161 | } 162 | 163 | @Override 164 | public boolean equals(Object o) { 165 | if (this == o) return true; 166 | if (o == null || getClass() != o.getClass()) return false; 167 | 168 | LtiKeyEntity that = (LtiKeyEntity) o; 169 | 170 | if (keyId != that.keyId) return false; 171 | if (keyKey != null ? !keyKey.equals(that.keyKey) : that.keyKey != null) return false; 172 | if (keySha256 != null ? !keySha256.equals(that.keySha256) : that.keySha256 != null) return false; 173 | 174 | return true; 175 | } 176 | 177 | @Override 178 | public int hashCode() { 179 | int result = (int) keyId; 180 | result = 31 * result + (keySha256 != null ? keySha256.hashCode() : 0); 181 | result = 31 * result + (keyKey != null ? keyKey.hashCode() : 0); 182 | return result; 183 | } 184 | 185 | } 186 | -------------------------------------------------------------------------------- /src/test/java/ltistarter/oauth/OAuth1LibraryTests.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.oauth; 16 | 17 | import ltistarter.Application; 18 | import org.junit.Before; 19 | import org.junit.Test; 20 | import org.junit.runner.RunWith; 21 | import org.mockito.Mock; 22 | import org.mockito.MockitoAnnotations; 23 | import org.springframework.boot.test.SpringApplicationConfiguration; 24 | import org.springframework.security.oauth.common.OAuthConsumerParameter; 25 | import org.springframework.security.oauth.provider.filter.CoreOAuthProviderSupport; 26 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 27 | import org.springframework.test.context.web.WebAppConfiguration; 28 | 29 | import javax.servlet.http.HttpServletRequest; 30 | import java.util.Arrays; 31 | import java.util.Collections; 32 | import java.util.HashMap; 33 | import java.util.Map; 34 | 35 | import static org.junit.Assert.assertEquals; 36 | import static org.mockito.Mockito.when; 37 | 38 | @RunWith(SpringJUnit4ClassRunner.class) 39 | @SpringApplicationConfiguration(classes = Application.class) 40 | @WebAppConfiguration 41 | public class OAuth1LibraryTests { 42 | 43 | @Mock 44 | private HttpServletRequest request; 45 | 46 | @Before 47 | public void setup() { 48 | MockitoAnnotations.initMocks(this); // init the mocks 49 | } 50 | 51 | // test REALLY basic OAuth library functions (just making sure OAuth 1.0 stuff is loaded really 52 | 53 | @Test 54 | public void testParseParameters() throws Exception { 55 | CoreOAuthProviderSupport support = new CoreOAuthProviderSupport(); 56 | when(request.getHeaders("Authorization")).thenReturn( 57 | Collections.enumeration(Arrays.asList("OAuth realm=\"http://sp.example.com/\",\n" 58 | + " oauth_consumer_key=\"0685bd9184jfhq22\",\n" 59 | + " oauth_token=\"ad180jjd733klru7\",\n" 60 | + " oauth_signature_method=\"HMAC-SHA1\",\n" 61 | + " oauth_signature=\"wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D\",\n" 62 | + " oauth_timestamp=\"137131200\",\n" 63 | + " oauth_nonce=\"4572616e48616d6d65724c61686176\",\n" 64 | + " oauth_version=\"1.0\""))); 65 | 66 | Map params = support.parseParameters(request); 67 | assertEquals("http://sp.example.com/", params.get("realm")); 68 | assertEquals("0685bd9184jfhq22", params.get(OAuthConsumerParameter.oauth_consumer_key.toString())); 69 | assertEquals("ad180jjd733klru7", params.get(OAuthConsumerParameter.oauth_token.toString())); 70 | assertEquals("HMAC-SHA1", params.get(OAuthConsumerParameter.oauth_signature_method.toString())); 71 | assertEquals("wOJIO9A2W5mFwDgiDvZbTSMK/PY=", params.get(OAuthConsumerParameter.oauth_signature.toString())); 72 | assertEquals("137131200", params.get(OAuthConsumerParameter.oauth_timestamp.toString())); 73 | assertEquals("4572616e48616d6d65724c61686176", params.get(OAuthConsumerParameter.oauth_nonce.toString())); 74 | assertEquals("1.0", params.get(OAuthConsumerParameter.oauth_version.toString())); 75 | } 76 | 77 | @Test 78 | public void testGetSignatureBaseString() throws Exception { 79 | Map requestParameters = new HashMap<>(); 80 | requestParameters.put("file", new String[]{"vacation.jpg"}); 81 | requestParameters.put("size", new String[]{"original"}); 82 | 83 | when(request.getParameterNames()).thenReturn(Collections.enumeration(requestParameters.keySet())); 84 | for (String key : requestParameters.keySet()) { 85 | when(request.getParameterValues(key)).thenReturn(requestParameters.get(key)); 86 | } 87 | 88 | when(request.getHeaders("Authorization")).thenReturn( 89 | Collections.enumeration(Arrays.asList("OAuth realm=\"http://sp.example.com/\",\n" 90 | + " oauth_consumer_key=\"dpf43f3p2l4k3l03\",\n" 91 | + " oauth_token=\"nnch734d00sl2jdk\",\n" 92 | + " oauth_signature_method=\"HMAC-SHA1\",\n" 93 | + " oauth_signature=\"unimportantforthistest\",\n" 94 | + " oauth_timestamp=\"1191242096\",\n" 95 | + " oauth_nonce=\"kllo9940pd9333jh\",\n" 96 | + " oauth_version=\"1.0\""))); 97 | 98 | when(request.getMethod()).thenReturn("gEt"); 99 | 100 | CoreOAuthProviderSupport support = new CoreOAuthProviderSupport(); 101 | support.setBaseUrl("http://photos.example.net"); 102 | when(request.getRequestURI()).thenReturn("photos"); 103 | 104 | String baseString = support.getSignatureBaseString(request); 105 | assertEquals("GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal", 106 | baseString); 107 | } 108 | 109 | } -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/ProfileEntity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.model; 16 | 17 | import javax.persistence.*; 18 | import java.sql.Timestamp; 19 | import java.util.Date; 20 | import java.util.HashSet; 21 | import java.util.Set; 22 | 23 | @Entity 24 | @Table(name = "profile") 25 | public class ProfileEntity extends BaseEntity { 26 | @Id 27 | @GeneratedValue(strategy = GenerationType.AUTO) 28 | @Column(name = "profile_id", nullable = false, insertable = true, updatable = true) 29 | private long profileId; 30 | @Basic 31 | @Column(name = "profile_sha256", nullable = false, insertable = true, updatable = true, length = 64) 32 | private String profileSha256; 33 | @Basic 34 | @Column(name = "profile_key", nullable = false, insertable = true, updatable = true, length = 4096) 35 | private String profileKey; 36 | @Basic 37 | @Column(name = "displayName", nullable = true, insertable = true, updatable = true, length = 2048) 38 | private String displayName; 39 | @Basic 40 | @Column(name = "email", nullable = true, insertable = true, updatable = true, length = 2048) 41 | private String email; 42 | @Basic 43 | @Column(name = "locale", nullable = true, insertable = true, updatable = true, length = 63) 44 | private String locale; 45 | @Basic 46 | @Column(name = "subscribe", nullable = true, insertable = true, updatable = true) 47 | private Short subscribe; 48 | @Basic 49 | @Column(name = "json", nullable = true, insertable = true, updatable = true, length = 65535) 50 | private String json; 51 | @Basic 52 | @Column(name = "login_at", nullable = false, insertable = true, updatable = true) 53 | private Timestamp loginAt; 54 | 55 | @OneToMany(mappedBy = "profile", fetch = FetchType.LAZY) 56 | private Set ssoKeys = new HashSet<>(); 57 | @OneToMany(mappedBy = "profile", fetch = FetchType.LAZY) 58 | private Set users = new HashSet<>(); 59 | 60 | public ProfileEntity() { 61 | } 62 | 63 | public ProfileEntity(String profileKey, Date loginAt, String email) { 64 | assert profileKey != null; 65 | if (loginAt == null) { 66 | loginAt = new Date(); 67 | } 68 | this.profileKey = profileKey; 69 | this.profileSha256 = makeSHA256(profileKey); 70 | this.loginAt = new Timestamp(loginAt.getTime()); 71 | this.email = email; 72 | } 73 | 74 | public long getProfileId() { 75 | return profileId; 76 | } 77 | 78 | public void setProfileId(long profileId) { 79 | this.profileId = profileId; 80 | } 81 | 82 | public String getProfileSha256() { 83 | return profileSha256; 84 | } 85 | 86 | public void setProfileSha256(String profileSha256) { 87 | this.profileSha256 = profileSha256; 88 | } 89 | 90 | public String getProfileKey() { 91 | return profileKey; 92 | } 93 | 94 | public void setProfileKey(String profileKey) { 95 | this.profileKey = profileKey; 96 | } 97 | 98 | public String getDisplayName() { 99 | return displayName; 100 | } 101 | 102 | public void setDisplayName(String displayName) { 103 | this.displayName = displayName; 104 | } 105 | 106 | public String getEmail() { 107 | return email; 108 | } 109 | 110 | public void setEmail(String email) { 111 | this.email = email; 112 | } 113 | 114 | public String getLocale() { 115 | return locale; 116 | } 117 | 118 | public void setLocale(String locale) { 119 | this.locale = locale; 120 | } 121 | 122 | public Short getSubscribe() { 123 | return subscribe; 124 | } 125 | 126 | public void setSubscribe(Short subscribe) { 127 | this.subscribe = subscribe; 128 | } 129 | 130 | public String getJson() { 131 | return json; 132 | } 133 | 134 | public void setJson(String json) { 135 | this.json = json; 136 | } 137 | 138 | public Timestamp getLoginAt() { 139 | return loginAt; 140 | } 141 | 142 | public void setLoginAt(Timestamp loginAt) { 143 | this.loginAt = loginAt; 144 | } 145 | 146 | public Set getSsoKeys() { 147 | return ssoKeys; 148 | } 149 | 150 | public void setSsoKeys(Set ssoKeys) { 151 | this.ssoKeys = ssoKeys; 152 | } 153 | 154 | public Set getUsers() { 155 | return users; 156 | } 157 | 158 | public void setUsers(Set users) { 159 | this.users = users; 160 | } 161 | 162 | @Override 163 | public boolean equals(Object o) { 164 | if (this == o) return true; 165 | if (o == null || getClass() != o.getClass()) return false; 166 | 167 | ProfileEntity that = (ProfileEntity) o; 168 | 169 | if (profileId != that.profileId) return false; 170 | if (profileKey != null ? !profileKey.equals(that.profileKey) : that.profileKey != null) return false; 171 | if (profileSha256 != null ? !profileSha256.equals(that.profileSha256) : that.profileSha256 != null) 172 | return false; 173 | 174 | return true; 175 | } 176 | 177 | @Override 178 | public int hashCode() { 179 | int result = (int) profileId; 180 | result = 31 * result + (profileSha256 != null ? profileSha256.hashCode() : 0); 181 | result = 31 * result + (profileKey != null ? profileKey.hashCode() : 0); 182 | return result; 183 | } 184 | 185 | } 186 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/LtiUserEntity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.model; 16 | 17 | import org.apache.commons.lang3.StringUtils; 18 | 19 | import javax.persistence.*; 20 | import java.sql.Timestamp; 21 | import java.util.Date; 22 | import java.util.Set; 23 | 24 | @Entity 25 | @Table(name = "lti_user") 26 | public class LtiUserEntity extends BaseEntity { 27 | @Id 28 | @GeneratedValue(strategy = GenerationType.AUTO) 29 | @Column(name = "user_id", nullable = false, insertable = true, updatable = true) 30 | private long userId; 31 | @Basic 32 | @Column(name = "user_sha256", nullable = false, insertable = true, updatable = true, length = 64) 33 | private String userSha256; 34 | @Basic 35 | @Column(name = "user_key", nullable = false, insertable = true, updatable = true, length = 4096) 36 | private String userKey; 37 | @Basic 38 | @Column(name = "displayname", nullable = true, insertable = true, updatable = true, length = 4096) 39 | private String displayName; 40 | /** 41 | * Actual max for emails is 254 chars 42 | */ 43 | @Basic 44 | @Column(name = "email", nullable = true, insertable = true, updatable = true, length = 255) 45 | private String email; 46 | @Basic 47 | @Column(name = "locale", nullable = true, insertable = true, updatable = true, length = 63) 48 | private String locale; 49 | @Basic 50 | @Column(name = "subscribe", nullable = true, insertable = true, updatable = true) 51 | private Short subscribe; 52 | @Basic 53 | @Column(name = "json", nullable = true, insertable = true, updatable = true, length = 65535) 54 | private String json; 55 | @Basic 56 | @Column(name = "login_at", nullable = false, insertable = true, updatable = true) 57 | private Timestamp loginAt; 58 | 59 | @ManyToOne(fetch = FetchType.LAZY, optional = true) 60 | @JoinColumn(name = "profile_id", nullable = true) 61 | private ProfileEntity profile; 62 | @OneToMany(mappedBy = "user", fetch = FetchType.LAZY) 63 | private Set results; 64 | 65 | protected LtiUserEntity() { 66 | } 67 | 68 | /** 69 | * @param userKey user identifier 70 | * @param loginAt date of user login 71 | */ 72 | public LtiUserEntity(String userKey, Date loginAt) { 73 | assert StringUtils.isNotBlank(userKey); 74 | if (loginAt == null) { 75 | loginAt = new Date(); 76 | } 77 | this.userKey = userKey; 78 | this.userSha256 = makeSHA256(userKey); 79 | this.loginAt = new Timestamp(loginAt.getTime()); 80 | } 81 | 82 | public long getUserId() { 83 | return userId; 84 | } 85 | 86 | public void setUserId(long userId) { 87 | this.userId = userId; 88 | } 89 | 90 | public String getUserSha256() { 91 | return userSha256; 92 | } 93 | 94 | public void setUserSha256(String userSha256) { 95 | this.userSha256 = userSha256; 96 | } 97 | 98 | public String getUserKey() { 99 | return userKey; 100 | } 101 | 102 | public void setUserKey(String userKey) { 103 | this.userKey = userKey; 104 | } 105 | 106 | public String getDisplayName() { 107 | return displayName; 108 | } 109 | 110 | public void setDisplayName(String displayName) { 111 | this.displayName = displayName; 112 | } 113 | 114 | public String getEmail() { 115 | return email; 116 | } 117 | 118 | public void setEmail(String email) { 119 | this.email = email; 120 | } 121 | 122 | public String getLocale() { 123 | return locale; 124 | } 125 | 126 | public void setLocale(String locale) { 127 | this.locale = locale; 128 | } 129 | 130 | public Short getSubscribe() { 131 | return subscribe; 132 | } 133 | 134 | public void setSubscribe(Short subscribe) { 135 | this.subscribe = subscribe; 136 | } 137 | 138 | public String getJson() { 139 | return json; 140 | } 141 | 142 | public void setJson(String json) { 143 | this.json = json; 144 | } 145 | 146 | public Timestamp getLoginAt() { 147 | return loginAt; 148 | } 149 | 150 | public void setLoginAt(Timestamp loginAt) { 151 | this.loginAt = loginAt; 152 | } 153 | 154 | public ProfileEntity getProfile() { 155 | return profile; 156 | } 157 | 158 | public void setProfile(ProfileEntity profile) { 159 | this.profile = profile; 160 | } 161 | 162 | public Set getResults() { 163 | return results; 164 | } 165 | 166 | public void setResults(Set results) { 167 | this.results = results; 168 | } 169 | 170 | @Override 171 | public boolean equals(Object o) { 172 | if (this == o) return true; 173 | if (o == null || getClass() != o.getClass()) return false; 174 | 175 | LtiUserEntity that = (LtiUserEntity) o; 176 | 177 | if (userId != that.userId) return false; 178 | if (email != null ? !email.equals(that.email) : that.email != null) return false; 179 | if (userKey != null ? !userKey.equals(that.userKey) : that.userKey != null) return false; 180 | if (userSha256 != null ? !userSha256.equals(that.userSha256) : that.userSha256 != null) return false; 181 | 182 | return true; 183 | } 184 | 185 | @Override 186 | public int hashCode() { 187 | int result = (int) userId; 188 | result = 31 * result + (userSha256 != null ? userSha256.hashCode() : 0); 189 | result = 31 * result + (userKey != null ? userKey.hashCode() : 0); 190 | result = 31 * result + (email != null ? email.hashCode() : 0); 191 | return result; 192 | } 193 | 194 | } 195 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/model/LtiResultEntity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.model; 16 | 17 | import org.apache.commons.lang3.StringUtils; 18 | 19 | import javax.persistence.*; 20 | import java.sql.Timestamp; 21 | import java.util.Date; 22 | 23 | @Entity 24 | @Table(name = "lti_result") 25 | public class LtiResultEntity extends BaseEntity { 26 | @Id 27 | @GeneratedValue(strategy = GenerationType.AUTO) 28 | @Column(name = "result_id", nullable = false, insertable = true, updatable = true) 29 | private long resultId; 30 | @Basic 31 | @Column(name = "sourcedid", nullable = false, insertable = true, updatable = true, length = 4096) 32 | private String sourcedid; 33 | @Basic 34 | @Column(name = "sourcedid_sha256", nullable = false, insertable = true, updatable = true, length = 64) 35 | private String sourcedidSha256; 36 | @Basic 37 | @Column(name = "grade", nullable = true, insertable = true, updatable = true, precision = 0) 38 | private Float grade; 39 | @Basic 40 | @Column(name = "note", nullable = true, insertable = true, updatable = true, length = 4096) 41 | private String note; 42 | @Basic 43 | @Column(name = "server_grade", nullable = true, insertable = true, updatable = true, precision = 0) 44 | private Float serverGrade; 45 | @Basic 46 | @Column(name = "json", nullable = true, insertable = true, updatable = true, length = 65535) 47 | private String json; 48 | @Basic 49 | @Column(name = "retrieved_at", nullable = false, insertable = true, updatable = true) 50 | private Timestamp retrievedAt; 51 | 52 | @ManyToOne(fetch = FetchType.LAZY, optional = false) 53 | @JoinColumn(name = "link_id") 54 | private LtiLinkEntity link; 55 | @ManyToOne(fetch = FetchType.LAZY, optional = false) 56 | @JoinColumn(name = "user_id") 57 | private LtiUserEntity user; 58 | 59 | @ManyToOne(fetch = FetchType.LAZY, optional = true, cascade = CascadeType.DETACH) 60 | @JoinColumn(name = "service_id") 61 | private LtiServiceEntity service; 62 | 63 | protected LtiResultEntity() { 64 | } 65 | 66 | /** 67 | * @param sourcedid the external key sourcedid 68 | * @param user the user for this grade result 69 | * @param link the link which this is a grade for 70 | * @param retrievedAt the date the grade was retrieved (null indicates now) 71 | * @param grade [OPTIONAL] the grade value 72 | */ 73 | public LtiResultEntity(String sourcedid, LtiUserEntity user, LtiLinkEntity link, Date retrievedAt, Float grade) { 74 | assert StringUtils.isNotBlank(sourcedid); 75 | assert user != null; 76 | assert link != null; 77 | if (retrievedAt == null) { 78 | retrievedAt = new Date(); 79 | } 80 | this.sourcedid = sourcedid; 81 | this.sourcedidSha256 = makeSHA256(sourcedid); 82 | this.retrievedAt = new Timestamp(retrievedAt.getTime()); 83 | this.user = user; 84 | this.link = link; 85 | this.grade = grade; 86 | } 87 | 88 | public long getResultId() { 89 | return resultId; 90 | } 91 | 92 | public void setResultId(long resultId) { 93 | this.resultId = resultId; 94 | } 95 | 96 | public String getSourcedid() { 97 | return sourcedid; 98 | } 99 | 100 | public void setSourcedid(String sourcedid) { 101 | this.sourcedid = sourcedid; 102 | } 103 | 104 | public String getSourcedidSha256() { 105 | return sourcedidSha256; 106 | } 107 | 108 | public void setSourcedidSha256(String sourcedidSha256) { 109 | this.sourcedidSha256 = sourcedidSha256; 110 | } 111 | 112 | public Float getGrade() { 113 | return grade; 114 | } 115 | 116 | public void setGrade(Float grade) { 117 | this.grade = grade; 118 | } 119 | 120 | public String getNote() { 121 | return note; 122 | } 123 | 124 | public void setNote(String note) { 125 | this.note = note; 126 | } 127 | 128 | public Float getServerGrade() { 129 | return serverGrade; 130 | } 131 | 132 | public void setServerGrade(Float serverGrade) { 133 | this.serverGrade = serverGrade; 134 | } 135 | 136 | public String getJson() { 137 | return json; 138 | } 139 | 140 | public void setJson(String json) { 141 | this.json = json; 142 | } 143 | 144 | public Timestamp getRetrievedAt() { 145 | return retrievedAt; 146 | } 147 | 148 | public void setRetrievedAt(Timestamp retrievedAt) { 149 | this.retrievedAt = retrievedAt; 150 | } 151 | 152 | public LtiLinkEntity getLink() { 153 | return link; 154 | } 155 | 156 | public void setLink(LtiLinkEntity link) { 157 | this.link = link; 158 | } 159 | 160 | public LtiUserEntity getUser() { 161 | return user; 162 | } 163 | 164 | public void setUser(LtiUserEntity user) { 165 | this.user = user; 166 | } 167 | 168 | public LtiServiceEntity getService() { 169 | return service; 170 | } 171 | 172 | public void setService(LtiServiceEntity service) { 173 | this.service = service; 174 | } 175 | 176 | @Override 177 | public boolean equals(Object o) { 178 | if (this == o) return true; 179 | if (o == null || getClass() != o.getClass()) return false; 180 | 181 | LtiResultEntity that = (LtiResultEntity) o; 182 | 183 | if (resultId != that.resultId) return false; 184 | if (sourcedid != null ? !sourcedid.equals(that.sourcedid) : that.sourcedid != null) return false; 185 | if (sourcedidSha256 != null ? !sourcedidSha256.equals(that.sourcedidSha256) : that.sourcedidSha256 != null) 186 | return false; 187 | 188 | return true; 189 | } 190 | 191 | @Override 192 | public int hashCode() { 193 | int result = (int) resultId; 194 | result = 31 * result + (sourcedid != null ? sourcedid.hashCode() : 0); 195 | result = 31 * result + (sourcedidSha256 != null ? sourcedidSha256.hashCode() : 0); 196 | return result; 197 | } 198 | 199 | } 200 | -------------------------------------------------------------------------------- /src/test/java/ltistarter/controllers/AppControllersTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.controllers; 16 | 17 | import ltistarter.BaseApplicationTest; 18 | import ltistarter.lti.LTIRequest; 19 | import ltistarter.model.LtiKeyEntity; 20 | import ltistarter.repository.LtiKeyRepository; 21 | import org.junit.Before; 22 | import org.junit.Test; 23 | import org.junit.runner.RunWith; 24 | import org.mockito.MockitoAnnotations; 25 | import org.springframework.beans.factory.annotation.Autowired; 26 | import org.springframework.http.MediaType; 27 | import org.springframework.mock.web.MockHttpSession; 28 | import org.springframework.security.oauth.provider.filter.OAuthProviderProcessingFilter; 29 | import org.springframework.security.web.FilterChainProxy; 30 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 31 | import org.springframework.test.web.servlet.MockMvc; 32 | import org.springframework.test.web.servlet.MvcResult; 33 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 34 | import org.springframework.transaction.annotation.Transactional; 35 | import org.springframework.web.context.WebApplicationContext; 36 | 37 | import static org.junit.Assert.assertNotNull; 38 | import static org.junit.Assert.assertTrue; 39 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 40 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 41 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 42 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 43 | 44 | @RunWith(SpringJUnit4ClassRunner.class) 45 | @SuppressWarnings({"SpringJavaAutowiredMembersInspection", "SpringJavaAutowiringInspection"}) 46 | public class AppControllersTest extends BaseApplicationTest { 47 | 48 | @Autowired 49 | private FilterChainProxy springSecurityFilter; 50 | 51 | private MockMvc mockMvc; 52 | 53 | @Before 54 | public void setup() { 55 | assertNotNull(context); 56 | assertNotNull(springSecurityFilter); 57 | // Process mock annotations 58 | MockitoAnnotations.initMocks(this); 59 | // Setup Spring test in webapp-mode (same config as spring-boot) 60 | this.mockMvc = MockMvcBuilders.webAppContextSetup(context) 61 | .addFilters(springSecurityFilter) 62 | .build(); 63 | context.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); 64 | } 65 | 66 | @Test 67 | public void testLoadRoot() throws Exception { 68 | // Test basic home controller request (no session, no user) 69 | MvcResult result = this.mockMvc.perform(get("/")) 70 | .andExpect(status().isOk()) 71 | .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML)) 72 | .andReturn(); 73 | String content = result.getResponse().getContentAsString(); 74 | assertNotNull(content); 75 | assertTrue(content.contains("Hello Spring Boot")); 76 | assertTrue(content.contains("Form Login endpoint")); 77 | } 78 | 79 | @Test 80 | public void testLoadRootWithAuth() throws Exception { 81 | // Test basic home controller request with a session and logged in user 82 | MockHttpSession session = makeAuthSession("azeckoski", "ROLE_USER"); 83 | MvcResult result = this.mockMvc.perform(get("/").session(session)) 84 | .andExpect(status().isOk()) 85 | .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML)) 86 | .andReturn(); 87 | String content = result.getResponse().getContentAsString(); 88 | assertNotNull(content); 89 | assertTrue(content.contains("Hello Spring Boot")); 90 | assertTrue(content.contains("only shown to users (ROLE_USER)")); 91 | } 92 | 93 | @Test 94 | public void testLoadFormWithAuth() throws Exception { 95 | // Test form controller request with a session and logged in user 96 | MockHttpSession session = makeAuthSession("azeckoski", "ROLE_USER"); 97 | MvcResult result = this.mockMvc.perform(get("/form").session(session)) 98 | .andExpect(status().isOk()) 99 | .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML)) 100 | .andReturn(); 101 | String content = result.getResponse().getContentAsString(); 102 | assertNotNull(content); 103 | assertTrue(content.contains("Hello Spring Boot")); 104 | assertTrue(content.contains("only shown to users (ROLE_USER)")); 105 | assertTrue(content.contains("Logout")); // logout button 106 | } 107 | 108 | @Autowired 109 | @SuppressWarnings({"SpringJavaAutowiredMembersInspection", "SpringJavaAutowiringInspection"}) 110 | LtiKeyRepository ltiKeyRepository; 111 | 112 | @Test 113 | @Transactional // rollback after 114 | public void testLoadLTI() throws Exception { 115 | // test minimal LTI launch 116 | LtiKeyEntity key = ltiKeyRepository.save(new LtiKeyEntity("AZltiKey", "AZsecret")); 117 | MockHttpSession session = makeAuthSession("azeckoski", "ROLE_LTI", "ROLE_OAUTH", "ROLE_USER"); 118 | MvcResult result = this.mockMvc.perform( 119 | post("/lti").session(session) 120 | .requestAttr(OAuthProviderProcessingFilter.OAUTH_PROCESSING_HANDLED, true) // skip OAuth processing in the filter 121 | .param(LTIRequest.LTI_VERSION, LTIRequest.LTI_VERSION_1P0) 122 | .param(LTIRequest.LTI_MESSAGE_TYPE, LTIRequest.LTI_MESSAGE_TYPE_BASIC) 123 | .param(LTIRequest.LTI_CONSUMER_KEY, key.getKeyKey()) 124 | .param(LTIRequest.LTI_LINK_ID, "Mylink") 125 | .param(LTIRequest.LTI_CONTEXT_ID, "courseAZ") 126 | .param(LTIRequest.LTI_USER_ID, "azeckoski") 127 | ).andExpect(status().isOk()).andReturn(); 128 | assertNotNull(result); 129 | String content = result.getResponse().getContentAsString(); 130 | assertNotNull(content); 131 | assertTrue(content.contains("Hello Spring Boot")); 132 | assertTrue(content.contains("only shown to LTI users")); 133 | } 134 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.zeckoski 7 | ltistarter 8 | 0.1-SNAPSHOT 9 | 2014 10 | war 11 | 12 | LTI starter app 13 | IMS LTI starter app 14 | 15 | 16 | org.springframework.boot 17 | spring-boot-starter-parent 18 | 1.1.5.RELEASE 19 | 20 | 21 | 22 | 23 | 24 | UTF-8 25 | ltistarter.Application 26 | 1.7 27 | 28 | 29 | 30 | 31 | org.apache.commons 32 | commons-lang3 33 | 3.3.2 34 | 35 | 36 | commons-codec 37 | commons-codec 38 | 1.9 39 | 40 | 41 | commons-collections 42 | commons-collections 43 | 3.2.1 44 | 45 | 46 | 47 | 48 | com.h2database 49 | h2 50 | 1.4.178 51 | 52 | 53 | 80 | 81 | 82 | 83 | 84 | org.springframework.boot 85 | spring-boot-starter-web 86 | 87 | 88 | org.springframework.boot 89 | spring-boot-starter-tomcat 90 | 91 | 92 | 93 | 94 | org.springframework.boot 95 | spring-boot-starter-jetty 96 | 97 | 98 | 99 | 100 | org.springframework.boot 101 | spring-boot-starter-actuator 102 | 103 | 104 | 105 | 106 | 107 | org.springframework.boot 108 | spring-boot-starter-thymeleaf 109 | 110 | 111 | 112 | org.thymeleaf.extras 113 | thymeleaf-extras-springsecurity3 114 | 115 | 116 | 117 | 118 | org.springframework.boot 119 | spring-boot-starter-security 120 | 121 | 122 | 123 | org.springframework.security.oauth 124 | spring-security-oauth 125 | 2.0.2.RELEASE 126 | 127 | 128 | org.springframework.security.oauth 129 | spring-security-oauth2 130 | 2.0.2.RELEASE 131 | 132 | 133 | 134 | org.springframework.boot 135 | spring-boot-starter-data-jpa 136 | 137 | 138 | 139 | org.springframework.boot 140 | spring-boot-starter-data-rest 141 | 142 | 143 | 144 | org.springframework.boot 145 | spring-boot-starter-test 146 | test 147 | 148 | 149 | 150 | 151 | 152 | 153 | debug 154 | 155 | 156 | 157 | org.springframework.boot 158 | spring-boot-maven-plugin 159 | 160 | 161 | -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | starter 172 | 173 | 174 | maven-compiler-plugin 175 | 2.3.2 176 | 177 | ${java.version} 178 | ${java.version} 179 | 180 | 181 | 182 | org.springframework.boot 183 | spring-boot-maven-plugin 184 | 185 | 186 | 189 | com.mycila.maven-license-plugin 190 | maven-license-plugin 191 | 1.10.b1 192 | 193 | true 194 |
${basedir}/LICENSE_HEADER
195 | 196 | ${project.name} 197 | ${project.inceptionYear} 198 | Unicon (R) 199 | 200 | 201 | .gitignore 202 | target/** 203 | bin/** 204 | .idea/** 205 | **/*.iml 206 | LICENSE* 207 | **/*.properties 208 | **/*.csv 209 | **/*.txt 210 | **/*.md 211 | **/*.sql 212 | **/js/jquery/** 213 | 214 | 215 | DYNASCRIPT_STYLE 216 | 217 | UTF-8 218 |
219 | 220 | 221 | 222 | check 223 | 224 | 225 | 226 |
227 |
228 |
229 | 230 | 231 | 232 | azeckoski 233 | Aaron Zeckoski 234 | azeckoski@vt.edu 235 | http://tinyurl.com/azprofile 236 | 237 | Architect 238 | Developer 239 | 240 | -5 241 | 242 | 243 | 244 | 245 | 246 | Apache License 2.0 247 | repo 248 | http://www.apache.org/licenses/LICENSE-2.0 249 | 250 | 251 | 252 |
253 | -------------------------------------------------------------------------------- /src/main/java/ltistarter/Application.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter; 16 | 17 | import ltistarter.lti.LTIConsumerDetailsService; 18 | import ltistarter.lti.LTIDataService; 19 | import ltistarter.lti.LTIOAuthAuthenticationHandler; 20 | import ltistarter.lti.LTIOAuthProviderProcessingFilter; 21 | import ltistarter.oauth.MyConsumerDetailsService; 22 | import ltistarter.oauth.MyOAuthAuthenticationHandler; 23 | import ltistarter.oauth.MyOAuthNonceServices; 24 | import ltistarter.oauth.ZeroLeggedOAuthProviderProcessingFilter; 25 | import org.h2.server.web.WebServlet; 26 | import org.slf4j.Logger; 27 | import org.slf4j.LoggerFactory; 28 | import org.springframework.beans.factory.annotation.Autowired; 29 | import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; 30 | import org.springframework.boot.SpringApplication; 31 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 32 | import org.springframework.boot.context.embedded.ServletRegistrationBean; 33 | import org.springframework.cache.CacheManager; 34 | import org.springframework.cache.annotation.EnableCaching; 35 | import org.springframework.cache.concurrent.ConcurrentMapCacheManager; 36 | import org.springframework.context.annotation.Bean; 37 | import org.springframework.context.annotation.ComponentScan; 38 | import org.springframework.context.annotation.Configuration; 39 | import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; 40 | import org.springframework.core.Ordered; 41 | import org.springframework.core.annotation.Order; 42 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 43 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 44 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 45 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 46 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 47 | import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; 48 | import org.springframework.security.oauth.provider.OAuthProcessingFilterEntryPoint; 49 | import org.springframework.security.oauth.provider.token.InMemoryProviderTokenServices; 50 | import org.springframework.security.oauth.provider.token.OAuthProviderTokenServices; 51 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 52 | import org.springframework.transaction.annotation.EnableTransactionManagement; 53 | import org.springframework.util.StringValueResolver; 54 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 55 | 56 | import javax.annotation.PostConstruct; 57 | 58 | @ComponentScan("ltistarter") 59 | @Configuration 60 | @EnableAutoConfiguration 61 | @EnableTransactionManagement // enables TX management and @Transaction 62 | @EnableCaching // enables caching and @Cache* tags 63 | @EnableWebMvcSecurity // enable spring security and web mvc hooks 64 | @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) 65 | // allows @Secured flag - proxyTargetClass = true causes this to die 66 | public class Application extends WebMvcConfigurerAdapter { 67 | 68 | final static Logger log = LoggerFactory.getLogger(Application.class); 69 | 70 | public static void main(String[] args) { 71 | SpringApplication.run(Application.class, args); 72 | } 73 | 74 | /** 75 | * Allows access to the various config values (from application.properties) using @Value 76 | */ 77 | @Bean 78 | public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() { 79 | return new PropertySourcesPlaceholderConfigurer() { 80 | @Override 81 | protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess, StringValueResolver valueResolver) { 82 | log.info("doProcessProperties"); 83 | super.doProcessProperties(beanFactoryToProcess, valueResolver); 84 | } 85 | }; 86 | } 87 | 88 | /** 89 | * Creates a CacheManager which allows the spring caching annotations to work 90 | * Annotations: Cacheable, CachePut and CacheEvict 91 | * http://spring.io/guides/gs/caching/ 92 | */ 93 | @Bean 94 | public CacheManager cacheManager() { 95 | return new ConcurrentMapCacheManager(); // not appropriate for production, try JCacheCacheManager or HazelcastCacheManager instead 96 | } 97 | 98 | /** 99 | * Allows access to the H2 console at: {server}/console/ 100 | * Enter this as the JDBC URL: jdbc:h2:mem:AZ 101 | */ 102 | @Bean 103 | public ServletRegistrationBean h2servletRegistration() { 104 | ServletRegistrationBean registration = new ServletRegistrationBean(new WebServlet()); 105 | registration.addUrlMappings("/console/*"); 106 | return registration; 107 | } 108 | 109 | // Spring Security 110 | 111 | @Autowired 112 | @Order(Ordered.HIGHEST_PRECEDENCE + 10) 113 | @SuppressWarnings("SpringJavaAutowiringInspection") 114 | public void configureSimpleAuthUsers(AuthenticationManagerBuilder auth) throws Exception { 115 | auth.inMemoryAuthentication() 116 | .withUser("admin").password("admin").roles("ADMIN", "USER") 117 | .and().withUser("user").password("user").roles("USER"); 118 | } 119 | 120 | @Configuration 121 | @Order(1) // HIGHEST 122 | public static class LTISecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { 123 | private LTIOAuthProviderProcessingFilter ltioAuthProviderProcessingFilter; 124 | @Autowired 125 | LTIDataService ltiDataService; 126 | @Autowired 127 | LTIConsumerDetailsService oauthConsumerDetailsService; 128 | @Autowired 129 | MyOAuthNonceServices oauthNonceServices; 130 | @Autowired 131 | LTIOAuthAuthenticationHandler oauthAuthenticationHandler; 132 | @Autowired 133 | OAuthProcessingFilterEntryPoint oauthProcessingFilterEntryPoint; 134 | @Autowired 135 | OAuthProviderTokenServices oauthProviderTokenServices; 136 | 137 | @PostConstruct 138 | public void init() { 139 | ltioAuthProviderProcessingFilter = new LTIOAuthProviderProcessingFilter(ltiDataService, oauthConsumerDetailsService, oauthNonceServices, oauthProcessingFilterEntryPoint, oauthAuthenticationHandler, oauthProviderTokenServices); 140 | } 141 | 142 | @Override 143 | protected void configure(HttpSecurity http) throws Exception { 144 | /**/ 145 | http.requestMatchers().antMatchers("/lti/**", "/lti2/**").and().addFilterBefore(ltioAuthProviderProcessingFilter, UsernamePasswordAuthenticationFilter.class).authorizeRequests().anyRequest().hasRole("LTI").and().csrf().disable(); 146 | /* 147 | http.antMatcher("/lti/**") 148 | .addFilterBefore(ltioAuthProviderProcessingFilter, UsernamePasswordAuthenticationFilter.class) 149 | .authorizeRequests().anyRequest().hasRole("LTI") 150 | .and().csrf().disable(); // probably need https://github.com/spring-projects/spring-boot/issues/179 151 | /**/ 152 | } 153 | } 154 | 155 | @Configuration 156 | @Order(11) // HIGH 157 | public static class OAuthSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { 158 | private ZeroLeggedOAuthProviderProcessingFilter zeroLeggedOAuthProviderProcessingFilter; 159 | @Autowired 160 | MyConsumerDetailsService oauthConsumerDetailsService; 161 | @Autowired 162 | MyOAuthNonceServices oauthNonceServices; 163 | @Autowired 164 | MyOAuthAuthenticationHandler oauthAuthenticationHandler; 165 | @Autowired 166 | OAuthProcessingFilterEntryPoint oauthProcessingFilterEntryPoint; 167 | @Autowired 168 | OAuthProviderTokenServices oauthProviderTokenServices; 169 | 170 | @PostConstruct 171 | public void init() { 172 | // NOTE: have to build the filter here: http://stackoverflow.com/questions/24761194/how-do-i-stop-spring-filterregistrationbean-from-registering-my-filter-on/24762970 173 | zeroLeggedOAuthProviderProcessingFilter = new ZeroLeggedOAuthProviderProcessingFilter(oauthConsumerDetailsService, oauthNonceServices, oauthProcessingFilterEntryPoint, oauthAuthenticationHandler, oauthProviderTokenServices, false); 174 | } 175 | 176 | @Override 177 | protected void configure(HttpSecurity http) throws Exception { 178 | http.antMatcher("/oauth/**") 179 | // added filters must be ordered: see http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/apidocs/org/springframework/security/config/annotation/web/HttpSecurityBuilder.html#addFilter%28javax.servlet.Filter%29 180 | .addFilterBefore(zeroLeggedOAuthProviderProcessingFilter, UsernamePasswordAuthenticationFilter.class) 181 | .authorizeRequests().anyRequest().hasRole("OAUTH") 182 | .and().csrf().disable(); // see above 183 | } 184 | } 185 | 186 | @Order(23) // MED 187 | @Configuration 188 | public static class FormLoginConfigurationAdapter extends WebSecurityConfigurerAdapter { 189 | @Override 190 | protected void configure(HttpSecurity http) throws Exception { 191 | http.antMatcher("/form/**").authorizeRequests().anyRequest().authenticated() 192 | .and().formLogin().permitAll().loginPage("/form/login").loginProcessingUrl("/form/login") 193 | .and().logout().logoutUrl("/form/logout").invalidateHttpSession(true).logoutSuccessUrl("/"); 194 | } 195 | } 196 | 197 | @Order(45) // LOW 198 | @Configuration 199 | public static class BasicAuthConfigurationAdapter extends WebSecurityConfigurerAdapter { 200 | @Override 201 | protected void configure(HttpSecurity http) throws Exception { 202 | // basic auth protection for the /basic path 203 | http.antMatcher("/basic/**").authorizeRequests().anyRequest().authenticated() 204 | .and().httpBasic(); 205 | } 206 | } 207 | 208 | @Order(67) // LOWEST 209 | @Configuration 210 | public static class NoAuthConfigurationAdapter extends WebSecurityConfigurerAdapter { 211 | @Override 212 | public void configure(WebSecurity web) throws Exception { 213 | web.ignoring().antMatchers("/console/**"); 214 | } 215 | 216 | @Override 217 | protected void configure(HttpSecurity http) throws Exception { 218 | // this ensures security context info (Principal, sec:authorize, etc.) is accessible on all paths 219 | http.antMatcher("/**").authorizeRequests().anyRequest().permitAll(); 220 | } 221 | } 222 | 223 | // OAuth beans 224 | 225 | @Bean(name = "oauthProviderTokenServices") 226 | public OAuthProviderTokenServices oauthProviderTokenServices() { 227 | // NOTE: we don't use the OAuthProviderTokenServices for 0-legged but it cannot be null 228 | return new InMemoryProviderTokenServices(); 229 | } 230 | 231 | } 232 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /src/test/java/ltistarter/lti/LTITests.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Unicon (R) 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | package ltistarter.lti; 16 | 17 | import ltistarter.BaseApplicationTest; 18 | import ltistarter.model.*; 19 | import ltistarter.repository.*; 20 | import org.junit.Test; 21 | import org.junit.runner.RunWith; 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.mock.web.MockHttpServletRequest; 24 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 25 | import org.springframework.transaction.annotation.Transactional; 26 | 27 | import static org.junit.Assert.*; 28 | 29 | @SuppressWarnings({"UnusedAssignment", "SpringJavaAutowiredMembersInspection", "SpringJavaAutowiringInspection"}) 30 | @RunWith(SpringJUnit4ClassRunner.class) 31 | public class LTITests extends BaseApplicationTest { 32 | 33 | @Autowired 34 | LtiKeyRepository ltiKeyRepository; 35 | @Autowired 36 | LtiUserRepository ltiUserRepository; 37 | @Autowired 38 | LtiContextRepository ltiContextRepository; 39 | @Autowired 40 | LtiLinkRepository ltiLinkRepository; 41 | @Autowired 42 | LtiMembershipRepository ltiMembershipRepository; 43 | @Autowired 44 | LtiServiceRepository ltiServiceRepository; 45 | 46 | @Autowired 47 | LTIDataService ltiDataService; 48 | 49 | @Test 50 | @Transactional 51 | public void testLTIRequest() { 52 | assertNotNull(ltiDataService); 53 | assertNotNull(ltiKeyRepository); 54 | assertNotNull(ltiContextRepository); 55 | assertNotNull(ltiLinkRepository); 56 | assertNotNull(ltiUserRepository); 57 | assertNotNull(ltiMembershipRepository); 58 | MockHttpServletRequest request; 59 | LTIRequest ltiRequest; 60 | 61 | LtiKeyEntity key1 = ltiKeyRepository.save(new LtiKeyEntity("AZkey", "AZsecret")); 62 | LtiKeyEntity key2 = ltiKeyRepository.save(new LtiKeyEntity("key", "secret")); 63 | LtiKeyEntity key3 = ltiKeyRepository.save(new LtiKeyEntity("3key", "secret")); 64 | LtiKeyEntity key4 = ltiKeyRepository.save(new LtiKeyEntity("4key", "secret")); 65 | LtiKeyEntity key5 = ltiKeyRepository.save(new LtiKeyEntity("5key", "secret")); 66 | 67 | LtiUserEntity user1 = ltiUserRepository.save(new LtiUserEntity("azeckoski", null)); 68 | LtiUserEntity user2 = ltiUserRepository.save(new LtiUserEntity("bzeckoski", null)); 69 | LtiUserEntity user3 = ltiUserRepository.save(new LtiUserEntity("czeckoski", null)); 70 | LtiUserEntity user4 = ltiUserRepository.save(new LtiUserEntity("dzeckoski", null)); 71 | 72 | LtiContextEntity context1 = ltiContextRepository.save(new LtiContextEntity("AZcontext", key1, "AZCtitle", null)); 73 | LtiContextEntity context2 = ltiContextRepository.save(new LtiContextEntity("3context", key3, "3Ctitle", null)); 74 | LtiContextEntity context3 = ltiContextRepository.save(new LtiContextEntity("5context", key5, "5Ctitle", null)); 75 | 76 | LtiLinkEntity link1 = ltiLinkRepository.save(new LtiLinkEntity("AZlink", context1, "linkTitle")); 77 | 78 | LtiMembershipEntity member1 = ltiMembershipRepository.save(new LtiMembershipEntity(context1, user1, LtiMembershipEntity.ROLE_STUDENT)); 79 | LtiMembershipEntity member2 = ltiMembershipRepository.save(new LtiMembershipEntity(context1, user2, LtiMembershipEntity.ROLE_STUDENT)); 80 | LtiMembershipEntity member3 = ltiMembershipRepository.save(new LtiMembershipEntity(context1, user3, LtiMembershipEntity.ROLE_INTRUCTOR)); 81 | LtiMembershipEntity member4 = ltiMembershipRepository.save(new LtiMembershipEntity(context2, user1, LtiMembershipEntity.ROLE_STUDENT)); 82 | LtiMembershipEntity member5 = ltiMembershipRepository.save(new LtiMembershipEntity(context2, user3, LtiMembershipEntity.ROLE_INTRUCTOR)); 83 | 84 | LtiServiceEntity service11 = ltiServiceRepository.save(new LtiServiceEntity("grading", key1, "format")); 85 | LtiServiceEntity service12 = ltiServiceRepository.save(new LtiServiceEntity("tracking", key1, "format")); 86 | 87 | request = new MockHttpServletRequest(); // NOT LTI request 88 | try { 89 | ltiRequest = new LTIRequest(request); 90 | fail("Should have died"); 91 | } catch (IllegalStateException e) { 92 | assertNotNull(e.getMessage()); 93 | } 94 | 95 | request = new MockHttpServletRequest(); // LTI request (minimal) 96 | request.setParameter(LTIRequest.LTI_VERSION, LTIRequest.LTI_VERSION_1P0); 97 | request.setParameter(LTIRequest.LTI_MESSAGE_TYPE, LTIRequest.LTI_MESSAGE_TYPE_BASIC); 98 | request.setParameter(LTIRequest.LTI_CONSUMER_KEY, key1.getKeyKey()); 99 | ltiRequest = new LTIRequest(request); 100 | assertFalse(ltiRequest.isComplete()); 101 | assertNotNull(ltiRequest.getLtiVersion()); 102 | assertNotNull(ltiRequest.getLtiMessageType()); 103 | assertNotNull(ltiRequest.getLtiConsumerKey()); 104 | assertNull(ltiRequest.getKey()); // not loaded yet 105 | boolean loaded = ltiDataService.loadLTIDataFromDB(ltiRequest); // load up the data 106 | assertTrue(loaded); 107 | assertNotNull(ltiRequest.getKey()); 108 | assertEquals(key1, ltiRequest.getKey()); 109 | 110 | request = new MockHttpServletRequest(); // LTI request (full) 111 | request.setParameter(LTIRequest.LTI_VERSION, LTIRequest.LTI_VERSION_1P0); 112 | request.setParameter(LTIRequest.LTI_MESSAGE_TYPE, LTIRequest.LTI_MESSAGE_TYPE_BASIC); 113 | request.setParameter(LTIRequest.LTI_CONSUMER_KEY, key1.getKeyKey()); 114 | request.setParameter(LTIRequest.LTI_CONTEXT_ID, context1.getContextKey()); 115 | request.setParameter(LTIRequest.LTI_LINK_ID, link1.getLinkKey()); 116 | request.setParameter(LTIRequest.LTI_USER_ID, user1.getUserKey()); 117 | ltiRequest = new LTIRequest(request, ltiDataService, false); 118 | assertTrue(ltiRequest.isLoaded()); 119 | assertTrue(ltiRequest.isComplete()); 120 | assertNotNull(ltiRequest.getLtiVersion()); 121 | assertNotNull(ltiRequest.getLtiMessageType()); 122 | assertNotNull(ltiRequest.getLtiConsumerKey()); 123 | assertNotNull(ltiRequest.getKey()); 124 | assertEquals(key1, ltiRequest.getKey()); 125 | assertNotNull(ltiRequest.getContext()); 126 | assertNotNull(ltiRequest.getLink()); 127 | assertNotNull(ltiRequest.getLtiUserId()); 128 | assertNotNull(ltiRequest.getMembership()); 129 | assertNull(ltiRequest.getService()); 130 | assertNull(ltiRequest.getResult()); 131 | 132 | request = new MockHttpServletRequest(); // LTI request (gaps) 133 | request.setParameter(LTIRequest.LTI_VERSION, LTIRequest.LTI_VERSION_1P0); 134 | request.setParameter(LTIRequest.LTI_MESSAGE_TYPE, LTIRequest.LTI_MESSAGE_TYPE_BASIC); 135 | request.setParameter(LTIRequest.LTI_CONSUMER_KEY, key1.getKeyKey()); 136 | request.setParameter(LTIRequest.LTI_CONTEXT_ID, context1.getContextKey()); 137 | request.setParameter(LTIRequest.LTI_LINK_ID, "invalid_link"); 138 | request.setParameter(LTIRequest.LTI_USER_ID, user1.getUserKey()); 139 | request.setParameter(LTIRequest.LTI_SOURCEDID, "invalid_sourcedid"); 140 | request.setParameter(LTIRequest.LTI_SERVICE, service11.getServiceKey()); 141 | ltiRequest = new LTIRequest(request, ltiDataService, false); 142 | assertTrue(ltiRequest.isLoaded()); 143 | assertFalse(ltiRequest.isComplete()); // missing the link 144 | assertFalse(ltiRequest.isUpdated()); 145 | assertNotNull(ltiRequest.getLtiVersion()); 146 | assertNotNull(ltiRequest.getLtiMessageType()); 147 | assertNotNull(ltiRequest.getLtiConsumerKey()); 148 | assertNotNull(ltiRequest.getKey()); 149 | assertNotNull(ltiRequest.getContext()); 150 | assertNull(ltiRequest.getLink()); 151 | assertNotNull(ltiRequest.getLtiUserId()); 152 | assertNotNull(ltiRequest.getMembership()); 153 | assertNull(ltiRequest.getResult()); 154 | assertNotNull(ltiRequest.getService()); 155 | 156 | // testing updating existing data 157 | request = new MockHttpServletRequest(); // LTI request (gaps) 158 | request.setParameter(LTIRequest.LTI_VERSION, LTIRequest.LTI_VERSION_1P0); 159 | request.setParameter(LTIRequest.LTI_MESSAGE_TYPE, LTIRequest.LTI_MESSAGE_TYPE_BASIC); 160 | request.setParameter(LTIRequest.LTI_CONSUMER_KEY, key1.getKeyKey()); 161 | request.setParameter(LTIRequest.LTI_CONTEXT_ID, context1.getContextKey()); 162 | request.setParameter(LTIRequest.LTI_CONTEXT_TITLE, "AZ context 1"); 163 | request.setParameter(LTIRequest.LTI_LINK_ID, link1.getLinkKey()); 164 | request.setParameter(LTIRequest.LTI_LINK_TITLE, "AZ link 1"); 165 | request.setParameter(LTIRequest.LTI_USER_ID, user1.getUserKey()); 166 | request.setParameter(LTIRequest.LTI_USER_NAME_FULL, "Aaron Zeckoski"); 167 | request.setParameter(LTIRequest.LTI_USER_EMAIL, "azeckoski@fake.email.com"); 168 | request.setParameter(LTIRequest.LTI_USER_ROLES, "Administrator,Instructor,Learner"); 169 | request.setParameter(LTIRequest.LTI_SOURCEDID, "new_sourcedid_AZ"); 170 | request.setParameter(LTIRequest.LTI_SERVICE, service11.getServiceKey()); 171 | ltiRequest = new LTIRequest(request, ltiDataService, true); 172 | assertTrue(ltiRequest.isLoaded()); 173 | assertTrue(ltiRequest.isComplete()); 174 | assertTrue(ltiRequest.isUpdated()); 175 | assertEquals(2, ltiRequest.getUserRoleNumber()); 176 | assertNotNull(ltiRequest.getLtiVersion()); 177 | assertNotNull(ltiRequest.getLtiMessageType()); 178 | assertNotNull(ltiRequest.getLtiConsumerKey()); 179 | assertNotNull(ltiRequest.getKey()); 180 | assertNotNull(ltiRequest.getContext()); 181 | assertNotNull(ltiRequest.getLink()); 182 | assertNotNull(ltiRequest.getUser()); 183 | assertNotNull(ltiRequest.getMembership()); 184 | assertNotNull(ltiRequest.getResult()); 185 | assertNotNull(ltiRequest.getService()); 186 | 187 | // testing inserting all new data (except key of course) 188 | request = new MockHttpServletRequest(); // LTI request (gaps) 189 | request.setParameter(LTIRequest.LTI_VERSION, LTIRequest.LTI_VERSION_1P0); 190 | request.setParameter(LTIRequest.LTI_MESSAGE_TYPE, LTIRequest.LTI_MESSAGE_TYPE_BASIC); 191 | request.setParameter(LTIRequest.LTI_CONSUMER_KEY, key5.getKeyKey()); 192 | request.setParameter(LTIRequest.LTI_CONTEXT_ID, "context 5555"); 193 | request.setParameter(LTIRequest.LTI_CONTEXT_TITLE, "AZ context 5555"); 194 | request.setParameter(LTIRequest.LTI_LINK_ID, "link 5555"); 195 | request.setParameter(LTIRequest.LTI_LINK_TITLE, "AZ link 5555"); 196 | request.setParameter(LTIRequest.LTI_USER_ID, "rzeckoski"); 197 | request.setParameter(LTIRequest.LTI_USER_NAME_FULL, "Rebecca Zeckoski"); 198 | request.setParameter(LTIRequest.LTI_USER_EMAIL, "rzeckoski@fake.email.com"); 199 | request.setParameter(LTIRequest.LTI_USER_ROLES, "Mentor/Advisor,Instructor/GuestInstructor,TeachingAssistant/TeachingAssistant"); 200 | request.setParameter(LTIRequest.LTI_SOURCEDID, "RZ_new_sourcedid"); 201 | request.setParameter(LTIRequest.LTI_SERVICE, "RZ_grading"); 202 | ltiRequest = new LTIRequest(request, ltiDataService, true); 203 | assertTrue(ltiRequest.isLoaded()); 204 | assertTrue(ltiRequest.isComplete()); 205 | assertTrue(ltiRequest.isUpdated()); 206 | assertNotNull(ltiRequest.getLtiVersion()); 207 | assertNotNull(ltiRequest.getLtiMessageType()); 208 | assertNotNull(ltiRequest.getLtiConsumerKey()); 209 | assertNotNull(ltiRequest.getKey()); 210 | assertNotNull(ltiRequest.getContext()); 211 | assertNotNull(ltiRequest.getLink()); 212 | assertNotNull(ltiRequest.getUser()); 213 | assertNotNull(ltiRequest.getMembership()); 214 | assertNotNull(ltiRequest.getResult()); 215 | assertNotNull(ltiRequest.getService()); 216 | } 217 | 218 | } --------------------------------------------------------------------------------