├── .travis.yml ├── src ├── main │ ├── resources │ │ ├── keystore.jks │ │ ├── application.properties │ │ ├── application-https.properties │ │ └── import.sql │ └── java │ │ └── hello │ │ ├── data │ │ ├── UserRepository.java │ │ ├── Role.java │ │ └── User.java │ │ ├── HomeController.java │ │ ├── Application.java │ │ ├── Greeting.java │ │ ├── WebInitializer.java │ │ ├── UserController.java │ │ ├── GreetingController.java │ │ ├── WebSecurityConfiguration.java │ │ ├── CustomUserDetailsService.java │ │ └── OAuth2ServerConfiguration.java └── test │ └── java │ └── hello │ ├── HomeControllerTest.java │ └── GreetingControllerTest.java ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── ci.sh ├── .gitignore ├── NOTICE ├── pom.xml ├── gradlew.bat ├── README.adoc ├── gradlew └── LICENSE /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - oraclejdk8 5 | - oraclejdk7 6 | -------------------------------------------------------------------------------- /src/main/resources/keystore.jks: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/royclarkson/spring-rest-service-oauth/HEAD/src/main/resources/keystore.jks -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/royclarkson/spring-rest-service-oauth/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /ci.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | cd $(dirname $0) 3 | 4 | set -e 5 | 6 | ./gradlew clean build 7 | rm -rf build 8 | 9 | mvn clean package 10 | rm -rf target 11 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.profiles.active=dev 2 | #comment above profile and uncoment line below to operate using https 3 | #spring.profiles.active=https 4 | -------------------------------------------------------------------------------- /src/main/resources/application-https.properties: -------------------------------------------------------------------------------- 1 | # Configure the server to run with SSL/TLS and using HTTPS 2 | server.port = 8443 3 | server.ssl.key-store = classpath:keystore.jks 4 | server.ssl.key-store-password = password 5 | server.ssl.key-password = password -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Oct 28 10:57:05 CDT 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.7-bin.zip 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Operating System Files 2 | 3 | *.DS_Store 4 | Thumbs.db 5 | *.sw? 6 | .#* 7 | *# 8 | *~ 9 | *.sublime-* 10 | 11 | # Build Artifacts 12 | 13 | .gradle/ 14 | build/ 15 | target/ 16 | bin/ 17 | dependency-reduced-pom.xml 18 | 19 | # Eclipse Project Files 20 | 21 | .classpath 22 | .project 23 | .settings/ 24 | 25 | # IntelliJ IDEA Files 26 | 27 | *.iml 28 | *.ipr 29 | *.iws 30 | *.idea -------------------------------------------------------------------------------- /src/main/resources/import.sql: -------------------------------------------------------------------------------- 1 | insert into user(id, name, login, password) values (1,'Roy','roy','spring'); 2 | insert into user(id, name, login, password) values (2,'Craig','craig','spring'); 3 | insert into user(id, name, login, password) values (3,'Greg','greg','spring'); 4 | 5 | insert into role(id, name) values (1,'ROLE_USER'); 6 | insert into role(id, name) values (2,'ROLE_ADMIN'); 7 | insert into role(id, name) values (3,'ROLE_GUEST'); 8 | 9 | insert into user_role(user_id, role_id) values (1,1); 10 | insert into user_role(user_id, role_id) values (1,2); 11 | insert into user_role(user_id, role_id) values (2,1); 12 | insert into user_role(user_id, role_id) values (3,1); 13 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 Roy Clarkson. All Rights Reserved. 2 | 3 | This product is licensed to you under the Apache License, Version 2.0 (the "License"). 4 | You may not use this product except in compliance with the License. 5 | 6 | This product may include a number of subcomponents with separate copyright notices 7 | and license terms. Your use of these subcomponents is subject to the terms and 8 | conditions of the subcomponent's license, as noted in the LICENSE file. 9 | 10 | This software downloads additional open source software components upon install 11 | that are distributed under separate terms and conditions. Please see the license 12 | information provided in the individual software components for more information. 13 | 14 | -------------------------------------------------------------------------------- /src/main/java/hello/data/UserRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2015 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello.data; 18 | 19 | import org.springframework.data.repository.CrudRepository; 20 | 21 | public interface UserRepository extends CrudRepository { 22 | 23 | User findByLogin(String login); 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/hello/HomeController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello; 18 | 19 | import org.springframework.web.bind.annotation.RequestMapping; 20 | import org.springframework.web.bind.annotation.RestController; 21 | 22 | @RestController 23 | public class HomeController { 24 | 25 | @RequestMapping("/") 26 | public String home() { 27 | return "home"; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/hello/Application.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello; 18 | 19 | import org.springframework.boot.SpringApplication; 20 | import org.springframework.boot.autoconfigure.SpringBootApplication; 21 | 22 | @SpringBootApplication 23 | public class Application { 24 | 25 | public static void main(String[] args) { 26 | SpringApplication.run(Application.class, args); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/hello/Greeting.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2015 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello; 18 | 19 | public class Greeting { 20 | 21 | private final long id; 22 | 23 | private final String content; 24 | 25 | public long getId() { 26 | return id; 27 | } 28 | 29 | public String getContent() { 30 | return content; 31 | } 32 | 33 | public Greeting(long id, String content) { 34 | this.id = id; 35 | this.content = content; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/hello/WebInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello; 18 | 19 | import org.springframework.boot.builder.SpringApplicationBuilder; 20 | import org.springframework.boot.context.web.SpringBootServletInitializer; 21 | 22 | public class WebInitializer extends SpringBootServletInitializer { 23 | 24 | @Override 25 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 26 | return application.sources(Application.class); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/hello/UserController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2015 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello; 18 | 19 | import hello.data.User; 20 | import hello.data.UserRepository; 21 | 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.web.bind.annotation.RequestMapping; 24 | import org.springframework.web.bind.annotation.RestController; 25 | 26 | @RestController 27 | public class UserController { 28 | 29 | private final UserRepository userRepository; 30 | 31 | @Autowired 32 | public UserController(UserRepository userRepository) { 33 | this.userRepository = userRepository; 34 | } 35 | 36 | @RequestMapping("/users") 37 | public Iterable getUsers() { 38 | return userRepository.findAll(); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/hello/GreetingController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello; 18 | 19 | import java.util.concurrent.atomic.AtomicLong; 20 | 21 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 22 | import org.springframework.web.bind.annotation.RequestMapping; 23 | import org.springframework.web.bind.annotation.RestController; 24 | 25 | import hello.data.User; 26 | 27 | @RestController 28 | public class GreetingController { 29 | 30 | private static final String template = "Hello, %s!"; 31 | 32 | private final AtomicLong counter = new AtomicLong(); 33 | 34 | @RequestMapping("/greeting") 35 | public Greeting greeting(@AuthenticationPrincipal User user) { 36 | return new Greeting(counter.incrementAndGet(), 37 | String.format(template, user.getName())); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/hello/WebSecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello; 18 | 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | import org.springframework.context.annotation.Bean; 21 | import org.springframework.context.annotation.Configuration; 22 | import org.springframework.security.authentication.AuthenticationManager; 23 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 24 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 25 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 26 | 27 | @Configuration 28 | @EnableWebSecurity 29 | public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { 30 | 31 | @Autowired 32 | private CustomUserDetailsService userDetailsService; 33 | 34 | @Override 35 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 36 | auth.userDetailsService(userDetailsService); 37 | } 38 | 39 | @Override 40 | @Bean 41 | public AuthenticationManager authenticationManagerBean() throws Exception { 42 | return super.authenticationManagerBean(); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/hello/data/Role.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2015 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello.data; 18 | 19 | import java.util.HashSet; 20 | import java.util.Set; 21 | 22 | import javax.persistence.Entity; 23 | import javax.persistence.FetchType; 24 | import javax.persistence.GeneratedValue; 25 | import javax.persistence.GenerationType; 26 | import javax.persistence.Id; 27 | import javax.persistence.ManyToMany; 28 | 29 | import org.hibernate.validator.constraints.NotEmpty; 30 | import org.springframework.security.core.GrantedAuthority; 31 | 32 | import com.fasterxml.jackson.annotation.JsonIgnore; 33 | 34 | @Entity 35 | public class Role implements GrantedAuthority { 36 | 37 | private static final long serialVersionUID = 1L; 38 | 39 | @Id 40 | @GeneratedValue(strategy = GenerationType.AUTO) 41 | private Integer id; 42 | 43 | @NotEmpty 44 | private String name; 45 | 46 | @JsonIgnore 47 | @ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles") 48 | private Set users = new HashSet(); 49 | 50 | @Override 51 | public String getAuthority() { 52 | return name; 53 | } 54 | 55 | public Integer getId() { 56 | return id; 57 | } 58 | 59 | public void setId(Integer id) { 60 | this.id = id; 61 | } 62 | 63 | public String getName() { 64 | return name; 65 | } 66 | 67 | public void setName(String name) { 68 | this.name = name; 69 | } 70 | 71 | public Set getUsers() { 72 | return users; 73 | } 74 | 75 | public void setUsers(Set users) { 76 | this.users = users; 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/test/java/hello/HomeControllerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello; 18 | 19 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 20 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 21 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 22 | 23 | import org.junit.Before; 24 | import org.junit.Test; 25 | import org.junit.runner.RunWith; 26 | import org.mockito.InjectMocks; 27 | import org.mockito.MockitoAnnotations; 28 | import org.springframework.beans.factory.annotation.Autowired; 29 | import org.springframework.boot.test.SpringApplicationConfiguration; 30 | import org.springframework.http.MediaType; 31 | import org.springframework.security.web.FilterChainProxy; 32 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 33 | import org.springframework.test.context.web.WebAppConfiguration; 34 | import org.springframework.test.web.servlet.MockMvc; 35 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 36 | import org.springframework.web.context.WebApplicationContext; 37 | 38 | /** 39 | * @author Roy Clarkson 40 | */ 41 | @RunWith(SpringJUnit4ClassRunner.class) 42 | @WebAppConfiguration 43 | @SpringApplicationConfiguration(classes = Application.class) 44 | public class HomeControllerTest { 45 | 46 | @Autowired 47 | WebApplicationContext context; 48 | 49 | @Autowired 50 | private FilterChainProxy springSecurityFilterChain; 51 | 52 | @InjectMocks 53 | HomeController controller; 54 | 55 | private MockMvc mvc; 56 | 57 | @Before 58 | public void setUp() { 59 | MockitoAnnotations.initMocks(this); 60 | mvc = MockMvcBuilders.webAppContextSetup(context) 61 | .addFilter(springSecurityFilterChain).build(); 62 | } 63 | 64 | @Test 65 | public void home() throws Exception { 66 | // @formatter:off 67 | mvc.perform(get("/") 68 | .accept(MediaType.TEXT_PLAIN)) 69 | .andExpect(status().isOk()) 70 | .andExpect(content().string("home")); 71 | // @formatter:on 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework 7 | spring-rest-service-oauth 8 | 0.1.0 9 | war 10 | 11 | 12 | org.springframework.boot 13 | spring-boot-starter-parent 14 | 1.3.0.RC1 15 | 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-security 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-data-jpa 33 | 34 | 35 | org.springframework.security.oauth 36 | spring-security-oauth2 37 | 38 | 39 | org.hsqldb 40 | hsqldb 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-tomcat 45 | provided 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-test 50 | test 51 | 52 | 53 | com.jayway.jsonpath 54 | json-path 55 | test 56 | 57 | 58 | com.jayway.jsonpath 59 | json-path-assert 60 | test 61 | 62 | 63 | 64 | 65 | 66 | 67 | org.springframework.boot 68 | spring-boot-maven-plugin 69 | 70 | 71 | 72 | 73 | 74 | 75 | spring-releases 76 | https://repo.spring.io/libs-release 77 | 78 | 79 | 80 | 81 | 82 | spring-plugin-releases 83 | https://repo.spring.io/plugins-release 84 | 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /src/main/java/hello/CustomUserDetailsService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2015 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello; 18 | 19 | import java.util.Collection; 20 | 21 | import hello.data.User; 22 | import hello.data.UserRepository; 23 | 24 | import org.springframework.beans.factory.annotation.Autowired; 25 | import org.springframework.security.core.GrantedAuthority; 26 | import org.springframework.security.core.userdetails.UserDetails; 27 | import org.springframework.security.core.userdetails.UserDetailsService; 28 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 29 | import org.springframework.stereotype.Service; 30 | 31 | @Service 32 | public class CustomUserDetailsService implements UserDetailsService { 33 | 34 | private final UserRepository userRepository; 35 | 36 | @Autowired 37 | public CustomUserDetailsService(UserRepository userRepository) { 38 | this.userRepository = userRepository; 39 | } 40 | 41 | @Override 42 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 43 | User user = userRepository.findByLogin(username); 44 | if (user == null) { 45 | throw new UsernameNotFoundException(String.format("User %s does not exist!", username)); 46 | } 47 | return new UserRepositoryUserDetails(user); 48 | } 49 | 50 | private final static class UserRepositoryUserDetails extends User implements UserDetails { 51 | 52 | private static final long serialVersionUID = 1L; 53 | 54 | private UserRepositoryUserDetails(User user) { 55 | super(user); 56 | } 57 | 58 | @Override 59 | public Collection getAuthorities() { 60 | return getRoles(); 61 | } 62 | 63 | @Override 64 | public String getUsername() { 65 | return getLogin(); 66 | } 67 | 68 | @Override 69 | public boolean isAccountNonExpired() { 70 | return true; 71 | } 72 | 73 | @Override 74 | public boolean isAccountNonLocked() { 75 | return true; 76 | } 77 | 78 | @Override 79 | public boolean isCredentialsNonExpired() { 80 | return true; 81 | } 82 | 83 | @Override 84 | public boolean isEnabled() { 85 | return true; 86 | } 87 | 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/hello/data/User.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2015 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello.data; 18 | 19 | import java.util.HashSet; 20 | import java.util.Set; 21 | 22 | import javax.persistence.CascadeType; 23 | import javax.persistence.Column; 24 | import javax.persistence.Entity; 25 | import javax.persistence.FetchType; 26 | import javax.persistence.GeneratedValue; 27 | import javax.persistence.GenerationType; 28 | import javax.persistence.Id; 29 | import javax.persistence.JoinColumn; 30 | import javax.persistence.JoinTable; 31 | import javax.persistence.ManyToMany; 32 | 33 | import org.hibernate.validator.constraints.NotEmpty; 34 | 35 | import com.fasterxml.jackson.annotation.JsonIgnore; 36 | 37 | @Entity 38 | public class User { 39 | 40 | @Id 41 | @GeneratedValue(strategy = GenerationType.AUTO) 42 | private Integer id; 43 | 44 | @NotEmpty 45 | private String name; 46 | 47 | @NotEmpty 48 | @Column(unique = true, nullable = false) 49 | private String login; 50 | 51 | @NotEmpty 52 | private String password; 53 | 54 | @JsonIgnore 55 | @ManyToMany(fetch = FetchType.EAGER) 56 | @JoinTable(name = "user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") }) 57 | private Set roles = new HashSet(); 58 | 59 | public User() { 60 | } 61 | 62 | public User(User user) { 63 | super(); 64 | this.id = user.getId(); 65 | this.name = user.getName(); 66 | this.login = user.getLogin(); 67 | this.password = user.getPassword(); 68 | this.roles = user.getRoles(); 69 | } 70 | 71 | public Integer getId() { 72 | return id; 73 | } 74 | 75 | public void setId(Integer id) { 76 | this.id = id; 77 | } 78 | 79 | public String getName() { 80 | return name; 81 | } 82 | 83 | public void setName(String name) { 84 | this.name = name; 85 | } 86 | 87 | public String getLogin() { 88 | return login; 89 | } 90 | 91 | public void setLogin(String login) { 92 | this.login = login; 93 | } 94 | 95 | public String getPassword() { 96 | return password; 97 | } 98 | 99 | public void setPassword(String password) { 100 | this.password = password; 101 | } 102 | 103 | public Set getRoles() { 104 | return roles; 105 | } 106 | 107 | public void setRoles(Set roles) { 108 | this.roles = roles; 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | = Spring REST Service OAuth 2 | 3 | image::https://travis-ci.org/royclarkson/spring-rest-service-oauth.svg[Build Status, link=https://travis-ci.org/royclarkson/spring-rest-service-oauth/] 4 | 5 | This is a simple REST service that provides a single RESTful endpoint protected by OAuth 2. The REST service is based on the https://spring.io/guides/gs/rest-service/[Building a RESTful Web Service] getting started guide. This project incorporates the new Java-based configuration support, now available in Spring Security OAuth 2.0. Please log any issues or feature requests to the https://github.com/spring-projects/spring-security-oauth/issues[Spring Security OAuth project]. 6 | 7 | 8 | == Spring Projects 9 | 10 | The following Spring projects are used in this sample app: 11 | 12 | * http://projects.spring.io/spring-boot/[Spring Boot] 13 | * http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html[Spring MVC] 14 | * http://projects.spring.io/spring-security/[Spring Security] 15 | * http://projects.spring.io/spring-security-oauth/[Spring Security OAuth] 16 | * http://projects.spring.io/spring-data-jpa/[Spring Data JPA] 17 | 18 | 19 | == Build and Run 20 | 21 | Use Gradle: 22 | 23 | ```sh 24 | ./gradlew clean build bootRun 25 | ``` 26 | 27 | Or Maven: 28 | 29 | ```sh 30 | mvn clean package spring-boot:run 31 | ``` 32 | 33 | == Usage 34 | 35 | Test the `greeting` endpoint: 36 | 37 | ```sh 38 | curl http://localhost:8080/greeting 39 | ``` 40 | 41 | You receive the following JSON response, which indicates you are not authorized to access the resource: 42 | 43 | ```json 44 | { 45 | "error": "unauthorized", 46 | "error_description": "An Authentication object was not found in the SecurityContext" 47 | } 48 | ``` 49 | 50 | In order to access the protected resource, you must first request an access token via the OAuth handshake. Request OAuth authorization: 51 | 52 | ```sh 53 | curl -X POST -vu clientapp:123456 http://localhost:8080/oauth/token -H "Accept: application/json" -d "password=spring&username=roy&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp" 54 | ``` 55 | 56 | A successful authorization results in the following JSON response: 57 | 58 | ```json 59 | { 60 | "access_token": "ff16372e-38a7-4e29-88c2-1fb92897f558", 61 | "token_type": "bearer", 62 | "refresh_token": "f554d386-0b0a-461b-bdb2-292831cecd57", 63 | "expires_in": 43199, 64 | "scope": "read write" 65 | } 66 | ``` 67 | 68 | Use the `access_token` returned in the previous request to make the authorized request to the protected endpoint: 69 | 70 | ```sh 71 | curl http://localhost:8080/greeting -H "Authorization: Bearer ff16372e-38a7-4e29-88c2-1fb92897f558" 72 | ``` 73 | 74 | If the request is successful, you will see the following JSON response: 75 | 76 | ```json 77 | { 78 | "id": 1, 79 | "content": "Hello, Roy!" 80 | } 81 | ``` 82 | 83 | After the specified time period, the `access_token` will expire. Use the `refresh_token` that was returned in the original OAuth authorization to retrieve a new `access_token`: 84 | 85 | ```sh 86 | curl -X POST -vu clientapp:123456 http://localhost:8080/oauth/token -H "Accept: application/json" -d "grant_type=refresh_token&refresh_token=f554d386-0b0a-461b-bdb2-292831cecd57&client_secret=123456&client_id=clientapp" 87 | ``` 88 | 89 | 90 | == SSL 91 | 92 | To configure the project to run on HTTPS as shown in https://spring.io/guides/tutorials/bookmarks/[Building REST services with Spring], enable the `https` profile. You can do this by uncommenting the appropriate line in the application.properties file of this project. This will change the server port to `8443`. Modify the previous requests as in the following command. 93 | 94 | ```sh 95 | curl -X POST -k -vu clientapp:123456 https://localhost:8443/oauth/token -H "Accept: application/json" -d "password=spring&username=roy&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp" 96 | ``` 97 | 98 | The `-k` parameter is necessary to allow connections to SSL sites without valid certificates or the self signed certificate which is created for this project. 99 | 100 | 101 | == Cloud Foundry Demo 102 | 103 | The service is deployed to Pivotal Cloud Foundry and available for testing. Modify the previous commands to point to the following URL: 104 | 105 | ```sh 106 | curl http://rclarkson-restoauth.cfapps.io/greeting 107 | ``` 108 | -------------------------------------------------------------------------------- /src/main/java/hello/OAuth2ServerConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2015 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello; 18 | 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | import org.springframework.beans.factory.annotation.Qualifier; 21 | import org.springframework.context.annotation.Bean; 22 | import org.springframework.context.annotation.Configuration; 23 | import org.springframework.context.annotation.Primary; 24 | import org.springframework.security.authentication.AuthenticationManager; 25 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 26 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 27 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 28 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 29 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 30 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 31 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 32 | import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; 33 | import org.springframework.security.oauth2.provider.token.DefaultTokenServices; 34 | import org.springframework.security.oauth2.provider.token.TokenStore; 35 | import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; 36 | 37 | @Configuration 38 | public class OAuth2ServerConfiguration { 39 | 40 | private static final String RESOURCE_ID = "restservice"; 41 | 42 | @Configuration 43 | @EnableResourceServer 44 | protected static class ResourceServerConfiguration extends 45 | ResourceServerConfigurerAdapter { 46 | 47 | @Override 48 | public void configure(ResourceServerSecurityConfigurer resources) { 49 | // @formatter:off 50 | resources 51 | .resourceId(RESOURCE_ID); 52 | // @formatter:on 53 | } 54 | 55 | @Override 56 | public void configure(HttpSecurity http) throws Exception { 57 | // @formatter:off 58 | http 59 | .authorizeRequests() 60 | .antMatchers("/users").hasRole("ADMIN") 61 | .antMatchers("/greeting").authenticated(); 62 | // @formatter:on 63 | } 64 | 65 | } 66 | 67 | @Configuration 68 | @EnableAuthorizationServer 69 | protected static class AuthorizationServerConfiguration extends 70 | AuthorizationServerConfigurerAdapter { 71 | 72 | private TokenStore tokenStore = new InMemoryTokenStore(); 73 | 74 | @Autowired 75 | @Qualifier("authenticationManagerBean") 76 | private AuthenticationManager authenticationManager; 77 | 78 | @Autowired 79 | private CustomUserDetailsService userDetailsService; 80 | 81 | @Override 82 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) 83 | throws Exception { 84 | // @formatter:off 85 | endpoints 86 | .tokenStore(this.tokenStore) 87 | .authenticationManager(this.authenticationManager) 88 | .userDetailsService(userDetailsService); 89 | // @formatter:on 90 | } 91 | 92 | @Override 93 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 94 | // @formatter:off 95 | clients 96 | .inMemory() 97 | .withClient("clientapp") 98 | .authorizedGrantTypes("password", "refresh_token") 99 | .authorities("USER") 100 | .scopes("read", "write") 101 | .resourceIds(RESOURCE_ID) 102 | .secret("123456"); 103 | // @formatter:on 104 | } 105 | 106 | @Bean 107 | @Primary 108 | public DefaultTokenServices tokenServices() { 109 | DefaultTokenServices tokenServices = new DefaultTokenServices(); 110 | tokenServices.setSupportRefreshToken(true); 111 | tokenServices.setTokenStore(this.tokenStore); 112 | return tokenServices; 113 | } 114 | 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /src/test/java/hello/GreetingControllerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package hello; 18 | 19 | import static org.hamcrest.Matchers.equalTo; 20 | import static org.hamcrest.Matchers.greaterThan; 21 | import static org.hamcrest.Matchers.hasSize; 22 | import static org.hamcrest.Matchers.is; 23 | import static org.hamcrest.Matchers.notNullValue; 24 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 25 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 26 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 27 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 28 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 29 | 30 | import org.junit.Before; 31 | import org.junit.Test; 32 | import org.junit.runner.RunWith; 33 | import org.mockito.InjectMocks; 34 | import org.mockito.MockitoAnnotations; 35 | import org.springframework.beans.factory.annotation.Autowired; 36 | import org.springframework.boot.test.SpringApplicationConfiguration; 37 | import org.springframework.http.MediaType; 38 | import org.springframework.security.web.FilterChainProxy; 39 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 40 | import org.springframework.test.context.web.WebAppConfiguration; 41 | import org.springframework.test.web.servlet.MockMvc; 42 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 43 | import org.springframework.util.Base64Utils; 44 | import org.springframework.web.context.WebApplicationContext; 45 | 46 | /** 47 | * @author Roy Clarkson 48 | */ 49 | @RunWith(SpringJUnit4ClassRunner.class) 50 | @WebAppConfiguration 51 | @SpringApplicationConfiguration(classes = Application.class) 52 | public class GreetingControllerTest { 53 | 54 | @Autowired 55 | WebApplicationContext context; 56 | 57 | @Autowired 58 | private FilterChainProxy springSecurityFilterChain; 59 | 60 | @InjectMocks 61 | GreetingController controller; 62 | 63 | private MockMvc mvc; 64 | 65 | @Before 66 | public void setUp() { 67 | MockitoAnnotations.initMocks(this); 68 | mvc = MockMvcBuilders.webAppContextSetup(context) 69 | .addFilter(springSecurityFilterChain).build(); 70 | } 71 | 72 | @Test 73 | public void greetingUnauthorized() throws Exception { 74 | // @formatter:off 75 | mvc.perform(get("/greeting") 76 | .accept(MediaType.APPLICATION_JSON)) 77 | .andExpect(status().isUnauthorized()) 78 | .andExpect(jsonPath("$.error", is("unauthorized"))); 79 | // @formatter:on 80 | } 81 | 82 | private String getAccessToken(String username, String password) throws Exception { 83 | String authorization = "Basic " 84 | + new String(Base64Utils.encode("clientapp:123456".getBytes())); 85 | String contentType = MediaType.APPLICATION_JSON + ";charset=UTF-8"; 86 | 87 | // @formatter:off 88 | String content = mvc 89 | .perform( 90 | post("/oauth/token") 91 | .header("Authorization", authorization) 92 | .contentType( 93 | MediaType.APPLICATION_FORM_URLENCODED) 94 | .param("username", username) 95 | .param("password", password) 96 | .param("grant_type", "password") 97 | .param("scope", "read write") 98 | .param("client_id", "clientapp") 99 | .param("client_secret", "123456")) 100 | .andExpect(status().isOk()) 101 | .andExpect(content().contentType(contentType)) 102 | .andExpect(jsonPath("$.access_token", is(notNullValue()))) 103 | .andExpect(jsonPath("$.token_type", is(equalTo("bearer")))) 104 | .andExpect(jsonPath("$.refresh_token", is(notNullValue()))) 105 | .andExpect(jsonPath("$.expires_in", is(greaterThan(4000)))) 106 | .andExpect(jsonPath("$.scope", is(equalTo("read write")))) 107 | .andReturn().getResponse().getContentAsString(); 108 | 109 | // @formatter:on 110 | 111 | return content.substring(17, 53); 112 | } 113 | 114 | @Test 115 | public void greetingAuthorized() throws Exception { 116 | String accessToken = getAccessToken("roy", "spring"); 117 | 118 | // @formatter:off 119 | mvc.perform(get("/greeting") 120 | .header("Authorization", "Bearer " + accessToken)) 121 | .andExpect(status().isOk()) 122 | .andExpect(jsonPath("$.id", is(1))) 123 | .andExpect(jsonPath("$.content", is("Hello, Roy!"))); 124 | // @formatter:on 125 | 126 | // @formatter:off 127 | mvc.perform(get("/greeting") 128 | .header("Authorization", "Bearer " + accessToken)) 129 | .andExpect(status().isOk()) 130 | .andExpect(jsonPath("$.id", is(2))) 131 | .andExpect(jsonPath("$.content", is("Hello, Roy!"))); 132 | // @formatter:on 133 | 134 | // @formatter:off 135 | mvc.perform(get("/greeting") 136 | .header("Authorization", "Bearer " + accessToken)) 137 | .andExpect(status().isOk()) 138 | .andExpect(jsonPath("$.id", is(3))) 139 | .andExpect(jsonPath("$.content", is("Hello, Roy!"))); 140 | // @formatter:on 141 | } 142 | 143 | @Test 144 | public void usersEndpointAuthorized() throws Exception { 145 | // @formatter:off 146 | mvc.perform(get("/users") 147 | .header("Authorization", "Bearer " + getAccessToken("roy", "spring"))) 148 | .andExpect(status().isOk()) 149 | .andExpect(jsonPath("$", hasSize(3))); 150 | // @formatter:on 151 | } 152 | 153 | @Test 154 | public void usersEndpointAccessDenied() throws Exception { 155 | // @formatter:off 156 | mvc.perform(get("/users") 157 | .header("Authorization", "Bearer " + getAccessToken("craig", "spring"))) 158 | .andExpect(status().is(403)); 159 | // @formatter:on 160 | } 161 | 162 | } 163 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------