├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── github │ │ └── pires │ │ └── example │ │ ├── Application.java │ │ ├── ApplicationExceptionHandler.java │ │ ├── OrientDbConfiguration.java │ │ ├── ShiroConfiguration.java │ │ ├── model │ │ ├── Permission.java │ │ ├── Role.java │ │ └── User.java │ │ ├── repository │ │ ├── PermissionRepository.java │ │ ├── RoleRepository.java │ │ └── UserRepository.java │ │ ├── rest │ │ ├── EmailAlreadyInUseException.java │ │ └── UserController.java │ │ └── shiro │ │ ├── HazelcastSessionDao.java │ │ ├── OrientDbRealm.java │ │ └── SessionAttributePredicate.java └── resources │ ├── application.yml │ └── logback.xml └── test └── java └── com └── github └── pires └── example └── rest └── UserControllerTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | build 3 | test-output 4 | gen 5 | dependency-reduced-pom.xml 6 | 7 | # Idea 8 | *.iml 9 | .idea 10 | 11 | # Eclipse 12 | .settings 13 | .classpath 14 | .project 15 | 16 | #Temp Files 17 | *~ -------------------------------------------------------------------------------- /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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This sample project is comprehended by the following: 2 | * Spring Boot REST controller 3 | * OrientDB (2.0.13) remote object persistence by means of Spring Data 4 | * Apache Shiro (1.2.4) session-management with OrientDB-based authorizing realm 5 | * Hazelcast (3.5.1) powered session distributed persistence 6 | 7 | # Pre-requisites 8 | 9 | * JDK 8 10 | * Maven 3.2.3 or newer 11 | 12 | # Spring Data hack 13 | 14 | We need ```spring-data-orientdb```for Spring Data OrientDB support. 15 | We'll be checking out a commit known to be working at the time of this writing. 16 | 17 | ``` 18 | git clone git@github.com:orientechnologies/spring-data-orientdb.git 19 | cd spring-data-orientdb 20 | git checkout 6337a3e 21 | mvn clean install 22 | ``` 23 | 24 | # Run 25 | 26 | ``` 27 | mvn clean package spring-boot:run 28 | ``` 29 | 30 | # Testing 31 | 32 | ## Automatically 33 | 34 | ```mvn clean test``` 35 | 36 | ## Manually 37 | 38 | ### Initialize test scenario 39 | 40 | ``` 41 | curl -i -H "Accept: application/json" -X PUT http://localhost:8080/users 42 | ``` 43 | 44 | ### Access protected method without being authenticated 45 | 46 | ``` 47 | curl -i -H "Accept: application/json" -X GET http://localhost:8080/users 48 | ``` 49 | 50 | You should get a ```401 Unauthorized``` response status. 51 | 52 | ### Log-in 53 | 54 | ``` 55 | curl -i -c cookie.txt -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"username":"pjpires@gmail.com","password":"123qwe"}' http://localhost:8080/users/auth 56 | ``` 57 | 58 | You should get a ```200 OK``` response status and have a valid cookie stored in ```cookie.txt```. 59 | 60 | ### Access protected method again 61 | 62 | ``` 63 | curl -i -b cookie.txt -H "Accept: application/json" -X GET http://localhost:8080/users 64 | ``` 65 | 66 | You should get a ```200 OK``` response status and some JSON representing existing users. 67 | 68 | ### Access another protected method to which you don't have permission 69 | 70 | ``` 71 | curl -i -b cookie.txt -H "Accept: application/json" -X GET http://localhost:8080/users/do_something 72 | ``` 73 | 74 | You should get a ```401 Unauthorized``` response status. 75 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | com.github.pires.example 6 | spring-boot-shiro-orientdb 7 | 0.1-SNAPSHOT 8 | 9 | Spring Boot + Shiro + OrientDB powered REST app 10 | 11 | 12 | org.springframework.boot 13 | spring-boot-starter-parent 14 | 1.2.5.RELEASE 15 | 16 | 17 | 18 | UTF-8 19 | 1.8 20 | ${java.version} 21 | ${java.version} 22 | 23 | 0.10.0-SNAPSHOT 24 | 2.0.13 25 | 1.2.4 26 | 3.5.1 27 | 1.8.6 28 | 6.8.21 29 | 30 | 31 | 32 | 33 | org.slf4j 34 | slf4j-api 35 | 36 | 37 | joda-time 38 | joda-time 39 | 40 | 41 | com.orientechnologies 42 | orientdb-object 43 | ${orientdb.version} 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-orientdb-autoconfigure 48 | ${spring.data.orientdb.version} 49 | 50 | 51 | org.springframework.data 52 | spring-data-orientdb-object 53 | ${spring.data.orientdb.version} 54 | 55 | 56 | org.springframework.boot 57 | spring-boot-starter-web 58 | 59 | 60 | org.apache.shiro 61 | shiro-spring 62 | ${shiro.version} 63 | 64 | 65 | org.apache.shiro 66 | shiro-aspectj 67 | ${shiro.version} 68 | provided 69 | 70 | 71 | com.hazelcast 72 | hazelcast 73 | ${hazelcast.version} 74 | 75 | 76 | org.springframework.boot 77 | spring-boot-starter-test 78 | test 79 | 80 | 81 | org.testng 82 | testng 83 | ${testng.version} 84 | test 85 | 86 | 87 | 88 | 89 | 90 | 91 | org.codehaus.mojo 92 | aspectj-maven-plugin 93 | 1.7 94 | 95 | ${java.version} 96 | ${java.version} 97 | ${java.version} 98 | 99 | 100 | org.apache.shiro 101 | shiro-aspectj 102 | 103 | 104 | 105 | 106 | 107 | org.aspectj 108 | aspectjrt 109 | ${aspectj.version} 110 | 111 | 112 | org.aspectj 113 | aspectjtools 114 | ${aspectj.version} 115 | 116 | 117 | 118 | 119 | 120 | compile 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/Application.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example; 2 | 3 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 4 | import org.springframework.boot.builder.SpringApplicationBuilder; 5 | import org.springframework.context.annotation.ComponentScan; 6 | 7 | @EnableAutoConfiguration 8 | @ComponentScan 9 | public class Application { 10 | 11 | public static void main(String... args) { 12 | new SpringApplicationBuilder() 13 | .sources(Application.class) 14 | .showBanner(false) 15 | .run(args); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/ApplicationExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example; 2 | 3 | import org.apache.shiro.authc.AuthenticationException; 4 | import org.apache.shiro.authc.IncorrectCredentialsException; 5 | import org.apache.shiro.authc.UnknownAccountException; 6 | import org.apache.shiro.authz.UnauthenticatedException; 7 | import org.apache.shiro.authz.UnauthorizedException; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.web.bind.annotation.ControllerAdvice; 10 | import org.springframework.web.bind.annotation.ExceptionHandler; 11 | import org.springframework.web.bind.annotation.ResponseStatus; 12 | 13 | /** 14 | * TODO add description 15 | */ 16 | @ControllerAdvice 17 | public class ApplicationExceptionHandler { 18 | 19 | @ResponseStatus(HttpStatus.UNAUTHORIZED) 20 | @ExceptionHandler( 21 | {AuthenticationException.class, UnknownAccountException.class, 22 | UnauthenticatedException.class, IncorrectCredentialsException.class, UnauthorizedException.class}) 23 | public void unauthorized() { 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/OrientDbConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.orient.commons.repository.config.EnableOrientRepositories; 6 | import org.springframework.data.orient.object.OrientObjectDatabaseFactory; 7 | import org.springframework.data.orient.object.repository.support.OrientObjectRepositoryFactoryBean; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | import javax.annotation.PostConstruct; 11 | 12 | @Configuration 13 | @EnableOrientRepositories(basePackages = "com.github.pires.example.repository", repositoryFactoryBeanClass = OrientObjectRepositoryFactoryBean.class) 14 | public class OrientDbConfiguration { 15 | 16 | @Autowired 17 | private OrientObjectDatabaseFactory factory; 18 | 19 | @PostConstruct 20 | @Transactional 21 | public void registerEntities() { 22 | factory.db().getEntityManager().registerEntityClasses("com.github.pires.example.model"); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/ShiroConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example; 2 | 3 | import com.github.pires.example.shiro.HazelcastSessionDao; 4 | import com.github.pires.example.shiro.OrientDbRealm; 5 | import org.apache.shiro.authc.credential.DefaultPasswordService; 6 | import org.apache.shiro.authc.credential.PasswordMatcher; 7 | import org.apache.shiro.session.mgt.eis.SessionDAO; 8 | import org.apache.shiro.spring.LifecycleBeanPostProcessor; 9 | import org.apache.shiro.spring.web.ShiroFilterFactoryBean; 10 | import org.apache.shiro.web.mgt.DefaultWebSecurityManager; 11 | import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.context.annotation.Configuration; 14 | import org.springframework.context.annotation.DependsOn; 15 | 16 | /** 17 | * TODO add description 18 | */ 19 | @Configuration 20 | public class ShiroConfiguration { 21 | 22 | @Bean 23 | public ShiroFilterFactoryBean shiroFilter() { 24 | ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean(); 25 | factoryBean.setSecurityManager(securityManager()); 26 | return factoryBean; 27 | } 28 | 29 | @Bean(name = "securityManager") 30 | public DefaultWebSecurityManager securityManager() { 31 | final DefaultWebSecurityManager securityManager 32 | = new DefaultWebSecurityManager(); 33 | securityManager.setRealm(realm()); 34 | securityManager.setSessionManager(sessionManager()); 35 | return securityManager; 36 | } 37 | 38 | @Bean 39 | public DefaultWebSessionManager sessionManager() { 40 | final DefaultWebSessionManager sessionManager 41 | = new DefaultWebSessionManager(); 42 | sessionManager.setSessionDAO(sessionDao()); 43 | sessionManager.setGlobalSessionTimeout(43200000); // 12 hours 44 | return sessionManager; 45 | } 46 | 47 | @Bean 48 | public SessionDAO sessionDao() { 49 | return new HazelcastSessionDao(); 50 | } 51 | 52 | @Bean(name = "realm") 53 | @DependsOn("lifecycleBeanPostProcessor") 54 | public OrientDbRealm realm() { 55 | final OrientDbRealm realm = new OrientDbRealm(); 56 | realm.setCredentialsMatcher(credentialsMatcher()); 57 | return realm; 58 | } 59 | 60 | @Bean(name = "credentialsMatcher") 61 | public PasswordMatcher credentialsMatcher() { 62 | final PasswordMatcher credentialsMatcher = new PasswordMatcher(); 63 | credentialsMatcher.setPasswordService(passwordService()); 64 | return credentialsMatcher; 65 | } 66 | 67 | @Bean(name = "passwordService") 68 | public DefaultPasswordService passwordService() { 69 | return new DefaultPasswordService(); 70 | } 71 | 72 | @Bean 73 | public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { 74 | return new LifecycleBeanPostProcessor(); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/model/Permission.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 5 | 6 | import javax.persistence.Id; 7 | import javax.persistence.Version; 8 | 9 | @JsonIgnoreProperties(value = {"handler"}) 10 | public class Permission { 11 | 12 | @Id 13 | private String id; 14 | @Version 15 | @JsonIgnore 16 | private Long version; 17 | private String name; 18 | private String description; 19 | 20 | public String getId() { 21 | return id; 22 | } 23 | 24 | public void setId(String id) { 25 | this.id = id; 26 | } 27 | 28 | public Long getVersion() { 29 | return version; 30 | } 31 | 32 | public void setVersion(Long version) { 33 | this.version = version; 34 | } 35 | 36 | public String getName() { 37 | return name; 38 | } 39 | 40 | public void setName(String name) { 41 | this.name = name; 42 | } 43 | 44 | public String getDescription() { 45 | return description; 46 | } 47 | 48 | public void setDescription(String description) { 49 | this.description = description; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import javax.persistence.Id; 9 | import javax.persistence.ManyToMany; 10 | import javax.persistence.Version; 11 | 12 | @JsonIgnoreProperties(value = {"handler"}) 13 | public class Role { 14 | 15 | @Id 16 | private String id; 17 | @Version 18 | @JsonIgnore 19 | private Long version; 20 | private String name; 21 | private String description; 22 | @ManyToMany 23 | private List permissions; 24 | 25 | public String getId() { 26 | return id; 27 | } 28 | 29 | public void setId(String id) { 30 | this.id = id; 31 | } 32 | 33 | public Long getVersion() { 34 | return version; 35 | } 36 | 37 | public void setVersion(Long version) { 38 | this.version = version; 39 | } 40 | 41 | public String getName() { 42 | return name; 43 | } 44 | 45 | public void setName(String name) { 46 | this.name = name; 47 | } 48 | 49 | public String getDescription() { 50 | return description; 51 | } 52 | 53 | public void setDescription(String description) { 54 | this.description = description; 55 | } 56 | 57 | public List getPermissions() { 58 | if (permissions == null) 59 | this.permissions = new ArrayList<>(); 60 | return permissions; 61 | } 62 | 63 | public void setPermissions(List permissions) { 64 | this.permissions = permissions; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/model/User.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import javax.persistence.Id; 9 | import javax.persistence.OneToMany; 10 | import javax.persistence.Version; 11 | 12 | @JsonIgnoreProperties(value = {"handler"}) 13 | public class User { 14 | 15 | @Id 16 | private String id; 17 | @Version 18 | @JsonIgnore 19 | private Long version; 20 | private Long created; 21 | private String email; 22 | private String name; 23 | private Boolean active; 24 | private String password; 25 | @OneToMany 26 | private List roles; 27 | 28 | public String getId() { 29 | return id; 30 | } 31 | 32 | public void setId(String id) { 33 | this.id = id; 34 | } 35 | 36 | public Long getVersion() { 37 | return version; 38 | } 39 | 40 | public void setVersion(Long version) { 41 | this.version = version; 42 | } 43 | 44 | public Long getCreated() { 45 | return created; 46 | } 47 | 48 | public void setCreated(Long created) { 49 | this.created = created; 50 | } 51 | 52 | public String getEmail() { 53 | return email; 54 | } 55 | 56 | public void setEmail(String email) { 57 | this.email = email; 58 | } 59 | 60 | public String getName() { 61 | return name; 62 | } 63 | 64 | public void setName(String name) { 65 | this.name = name; 66 | } 67 | 68 | public Boolean getActive() { 69 | return active; 70 | } 71 | 72 | public void setActive(Boolean active) { 73 | this.active = active; 74 | } 75 | 76 | public String getPassword() { 77 | return password; 78 | } 79 | 80 | public void setPassword(String password) { 81 | this.password = password; 82 | } 83 | 84 | public List getRoles() { 85 | if (roles == null) { 86 | this.roles = new ArrayList<>(); 87 | } 88 | return roles; 89 | } 90 | 91 | public void setRoles(List roles) { 92 | this.roles = roles; 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/repository/PermissionRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example.repository; 2 | 3 | import com.github.pires.example.model.Permission; 4 | import org.springframework.data.orient.object.repository.OrientObjectRepository; 5 | 6 | /** 7 | * DAO for {@link Permission}. 8 | */ 9 | public interface PermissionRepository extends OrientObjectRepository { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/repository/RoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example.repository; 2 | 3 | import com.github.pires.example.model.Role; 4 | import org.springframework.data.orient.object.repository.OrientObjectRepository; 5 | 6 | /** 7 | * DAO for {@link Role}. 8 | */ 9 | public interface RoleRepository extends OrientObjectRepository { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example.repository; 2 | 3 | import com.github.pires.example.model.User; 4 | import org.springframework.data.orient.object.repository.OrientObjectRepository; 5 | 6 | /** 7 | * DAO for {@link User}. 8 | */ 9 | public interface UserRepository extends OrientObjectRepository { 10 | 11 | User findByEmail(String email); 12 | 13 | User findByEmailAndActive(String email, boolean active); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/rest/EmailAlreadyInUseException.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example.rest; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | @ResponseStatus(HttpStatus.PRECONDITION_FAILED) 7 | public class EmailAlreadyInUseException extends RuntimeException { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/rest/UserController.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example.rest; 2 | 3 | import com.github.pires.example.model.Permission; 4 | import com.github.pires.example.model.Role; 5 | import com.github.pires.example.model.User; 6 | import com.github.pires.example.repository.PermissionRepository; 7 | import com.github.pires.example.repository.RoleRepository; 8 | import com.github.pires.example.repository.UserRepository; 9 | 10 | import java.util.List; 11 | 12 | import org.apache.shiro.SecurityUtils; 13 | import org.apache.shiro.authc.UsernamePasswordToken; 14 | import org.apache.shiro.authc.credential.DefaultPasswordService; 15 | import org.apache.shiro.authz.annotation.RequiresAuthentication; 16 | import org.apache.shiro.authz.annotation.RequiresRoles; 17 | import org.apache.shiro.subject.Subject; 18 | import org.slf4j.Logger; 19 | import org.slf4j.LoggerFactory; 20 | import org.springframework.beans.factory.annotation.Autowired; 21 | import org.springframework.web.bind.annotation.RequestBody; 22 | import org.springframework.web.bind.annotation.RequestMapping; 23 | 24 | import static org.springframework.web.bind.annotation.RequestMethod.GET; 25 | import static org.springframework.web.bind.annotation.RequestMethod.POST; 26 | import static org.springframework.web.bind.annotation.RequestMethod.PUT; 27 | 28 | import org.springframework.web.bind.annotation.RestController; 29 | 30 | /** 31 | * TODO add description 32 | */ 33 | @RestController 34 | @RequestMapping("/users") 35 | public class UserController { 36 | 37 | private static final Logger log = LoggerFactory. 38 | getLogger(UserController.class); 39 | 40 | @Autowired 41 | private DefaultPasswordService passwordService; 42 | 43 | @Autowired 44 | private UserRepository userRepo; 45 | 46 | @Autowired 47 | private RoleRepository roleRepo; 48 | 49 | @Autowired 50 | private PermissionRepository permissionRepo; 51 | 52 | @RequestMapping(value = "/auth", method = POST) 53 | public void authenticate(@RequestBody final UsernamePasswordToken credentials) { 54 | log.info("Authenticating {}", credentials.getUsername()); 55 | final Subject subject = SecurityUtils.getSubject(); 56 | subject.login(credentials); 57 | // set attribute that will allow session querying 58 | subject.getSession().setAttribute("email", credentials.getUsername()); 59 | } 60 | 61 | @RequestMapping(method = GET) 62 | @RequiresAuthentication 63 | @RequiresRoles("ADMIN") 64 | public List getAll() { 65 | return userRepo.findAll(); 66 | } 67 | 68 | @RequestMapping(value = "do_something", method = GET) 69 | @RequiresAuthentication 70 | @RequiresRoles("DO_SOMETHING") 71 | public List dontHavePermission() { 72 | return userRepo.findAll(); 73 | } 74 | 75 | @RequestMapping(method = PUT) 76 | public void initScenario() { 77 | log.info("Initializing scenario.."); 78 | // clean-up users, roles and permissions 79 | userRepo.deleteAll(); 80 | roleRepo.deleteAll(); 81 | permissionRepo.deleteAll(); 82 | // define permissions 83 | final Permission p1 = new Permission(); 84 | p1.setName("VIEW_ALL_USERS"); 85 | permissionRepo.save(p1); 86 | final Permission p2 = new Permission(); 87 | p2.setName("DO_SOMETHING"); 88 | permissionRepo.save(p2); 89 | // define roles 90 | final Role roleAdmin = new Role(); 91 | roleAdmin.setName("ADMIN"); 92 | roleAdmin.getPermissions().add(p1); 93 | roleRepo.save(roleAdmin); 94 | // define user 95 | final User user = new User(); 96 | user.setActive(true); 97 | user.setCreated(System.currentTimeMillis()); 98 | user.setEmail("pjpires@gmail.com"); 99 | user.setName("Paulo Pires"); 100 | user.setPassword(passwordService.encryptPassword("123qwe")); 101 | user.getRoles().add(roleAdmin); 102 | userRepo.save(user); 103 | log.info("Scenario initiated."); 104 | } 105 | 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/shiro/HazelcastSessionDao.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example.shiro; 2 | 3 | import com.hazelcast.config.Config; 4 | import com.hazelcast.config.GroupConfig; 5 | import com.hazelcast.config.JoinConfig; 6 | import com.hazelcast.config.MulticastConfig; 7 | import com.hazelcast.config.NetworkConfig; 8 | import com.hazelcast.config.SSLConfig; 9 | import com.hazelcast.config.TcpIpConfig; 10 | import com.hazelcast.core.Hazelcast; 11 | import com.hazelcast.core.HazelcastInstance; 12 | import com.hazelcast.core.IMap; 13 | 14 | import java.io.Serializable; 15 | import java.util.Collection; 16 | import java.util.UUID; 17 | 18 | import org.apache.shiro.session.Session; 19 | import org.apache.shiro.session.UnknownSessionException; 20 | import org.apache.shiro.session.mgt.eis.AbstractSessionDAO; 21 | import org.slf4j.Logger; 22 | import org.slf4j.LoggerFactory; 23 | 24 | /** 25 | * Data Access Object for Shiro {@link Session} persistence in Hazelcast. 26 | */ 27 | public class HazelcastSessionDao extends AbstractSessionDAO { 28 | 29 | private static final Logger log = LoggerFactory 30 | .getLogger(HazelcastSessionDao.class); 31 | private static final String HC_MAP = "sessions"; 32 | private static final String HC_GROUP_NAME = "hc"; 33 | private static final String HC_GROUP_PASSWORD = "oursessionssecret"; 34 | private static final int HC_PORT = 5701; 35 | private static final String HC_MULTICAST_GROUP = "224.2.2.3"; 36 | private static final int HC_MULTICAST_PORT = 54327; 37 | private String hcInstanceName = UUID.randomUUID().toString(); 38 | private IMap map; 39 | 40 | public HazelcastSessionDao() { 41 | log.info("Initializing Hazelcast Shiro session persistence.."); 42 | 43 | // configure Hazelcast instance 44 | final Config cfg = new Config(); 45 | cfg.setInstanceName(hcInstanceName); 46 | // group configuration 47 | cfg.setGroupConfig(new GroupConfig(HC_GROUP_NAME, HC_GROUP_PASSWORD)); 48 | // network configuration initialization 49 | final NetworkConfig netCfg = new NetworkConfig(); 50 | netCfg.setPortAutoIncrement(true); 51 | netCfg.setPort(HC_PORT); 52 | // multicast 53 | final MulticastConfig mcCfg = new MulticastConfig(); 54 | mcCfg.setEnabled(false); 55 | mcCfg.setMulticastGroup(HC_MULTICAST_GROUP); 56 | mcCfg.setMulticastPort(HC_MULTICAST_PORT); 57 | // tcp 58 | final TcpIpConfig tcpCfg = new TcpIpConfig(); 59 | tcpCfg.addMember("127.0.0.1"); 60 | tcpCfg.setEnabled(false); 61 | // network join configuration 62 | final JoinConfig joinCfg = new JoinConfig(); 63 | joinCfg.setMulticastConfig(mcCfg); 64 | joinCfg.setTcpIpConfig(tcpCfg); 65 | netCfg.setJoin(joinCfg); 66 | // ssl 67 | netCfg.setSSLConfig(new SSLConfig().setEnabled(false)); 68 | 69 | // get map 70 | map = Hazelcast.newHazelcastInstance(cfg).getMap(HC_MAP); 71 | log.info("Hazelcast Shiro session persistence initialized."); 72 | } 73 | 74 | @Override 75 | protected Serializable doCreate(Session session) { 76 | final Serializable sessionId = generateSessionId(session); 77 | log.debug("Creating a new session identified by[{}]", sessionId); 78 | assignSessionId(session, sessionId); 79 | map.put(session.getId(), session); 80 | 81 | return sessionId; 82 | } 83 | 84 | @Override 85 | protected Session doReadSession(Serializable sessionId) { 86 | log.debug("Reading a session identified by[{}]", sessionId); 87 | return map.get(sessionId); 88 | } 89 | 90 | @Override 91 | public void update(Session session) throws UnknownSessionException { 92 | log.debug("Updating a session identified by[{}]", session.getId()); 93 | map.replace(session.getId(), session); 94 | } 95 | 96 | @Override 97 | public void delete(Session session) { 98 | log.debug("Deleting a session identified by[{}]", session.getId()); 99 | map.remove(session.getId()); 100 | } 101 | 102 | @Override 103 | public Collection getActiveSessions() { 104 | return map.values(); 105 | } 106 | 107 | /** 108 | * Retrieves a collection of sessions related to a user. 109 | *

110 | * @param email the authentication identifier to look sessions for. 111 | * @return a collection of sessions. 112 | */ 113 | public Collection getSessionsForAuthenticationEntity( 114 | final String email) { 115 | log.debug("Looking up for sessions related to [{}]", email); 116 | final SessionAttributePredicate predicate 117 | = new SessionAttributePredicate<>("email", email); 118 | return map.values(predicate); 119 | } 120 | 121 | /** 122 | * Destroys currently allocated instance. 123 | */ 124 | public void destroy() { 125 | log.info("Shutting down Hazelcast instance [{}]..", hcInstanceName); 126 | final HazelcastInstance instance = Hazelcast.getHazelcastInstanceByName( 127 | hcInstanceName); 128 | if (instance != null) { 129 | instance.shutdown(); 130 | } 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/shiro/OrientDbRealm.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example.shiro; 2 | 3 | import com.github.pires.example.model.Permission; 4 | import com.github.pires.example.model.Role; 5 | import com.github.pires.example.model.User; 6 | import com.github.pires.example.repository.UserRepository; 7 | 8 | import java.util.LinkedHashSet; 9 | import java.util.Set; 10 | 11 | import org.apache.shiro.authc.AuthenticationException; 12 | import org.apache.shiro.authc.AuthenticationInfo; 13 | import org.apache.shiro.authc.AuthenticationToken; 14 | import org.apache.shiro.authc.SimpleAuthenticationInfo; 15 | import org.apache.shiro.authc.UnknownAccountException; 16 | import org.apache.shiro.authc.UsernamePasswordToken; 17 | import org.apache.shiro.authz.AuthorizationInfo; 18 | import org.apache.shiro.authz.SimpleAuthorizationInfo; 19 | import org.apache.shiro.realm.AuthorizingRealm; 20 | import org.apache.shiro.subject.PrincipalCollection; 21 | import org.apache.shiro.util.ByteSource; 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.stereotype.Component; 24 | 25 | /** 26 | * Shiro authentication & authorization realm that relies on OrientDB as 27 | * datastore. 28 | */ 29 | @Component 30 | public class OrientDbRealm extends AuthorizingRealm { 31 | 32 | @Autowired 33 | private UserRepository userRepository; 34 | 35 | @Override 36 | protected AuthenticationInfo doGetAuthenticationInfo( 37 | final AuthenticationToken token) 38 | throws AuthenticationException { 39 | final UsernamePasswordToken credentials = (UsernamePasswordToken) token; 40 | final String email = credentials.getUsername(); 41 | if (email == null) { 42 | throw new UnknownAccountException("Email not provided"); 43 | } 44 | final User user = userRepository.findByEmailAndActive(email, true); 45 | if (user == null) { 46 | throw new UnknownAccountException("Account does not exist"); 47 | } 48 | return new SimpleAuthenticationInfo(email, user.getPassword().toCharArray(), 49 | ByteSource.Util.bytes(email), getName()); 50 | } 51 | 52 | @Override 53 | protected AuthorizationInfo doGetAuthorizationInfo( 54 | final PrincipalCollection principals) { 55 | // retrieve role names and permission names 56 | final String email = (String) principals.getPrimaryPrincipal(); 57 | final User user = userRepository.findByEmailAndActive(email, true); 58 | if (user == null) { 59 | throw new UnknownAccountException("Account does not exist"); 60 | } 61 | final int totalRoles = user.getRoles().size(); 62 | final Set roleNames = new LinkedHashSet<>(totalRoles); 63 | final Set permissionNames = new LinkedHashSet<>(); 64 | if (totalRoles > 0) { 65 | for (Role role : user.getRoles()) { 66 | roleNames.add(role.getName()); 67 | for (Permission permission : role.getPermissions()) { 68 | permissionNames.add(permission.getName()); 69 | } 70 | } 71 | } 72 | final SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames); 73 | info.setStringPermissions(permissionNames); 74 | return info; 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/github/pires/example/shiro/SessionAttributePredicate.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example.shiro; 2 | 3 | import com.hazelcast.query.Predicate; 4 | 5 | import java.io.Serializable; 6 | import java.util.Map; 7 | 8 | import org.apache.shiro.session.Session; 9 | 10 | /** 11 | * Hazelcast query predicate for Shiro session attributes. 12 | */ 13 | public class SessionAttributePredicate implements 14 | Predicate { 15 | 16 | private final String attributeName; 17 | private final T attributeValue; 18 | 19 | public SessionAttributePredicate(String attributeName, T attributeValue) { 20 | this.attributeName = attributeName; 21 | this.attributeValue = attributeValue; 22 | } 23 | 24 | public String getAttributeName() { 25 | return attributeName; 26 | } 27 | 28 | public T getAttributeValue() { 29 | return attributeValue; 30 | } 31 | 32 | @Override 33 | public boolean apply(Map.Entry sessionEntry) { 34 | final T attribute = (T) sessionEntry.getValue().getAttribute(attributeName); 35 | return attribute.equals(attributeValue); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring.data.orient: 2 | url: memory:orientdb/test1test 3 | username: admin 4 | password: admin -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/test/java/com/github/pires/example/rest/UserControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.pires.example.rest; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.github.pires.example.Application; 6 | import com.github.pires.example.OrientDbConfiguration; 7 | import com.github.pires.example.ShiroConfiguration; 8 | import com.github.pires.example.model.Permission; 9 | import com.github.pires.example.model.Role; 10 | import com.github.pires.example.model.User; 11 | import com.github.pires.example.repository.PermissionRepository; 12 | import com.github.pires.example.repository.RoleRepository; 13 | import com.github.pires.example.repository.UserRepository; 14 | 15 | import java.util.Arrays; 16 | 17 | import org.apache.shiro.authc.UsernamePasswordToken; 18 | import org.apache.shiro.authc.credential.DefaultPasswordService; 19 | 20 | import static org.hamcrest.CoreMatchers.equalTo; 21 | import static org.hamcrest.MatcherAssert.assertThat; 22 | 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.boot.test.IntegrationTest; 25 | import org.springframework.boot.test.SpringApplicationConfiguration; 26 | import org.springframework.boot.test.TestRestTemplate; 27 | import org.springframework.boot.test.TestRestTemplate.HttpClientOption; 28 | import org.springframework.http.HttpEntity; 29 | import org.springframework.http.HttpHeaders; 30 | import org.springframework.http.HttpMethod; 31 | import org.springframework.http.HttpStatus; 32 | import org.springframework.http.MediaType; 33 | import org.springframework.http.ResponseEntity; 34 | import org.springframework.test.context.TestExecutionListeners; 35 | import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; 36 | import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; 37 | import org.springframework.test.context.web.WebAppConfiguration; 38 | 39 | import static org.testng.AssertJUnit.assertEquals; 40 | 41 | import org.testng.annotations.BeforeClass; 42 | import org.testng.annotations.Test; 43 | 44 | @SpringApplicationConfiguration(classes 45 | = {Application.class, OrientDbConfiguration.class, ShiroConfiguration.class}) 46 | @WebAppConfiguration 47 | @IntegrationTest 48 | @TestExecutionListeners(inheritListeners = false, listeners 49 | = {DependencyInjectionTestExecutionListener.class}) 50 | public class UserControllerTest extends AbstractTestNGSpringContextTests { 51 | 52 | private final String BASE_URL = "http://localhost:8080/users"; 53 | private final String USER_NAME = "Paulo Pires"; 54 | private final String USER_EMAIL = "pjpires@gmail.com"; 55 | private final String USER_PWD = "123qwe"; 56 | @Autowired 57 | private DefaultPasswordService passwordService; 58 | @Autowired 59 | private UserRepository userRepo; 60 | @Autowired 61 | private RoleRepository roleRepo; 62 | @Autowired 63 | private PermissionRepository permissionRepo; 64 | 65 | @BeforeClass 66 | public void setUp() { 67 | // clean-up users, roles and permissions 68 | userRepo.deleteAll(); 69 | roleRepo.deleteAll(); 70 | permissionRepo.deleteAll(); 71 | // define permissions 72 | final Permission p1 = new Permission(); 73 | p1.setName("VIEW_USER_ROLES"); 74 | permissionRepo.save(p1); 75 | // define roles 76 | final Role roleAdmin = new Role(); 77 | roleAdmin.setName("ADMIN"); 78 | roleAdmin.getPermissions().add(p1); 79 | roleRepo.save(roleAdmin); 80 | // define user 81 | final User user = new User(); 82 | user.setActive(true); 83 | user.setCreated(System.currentTimeMillis()); 84 | user.setEmail(USER_EMAIL); 85 | user.setName(USER_NAME); 86 | user.setPassword(passwordService.encryptPassword(USER_PWD)); 87 | user.getRoles().add(roleAdmin); 88 | userRepo.save(user); 89 | } 90 | 91 | @Test 92 | public void test_count() { 93 | assertEquals(1, userRepo.count()); 94 | } 95 | 96 | @Test 97 | public void test_authenticate_success() throws JsonProcessingException { 98 | // authenticate 99 | HttpHeaders headers = new HttpHeaders(); 100 | headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); 101 | headers.setContentType(MediaType.APPLICATION_JSON); 102 | final String json = new ObjectMapper().writeValueAsString( 103 | new UsernamePasswordToken(USER_EMAIL, USER_PWD)); 104 | System.out.println(json); 105 | final ResponseEntity response = new TestRestTemplate( 106 | HttpClientOption.ENABLE_COOKIES).exchange(BASE_URL.concat("/auth"), 107 | HttpMethod.POST, new HttpEntity<>(json, headers), String.class); 108 | assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); 109 | } 110 | 111 | @Test 112 | public void test_authenticate_failure() throws JsonProcessingException { 113 | // authenticate 114 | HttpHeaders headers = new HttpHeaders(); 115 | headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); 116 | headers.setContentType(MediaType.APPLICATION_JSON); 117 | final String json = new ObjectMapper().writeValueAsString( 118 | new UsernamePasswordToken(USER_EMAIL, "wrong password")); 119 | System.out.println(json); 120 | final ResponseEntity response = new TestRestTemplate( 121 | HttpClientOption.ENABLE_COOKIES).exchange(BASE_URL.concat("/auth"), 122 | HttpMethod.POST, new HttpEntity<>(json, headers), String.class); 123 | assertThat(response.getStatusCode(), equalTo(HttpStatus.UNAUTHORIZED)); 124 | } 125 | 126 | } 127 | --------------------------------------------------------------------------------