├── .gitignore ├── client ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── src │ └── main │ │ ├── resources │ │ ├── static │ │ │ └── css │ │ │ │ └── style.css │ │ ├── templates │ │ │ ├── login.html │ │ │ └── index.html │ │ └── application.yml │ │ └── java │ │ └── com │ │ └── example │ │ └── client │ │ ├── web │ │ ├── controller │ │ │ ├── LoginController.java │ │ │ └── TodoController.java │ │ ├── form │ │ │ └── TodoForm.java │ │ └── filter │ │ │ └── LoggingFilter.java │ │ ├── service │ │ ├── TodoService.java │ │ ├── dto │ │ │ └── Todo.java │ │ └── impl │ │ │ └── TodoServiceImpl.java │ │ ├── security │ │ ├── keycloak │ │ │ ├── KeycloakProperties.java │ │ │ └── KeycloakService.java │ │ ├── config │ │ │ └── SecurityConfig.java │ │ └── oauth2 │ │ │ └── OAuth2TokenService.java │ │ └── ClientApplication.java ├── .gitignore ├── pom.xml ├── mvnw.cmd └── mvnw └── resource-server ├── .mvn └── wrapper │ ├── maven-wrapper.properties │ └── maven-wrapper.jar ├── src └── main │ ├── resources │ ├── schema.sql │ ├── data.sql │ └── application.yml │ └── java │ └── com │ └── example │ └── resourceserver │ ├── service │ ├── TodoService.java │ └── impl │ │ └── TodoServiceImpl.java │ ├── persistence │ ├── respository │ │ └── TodoRepository.java │ └── entity │ │ └── Todo.java │ ├── web │ ├── request │ │ └── TodoRequest.java │ ├── response │ │ └── TodoResponse.java │ ├── filter │ │ └── LoggingFilter.java │ └── controller │ │ └── TodoController.java │ ├── security │ └── config │ │ └── SecurityConfig.java │ └── ResourceServerApplication.java ├── .gitignore ├── curl.txt ├── pom.xml ├── mvnw.cmd └── mvnw /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.sh -------------------------------------------------------------------------------- /client/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MasatoshiTada/oauth2-with-spring-security-51/HEAD/client/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /client/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip 2 | -------------------------------------------------------------------------------- /resource-server/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip 2 | -------------------------------------------------------------------------------- /resource-server/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MasatoshiTada/oauth2-with-spring-security-51/HEAD/resource-server/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /client/src/main/resources/static/css/style.css: -------------------------------------------------------------------------------- 1 | h1 { 2 | background-color: orange; 3 | } 4 | 5 | .error { 6 | color: red; 7 | } 8 | 9 | th { 10 | background-color: orange; 11 | } 12 | 13 | table, th, td { 14 | border: solid 1px; 15 | } -------------------------------------------------------------------------------- /resource-server/src/main/resources/schema.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE IF EXISTS todo; 2 | DROP SEQUENCE IF EXISTS seq_todo_id; 3 | 4 | CREATE SEQUENCE seq_todo_id START WITH 1 INCREMENT BY 1; 5 | 6 | CREATE TABLE todo( 7 | id INTEGER DEFAULT nextval('seq_todo_id') PRIMARY KEY, 8 | description VARCHAR(256), 9 | created_at TIMESTAMP, 10 | deadline DATE, 11 | done BOOLEAN 12 | ); -------------------------------------------------------------------------------- /client/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /resource-server/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /client/src/main/java/com/example/client/web/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.example.client.web.controller; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | 6 | @Controller 7 | public class LoginController { 8 | 9 | @GetMapping("/login") 10 | public String loginPage() { 11 | return "login"; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /client/src/main/java/com/example/client/service/TodoService.java: -------------------------------------------------------------------------------- 1 | package com.example.client.service; 2 | 3 | import com.example.client.service.dto.Todo; 4 | 5 | import java.util.List; 6 | 7 | public interface TodoService { 8 | 9 | public List findAll(); 10 | 11 | public void save(Todo todo); 12 | 13 | public void updateDoneById(Integer id); 14 | 15 | public void deleteById(Integer id); 16 | } 17 | -------------------------------------------------------------------------------- /resource-server/src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO todo(description, created_at, deadline, done) VALUES('牛乳を買う', CURRENT_TIMESTAMP, DATEADD('DAY', 3, CURRENT_DATE), TRUE); 2 | INSERT INTO todo(description, created_at, deadline, done) VALUES('メールを送る', CURRENT_TIMESTAMP, DATEADD('DAY', 4, CURRENT_DATE), FALSE); 3 | INSERT INTO todo(description, created_at, deadline, done) VALUES('本を買う', CURRENT_TIMESTAMP, DATEADD('DAY', 5, CURRENT_DATE), FALSE); -------------------------------------------------------------------------------- /resource-server/src/main/java/com/example/resourceserver/service/TodoService.java: -------------------------------------------------------------------------------- 1 | package com.example.resourceserver.service; 2 | 3 | import com.example.resourceserver.persistence.entity.Todo; 4 | 5 | public interface TodoService { 6 | 7 | public Iterable findAll(); 8 | 9 | public void save(Todo todo); 10 | 11 | public void updateDoneById(Integer id); 12 | 13 | public void deleteById(Integer id); 14 | 15 | public boolean existsById(Integer id); 16 | } 17 | -------------------------------------------------------------------------------- /client/src/main/resources/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | OAuth2ログインページ 7 | 9 | 10 | 11 |

OAuth2ログインページ

12 | Keycloakでログイン 13 | 14 | -------------------------------------------------------------------------------- /client/src/main/java/com/example/client/security/keycloak/KeycloakProperties.java: -------------------------------------------------------------------------------- 1 | package com.example.client.security.keycloak; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | @ConfigurationProperties("keycloak") 8 | public class KeycloakProperties { 9 | 10 | private String logoutUri; 11 | 12 | public String getLogoutUri() { 13 | return logoutUri; 14 | } 15 | 16 | public void setLogoutUri(String logoutUri) { 17 | this.logoutUri = logoutUri; 18 | } 19 | } -------------------------------------------------------------------------------- /resource-server/src/main/java/com/example/resourceserver/persistence/respository/TodoRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.resourceserver.persistence.respository; 2 | 3 | import com.example.resourceserver.persistence.entity.Todo; 4 | import org.springframework.data.jdbc.repository.query.Modifying; 5 | import org.springframework.data.jdbc.repository.query.Query; 6 | import org.springframework.data.repository.CrudRepository; 7 | 8 | public interface TodoRepository extends CrudRepository { 9 | 10 | @Query("UPDATE todo SET done = true WHERE id = :id") 11 | @Modifying 12 | public void updateDoneById(Integer id); 13 | } 14 | -------------------------------------------------------------------------------- /resource-server/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server.port: 8090 2 | 3 | spring.jackson: 4 | date-format: com.fasterxml.jackson.databind.util.StdDateFormat 5 | time-zone: Asia/Tokyo 6 | property-naming-strategy: SNAKE_CASE 7 | 8 | spring.datasource.sql-script-encoding: utf-8 9 | 10 | spring.security.oauth2.resourceserver.jwt: 11 | issuer-uri: http://localhost:9000/auth/realms/todo-api 12 | # jwk-set-uri: http://localhost:9000/auth/realms/todo-api/protocol/openid-connect/certs # not necessary if using Keycloak 13 | 14 | logging: 15 | level: 16 | org.springframework: 17 | security: trace 18 | jdbc.core.JdbcTemplate: debug -------------------------------------------------------------------------------- /resource-server/src/main/java/com/example/resourceserver/web/request/TodoRequest.java: -------------------------------------------------------------------------------- 1 | package com.example.resourceserver.web.request; 2 | 3 | import com.example.resourceserver.persistence.entity.Todo; 4 | 5 | import java.time.LocalDate; 6 | 7 | public class TodoRequest { 8 | 9 | private String description; 10 | 11 | private LocalDate deadline; 12 | 13 | public String getDescription() { 14 | return description; 15 | } 16 | 17 | public void setDescription(String description) { 18 | this.description = description; 19 | } 20 | 21 | public LocalDate getDeadline() { 22 | return deadline; 23 | } 24 | 25 | public void setDeadline(LocalDate deadline) { 26 | this.deadline = deadline; 27 | } 28 | 29 | public Todo convertToEntity() { 30 | return new Todo(description, deadline); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /client/src/main/java/com/example/client/web/form/TodoForm.java: -------------------------------------------------------------------------------- 1 | package com.example.client.web.form; 2 | 3 | import com.example.client.service.dto.Todo; 4 | import org.springframework.format.annotation.DateTimeFormat; 5 | 6 | import java.time.LocalDate; 7 | 8 | public class TodoForm { 9 | 10 | private final String description; 11 | 12 | @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) 13 | private final LocalDate deadline; 14 | 15 | public TodoForm(String description, LocalDate deadline) { 16 | this.description = description; 17 | this.deadline = deadline; 18 | } 19 | 20 | public String getDescription() { 21 | return description; 22 | } 23 | 24 | public LocalDate getDeadline() { 25 | return deadline; 26 | } 27 | 28 | public Todo convertToDto() { 29 | return new Todo(description, deadline); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/example/resourceserver/security/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.resourceserver.security.config; 2 | 3 | import org.springframework.http.HttpMethod; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 6 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 7 | 8 | @EnableWebSecurity 9 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 10 | 11 | @Override 12 | protected void configure(HttpSecurity http) throws Exception { 13 | http.authorizeRequests() 14 | .mvcMatchers(HttpMethod.GET, "/todos/**").hasAuthority("SCOPE_todo:read") 15 | .mvcMatchers("/todos/**").hasAuthority("SCOPE_todo:write") 16 | .anyRequest().authenticated(); 17 | http.oauth2ResourceServer() 18 | .jwt(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /client/src/main/java/com/example/client/service/dto/Todo.java: -------------------------------------------------------------------------------- 1 | package com.example.client.service.dto; 2 | 3 | import java.time.LocalDate; 4 | import java.time.LocalDateTime; 5 | 6 | public class Todo { 7 | 8 | private Integer id; 9 | 10 | private String description; 11 | 12 | private LocalDateTime createdAt; 13 | 14 | private LocalDate deadline; 15 | 16 | private Boolean done; 17 | 18 | public Todo() {} 19 | 20 | public Todo(String description, LocalDate deadline) { 21 | this.description = description; 22 | this.deadline = deadline; 23 | } 24 | 25 | public Integer getId() { 26 | return id; 27 | } 28 | 29 | public String getDescription() { 30 | return description; 31 | } 32 | 33 | public LocalDateTime getCreatedAt() { 34 | return createdAt; 35 | } 36 | 37 | public LocalDate getDeadline() { 38 | return deadline; 39 | } 40 | 41 | public Boolean getDone() { 42 | return done; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /resource-server/curl.txt: -------------------------------------------------------------------------------- 1 | # 認可サーバーからアクセストークンを取得する 2 | curl -v -X POST -u todo-client:9299ff05-1eca-45f1-a8ea-85d376943b20 -d grant_type=password -d username=user -d password=user http://localhost:9000/auth/realms/todo-api/protocol/openid-connect/token | jq 3 | 4 | # 全件検索 5 | curl -v -X GET -H "Authorization: Bearer $TODO_ACCESS_TOKEN" http://localhost:8090/todos | jq 6 | 7 | # 追加 8 | curl -v -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TODO_ACCESS_TOKEN" -d "{\"description\":\"Buy newspaper\",\"deadline\":\"2018-11-01\"}" http://localhost:8090/todos | jq 9 | 10 | # 更新 11 | curl -v -X PATCH -H "Authorization: Bearer $TODO_ACCESS_TOKEN" http://localhost:8090/todos/2 | jq 12 | 13 | # 削除 14 | curl -v -X DELETE -H "Authorization: Bearer $TODO_ACCESS_TOKEN" http://localhost:8090/todos/2 | jq 15 | 16 | # トークンのリフレッシュ 17 | curl -v -X POST -u todo-client:9299ff05-1eca-45f1-a8ea-85d376943b20 -d grant_type=refresh_token -d refresh_token=$TODO_REFRESH_TOKEN http://localhost:9000/auth/realms/todo-api/protocol/openid-connect/token | jq 18 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/example/resourceserver/ResourceServerApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.resourceserver; 2 | 3 | import com.example.resourceserver.web.filter.LoggingFilter; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 7 | import org.springframework.context.annotation.Bean; 8 | 9 | @SpringBootApplication 10 | public class ResourceServerApplication { 11 | 12 | public static void main(String[] args) { 13 | SpringApplication.run(ResourceServerApplication.class, args); 14 | } 15 | 16 | @Bean 17 | public FilterRegistrationBean loggingFilter() { 18 | LoggingFilter loggingFilter = new LoggingFilter(); 19 | FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(loggingFilter); 20 | // フィルターの順番を一番最初に指定 21 | registrationBean.setOrder(Integer.MIN_VALUE); 22 | // url-patternを指定 23 | registrationBean.addUrlPatterns("/*"); 24 | return registrationBean; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/example/resourceserver/web/response/TodoResponse.java: -------------------------------------------------------------------------------- 1 | package com.example.resourceserver.web.response; 2 | 3 | import com.example.resourceserver.persistence.entity.Todo; 4 | 5 | import java.time.LocalDate; 6 | import java.time.LocalDateTime; 7 | 8 | public class TodoResponse { 9 | 10 | private Integer id; 11 | 12 | private String description; 13 | 14 | private LocalDateTime createdAt; 15 | 16 | private LocalDate deadline; 17 | 18 | private Boolean done; 19 | 20 | public TodoResponse(Todo todo) { 21 | this.id = todo.getId(); 22 | this.description = todo.getDescription(); 23 | this.createdAt = todo.getCreatedAt(); 24 | this.deadline = todo.getDeadline(); 25 | this.done = todo.getDone(); 26 | } 27 | 28 | public Integer getId() { 29 | return id; 30 | } 31 | 32 | public String getDescription() { 33 | return description; 34 | } 35 | 36 | public LocalDateTime getCreatedAt() { 37 | return createdAt; 38 | } 39 | 40 | public LocalDate getDeadline() { 41 | return deadline; 42 | } 43 | 44 | public Boolean getDone() { 45 | return done; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/example/resourceserver/service/impl/TodoServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.resourceserver.service.impl; 2 | 3 | import com.example.resourceserver.persistence.entity.Todo; 4 | import com.example.resourceserver.persistence.respository.TodoRepository; 5 | import com.example.resourceserver.service.TodoService; 6 | import org.springframework.stereotype.Service; 7 | 8 | @Service 9 | public class TodoServiceImpl implements TodoService { 10 | 11 | private final TodoRepository todoRepository; 12 | 13 | public TodoServiceImpl(TodoRepository todoRepository) { 14 | this.todoRepository = todoRepository; 15 | } 16 | 17 | @Override 18 | public Iterable findAll() { 19 | return todoRepository.findAll(); 20 | } 21 | 22 | @Override 23 | public void save(Todo todo) { 24 | todoRepository.save(todo); 25 | } 26 | 27 | @Override 28 | public void updateDoneById(Integer id) { 29 | todoRepository.updateDoneById(id); 30 | } 31 | 32 | @Override 33 | public void deleteById(Integer id) { 34 | todoRepository.deleteById(id); 35 | } 36 | 37 | @Override 38 | public boolean existsById(Integer id) { 39 | return todoRepository.existsById(id); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /client/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | issuer.uri: http://localhost:9000/auth/realms/todo-api 2 | auth-server.uri: ${issuer.uri}/protocol/openid-connect 3 | resource-server.uri: http://localhost:8090 4 | 5 | keycloak: 6 | logout-uri: ${auth-server.uri}/logout 7 | 8 | spring.security.oauth2.client.registration.todo: 9 | provider: todo 10 | client-id: todo-client 11 | client-secret: efbd681a-343f-442c-8836-7d3a6c11c3d5 12 | client-authentication-method: basic 13 | redirect-uri: http://localhost:8080/login/oauth2/code/todo-client 14 | authorization-grant-type: authorization_code 15 | scope: todo:read,todo:write,profile,openid 16 | client-name: todo-client 17 | 18 | spring.security.oauth2.client.provider.todo: 19 | # authorization-uri: ${auth-server.uri}/auth 20 | # token-uri: ${auth-server.uri}/token 21 | # user-info-uri: ${auth-server.uri}/userinfo 22 | # user-info-authentication-method: basic 23 | user-name-attribute: preferred_username 24 | # jwk-set-uri: ${auth-server.uri}/certs # not necessary if using Keycloak 25 | issuer-uri: ${issuer.uri} 26 | 27 | logging: 28 | level: 29 | com.example: debug 30 | org.springframework: 31 | security: trace 32 | web.client.RestTemplate: debug 33 | 34 | spring.jackson: 35 | date-format: com.fasterxml.jackson.databind.util.StdDateFormat 36 | time-zone: Asia/Tokyo 37 | property-naming-strategy: SNAKE_CASE 38 | 39 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/example/resourceserver/persistence/entity/Todo.java: -------------------------------------------------------------------------------- 1 | package com.example.resourceserver.persistence.entity; 2 | 3 | import org.springframework.data.annotation.Id; 4 | import org.springframework.data.relational.core.mapping.Column; 5 | 6 | import java.time.LocalDate; 7 | import java.time.LocalDateTime; 8 | 9 | public class Todo { 10 | 11 | @Id 12 | private Integer id; 13 | 14 | private String description; 15 | 16 | @Column("CREATED_AT") 17 | private LocalDateTime createdAt; 18 | 19 | private LocalDate deadline; 20 | 21 | private Boolean done; 22 | 23 | public Todo() { 24 | } 25 | 26 | public Todo(String description, LocalDate deadline) { 27 | this.description = description; 28 | this.createdAt = LocalDateTime.now(); 29 | this.deadline = deadline; 30 | this.done = Boolean.FALSE; 31 | } 32 | 33 | public Integer getId() { 34 | return id; 35 | } 36 | 37 | public void setId(Integer id) { 38 | this.id = id; 39 | } 40 | 41 | public String getDescription() { 42 | return description; 43 | } 44 | 45 | public void setDescription(String description) { 46 | this.description = description; 47 | } 48 | 49 | public LocalDateTime getCreatedAt() { 50 | return createdAt; 51 | } 52 | 53 | public void setCreatedAt(LocalDateTime createdAt) { 54 | this.createdAt = createdAt; 55 | } 56 | 57 | public LocalDate getDeadline() { 58 | return deadline; 59 | } 60 | 61 | public void setDeadline(LocalDate deadline) { 62 | this.deadline = deadline; 63 | } 64 | 65 | public Boolean getDone() { 66 | return done; 67 | } 68 | 69 | public void setDone(Boolean done) { 70 | this.done = done; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /client/src/main/java/com/example/client/service/impl/TodoServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.client.service.impl; 2 | 3 | import com.example.client.service.TodoService; 4 | import com.example.client.service.dto.Todo; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.core.ParameterizedTypeReference; 7 | import org.springframework.http.HttpMethod; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.stereotype.Service; 10 | import org.springframework.web.client.RestTemplate; 11 | 12 | import java.util.List; 13 | 14 | @Service 15 | public class TodoServiceImpl implements TodoService { 16 | 17 | private final RestTemplate restTemplate; 18 | private final String resourceServerUri; 19 | 20 | public TodoServiceImpl(RestTemplate restTemplate, 21 | @Value("${resource-server.uri}") String resourceServerUri) { 22 | this.restTemplate = restTemplate; 23 | this.resourceServerUri = resourceServerUri; 24 | } 25 | 26 | @Override 27 | public List findAll() { 28 | ResponseEntity> responseEntity = restTemplate.exchange( 29 | resourceServerUri + "/todos", HttpMethod.GET, null, 30 | new ParameterizedTypeReference<>() {}); 31 | return responseEntity.getBody(); 32 | } 33 | 34 | @Override 35 | public void save(Todo todo) { 36 | restTemplate.postForEntity(resourceServerUri + "/todos", todo, Void.class); 37 | } 38 | 39 | @Override 40 | public void updateDoneById(Integer id) { 41 | restTemplate.patchForObject(resourceServerUri + "/todos/{id}", null, Void.class, id); 42 | } 43 | 44 | @Override 45 | public void deleteById(Integer id) { 46 | restTemplate.delete(resourceServerUri + "/todos/{id}", id); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /client/src/main/java/com/example/client/web/controller/TodoController.java: -------------------------------------------------------------------------------- 1 | package com.example.client.web.controller; 2 | 3 | import com.example.client.service.TodoService; 4 | import com.example.client.service.dto.Todo; 5 | import com.example.client.web.form.TodoForm; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.security.core.Authentication; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.ui.Model; 11 | import org.springframework.web.bind.annotation.GetMapping; 12 | import org.springframework.web.bind.annotation.PostMapping; 13 | import org.springframework.web.bind.annotation.RequestParam; 14 | 15 | import java.util.List; 16 | 17 | @Controller 18 | public class TodoController { 19 | 20 | private static final Logger logger = LoggerFactory.getLogger(TodoController.class); 21 | 22 | private final TodoService todoService; 23 | 24 | public TodoController(TodoService todoService) { 25 | this.todoService = todoService; 26 | } 27 | 28 | @GetMapping("/") 29 | public String index(Model model, Authentication authentication) { 30 | logger.debug("{}", authentication); 31 | List todoList = todoService.findAll(); 32 | model.addAttribute("todoList", todoList); 33 | return "index"; 34 | } 35 | 36 | @PostMapping("/add") 37 | public String add(TodoForm todoForm) { 38 | Todo todo = todoForm.convertToDto(); 39 | todoService.save(todo); 40 | return "redirect:/"; 41 | } 42 | 43 | @PostMapping("/update") 44 | public String update(@RequestParam Integer id) { 45 | todoService.updateDoneById(id); 46 | return "redirect:/"; 47 | } 48 | 49 | @PostMapping("/delete") 50 | public String delete(@RequestParam Integer id) { 51 | todoService.deleteById(id); 52 | return "redirect:/"; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /resource-server/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | resource-server 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | resource-server 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.3.3.RELEASE 18 | 19 | 20 | 21 | 22 | 11 23 | 24 | 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-data-jdbc 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-web 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-oauth2-resource-server 37 | 38 | 39 | com.h2database 40 | h2 41 | 42 | 43 | 44 | 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-maven-plugin 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /client/src/main/java/com/example/client/web/filter/LoggingFilter.java: -------------------------------------------------------------------------------- 1 | package com.example.client.web.filter; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.web.filter.OncePerRequestFilter; 6 | 7 | import javax.servlet.FilterChain; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | import java.io.IOException; 12 | import java.util.Enumeration; 13 | 14 | public class LoggingFilter extends OncePerRequestFilter { 15 | 16 | private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class); 17 | 18 | @Override 19 | protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) 20 | throws ServletException, IOException { 21 | logger.debug("======================================"); 22 | logger.debug("## REQUEST"); 23 | String requestMethodAndUri = httpServletRequest.getMethod() + " " + httpServletRequest.getRequestURI(); 24 | logger.debug(requestMethodAndUri); 25 | for (Enumeration headerNames = httpServletRequest.getHeaderNames(); headerNames.hasMoreElements();) { 26 | String headerName = headerNames.nextElement(); 27 | String headerValue = httpServletRequest.getHeader(headerName); 28 | logger.debug(headerName + ": " + headerValue); 29 | } 30 | logger.debug("======================================"); 31 | filterChain.doFilter(httpServletRequest, httpServletResponse); 32 | logger.debug("======================================"); 33 | logger.debug("## RESPONSE (for " + requestMethodAndUri + ")"); 34 | logger.debug("{}", httpServletResponse.getStatus()); 35 | for (String headerName : httpServletResponse.getHeaderNames()) { 36 | String headerValue = httpServletResponse.getHeader(headerName); 37 | logger.debug(headerName + ": " + headerValue); 38 | } 39 | logger.debug("======================================"); 40 | } 41 | } -------------------------------------------------------------------------------- /resource-server/src/main/java/com/example/resourceserver/web/filter/LoggingFilter.java: -------------------------------------------------------------------------------- 1 | package com.example.resourceserver.web.filter; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.web.filter.OncePerRequestFilter; 6 | 7 | import javax.servlet.FilterChain; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | import java.io.IOException; 12 | import java.util.Enumeration; 13 | 14 | public class LoggingFilter extends OncePerRequestFilter { 15 | 16 | private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class); 17 | 18 | @Override 19 | protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) 20 | throws ServletException, IOException { 21 | logger.debug("======================================"); 22 | logger.debug("## REQUEST"); 23 | String requestMethodAndUri = httpServletRequest.getMethod() + " " + httpServletRequest.getRequestURI(); 24 | logger.debug(requestMethodAndUri); 25 | for (Enumeration headerNames = httpServletRequest.getHeaderNames(); headerNames.hasMoreElements();) { 26 | String headerName = headerNames.nextElement(); 27 | String headerValue = httpServletRequest.getHeader(headerName); 28 | logger.debug(headerName + ": " + headerValue); 29 | } 30 | logger.debug("======================================"); 31 | filterChain.doFilter(httpServletRequest, httpServletResponse); 32 | logger.debug("======================================"); 33 | logger.debug("## RESPONSE (for " + requestMethodAndUri + ")"); 34 | logger.debug("{}", httpServletResponse.getStatus()); 35 | for (String headerName : httpServletResponse.getHeaderNames()) { 36 | String headerValue = httpServletResponse.getHeader(headerName); 37 | logger.debug(headerName + ": " + headerValue); 38 | } 39 | logger.debug("======================================"); 40 | } 41 | } -------------------------------------------------------------------------------- /client/src/main/java/com/example/client/security/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.client.security.config; 2 | 3 | import com.example.client.security.keycloak.KeycloakService; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.boot.autoconfigure.security.servlet.PathRequest; 7 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 8 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 9 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 11 | import org.springframework.security.web.authentication.logout.LogoutHandler; 12 | 13 | @EnableWebSecurity 14 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 15 | 16 | private static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class); 17 | 18 | private final KeycloakService keycloakService; 19 | 20 | public SecurityConfig(KeycloakService keycloakService) { 21 | this.keycloakService = keycloakService; 22 | } 23 | 24 | @Override 25 | public void configure(WebSecurity web) throws Exception { 26 | // /css/**, /js/**, /images/**, /webjars/**, /**/favicon.ico は􏰁セキュリティ保護対象外 27 | web.ignoring().requestMatchers( 28 | PathRequest.toStaticResources().atCommonLocations()); 29 | } 30 | 31 | @Override 32 | protected void configure(HttpSecurity http) throws Exception { 33 | http.oauth2Login() 34 | .loginPage("/login") 35 | .permitAll(); 36 | http.authorizeRequests() 37 | .anyRequest().authenticated(); 38 | http.logout() 39 | // 認可サーバーからもログアウトする 40 | .addLogoutHandler(logoutFromAuthServer()) 41 | .invalidateHttpSession(true) 42 | .permitAll(); 43 | } 44 | 45 | /** 46 | * 認可サーバーからログアウトするLogoutHandler 47 | */ 48 | private LogoutHandler logoutFromAuthServer() { 49 | return (request, response, authentication) -> { 50 | keycloakService.logout(); 51 | }; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /client/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | client 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | client 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.3.3.RELEASE 18 | 19 | 20 | 21 | 22 | 11 23 | 24 | 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-thymeleaf 29 | 30 | 31 | org.thymeleaf.extras 32 | thymeleaf-extras-springsecurity5 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-web 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-oauth2-client 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-configuration-processor 45 | true 46 | 47 | 48 | org.apache.httpcomponents 49 | httpclient 50 | 51 | 52 | 53 | 54 | 55 | 56 | org.springframework.boot 57 | spring-boot-maven-plugin 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /client/src/main/java/com/example/client/ClientApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.client; 2 | 3 | import com.example.client.security.oauth2.OAuth2TokenService; 4 | import com.example.client.web.filter.LoggingFilter; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.boot.web.client.RestTemplateBuilder; 10 | import org.springframework.boot.web.client.RestTemplateRequestCustomizer; 11 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.security.core.Authentication; 14 | import org.springframework.security.core.context.SecurityContextHolder; 15 | import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; 16 | import org.springframework.web.client.RestTemplate; 17 | 18 | import java.time.Duration; 19 | 20 | @SpringBootApplication 21 | public class ClientApplication { 22 | 23 | private static final Logger logger = LoggerFactory.getLogger(ClientApplication.class); 24 | 25 | public static void main(String[] args) { 26 | SpringApplication.run(ClientApplication.class, args); 27 | } 28 | 29 | @Bean 30 | public FilterRegistrationBean loggingFilter() { 31 | LoggingFilter loggingFilter = new LoggingFilter(); 32 | FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(loggingFilter); 33 | // フィルターの順番を一番最初に指定 34 | registrationBean.setOrder(Integer.MIN_VALUE); 35 | // url-patternを指定 36 | registrationBean.addUrlPatterns("/*"); 37 | return registrationBean; 38 | } 39 | 40 | @Bean 41 | public RestTemplate restTemplate(RestTemplateBuilder builder, OAuth2TokenService oAuth2TokenService) { 42 | return builder.setConnectTimeout(Duration.ofMillis(500)) 43 | .setReadTimeout(Duration.ofMillis(500)) 44 | .additionalRequestCustomizers(addAccessTokenToHeader(oAuth2TokenService)) 45 | .build(); 46 | } 47 | 48 | private RestTemplateRequestCustomizer addAccessTokenToHeader(OAuth2TokenService oAuth2TokenService) { 49 | return request -> { 50 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 51 | // 認証不要またはOAuth2以外なら何もしない 52 | if (authentication == null || !(authentication instanceof OAuth2AuthenticationToken)) { 53 | return; 54 | } 55 | // OAuth2の場合はAuthorizationヘッダーに"Bearer アクセストークン"をセットする 56 | request.getHeaders().setBearerAuth(oAuth2TokenService.getAccessTokenValue()); 57 | }; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /client/src/main/java/com/example/client/security/keycloak/KeycloakService.java: -------------------------------------------------------------------------------- 1 | package com.example.client.security.keycloak; 2 | 3 | import com.example.client.security.oauth2.OAuth2TokenService; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties; 7 | import org.springframework.http.HttpHeaders; 8 | import org.springframework.http.HttpMethod; 9 | import org.springframework.http.MediaType; 10 | import org.springframework.http.RequestEntity; 11 | import org.springframework.http.ResponseEntity; 12 | import org.springframework.stereotype.Service; 13 | import org.springframework.util.LinkedMultiValueMap; 14 | import org.springframework.util.MultiValueMap; 15 | import org.springframework.web.client.RestTemplate; 16 | 17 | import java.net.URI; 18 | 19 | /** 20 | * Keycloakに対する操作を提供するクラス。 21 | */ 22 | @Service 23 | public class KeycloakService { 24 | 25 | private static final Logger logger = LoggerFactory.getLogger(KeycloakService.class); 26 | 27 | private final RestTemplate restTemplate; 28 | private final OAuth2TokenService oAuth2TokenService; 29 | private final OAuth2ClientProperties.Registration registration; 30 | private final KeycloakProperties keycloakProperties; 31 | 32 | public KeycloakService(RestTemplate restTemplate, 33 | OAuth2TokenService oAuth2TokenService, 34 | OAuth2ClientProperties oAuth2ClientProperties, 35 | KeycloakProperties keycloakProperties) { 36 | this.restTemplate = restTemplate; 37 | this.oAuth2TokenService = oAuth2TokenService; 38 | this.registration = oAuth2ClientProperties.getRegistration().get("todo"); 39 | this.keycloakProperties = keycloakProperties; 40 | } 41 | 42 | /** 43 | * Keycloakからログアウトする。 44 | * https://www.keycloak.org/docs/latest/securing_apps/index.html#logout-endpoint 45 | */ 46 | public void logout() { 47 | // POSTするリクエストパラメーターを作成 48 | MultiValueMap formParams = new LinkedMultiValueMap<>(); 49 | formParams.add("client_id", registration.getClientId()); 50 | formParams.add("client_secret", registration.getClientSecret()); 51 | formParams.add("refresh_token", oAuth2TokenService.getRefreshTokenValue()); 52 | // リクエストヘッダーを作成 53 | HttpHeaders httpHeaders = new HttpHeaders(); 54 | httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); 55 | // リクエストを作成 56 | RequestEntity> requestEntity = 57 | new RequestEntity<>(formParams, httpHeaders, HttpMethod.POST, 58 | URI.create(keycloakProperties.getLogoutUri())); 59 | // POSTリクエスト送信(ログアウト実行) 60 | ResponseEntity responseEntity = restTemplate.exchange(requestEntity, String.class); 61 | // ログ出力 62 | logger.info("{}", responseEntity.getStatusCode()); 63 | logger.info("{}", responseEntity.getBody()); 64 | } 65 | } -------------------------------------------------------------------------------- /resource-server/src/main/java/com/example/resourceserver/web/controller/TodoController.java: -------------------------------------------------------------------------------- 1 | package com.example.resourceserver.web.controller; 2 | 3 | import com.example.resourceserver.persistence.entity.Todo; 4 | import com.example.resourceserver.service.TodoService; 5 | import com.example.resourceserver.web.request.TodoRequest; 6 | import com.example.resourceserver.web.response.TodoResponse; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.DeleteMapping; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.PatchMapping; 12 | import org.springframework.web.bind.annotation.PathVariable; 13 | import org.springframework.web.bind.annotation.PostMapping; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | import org.springframework.web.bind.annotation.RequestMapping; 16 | import org.springframework.web.bind.annotation.ResponseStatus; 17 | import org.springframework.web.bind.annotation.RestController; 18 | import org.springframework.web.server.ResponseStatusException; 19 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder; 20 | 21 | import java.net.URI; 22 | import java.util.List; 23 | import java.util.stream.Collectors; 24 | import java.util.stream.StreamSupport; 25 | 26 | @RestController 27 | @RequestMapping("/todos") 28 | public class TodoController { 29 | 30 | private final TodoService todoService; 31 | 32 | public TodoController(TodoService todoService) { 33 | this.todoService = todoService; 34 | } 35 | 36 | @GetMapping 37 | public List getAll() { 38 | List todoResponseList = 39 | StreamSupport.stream(todoService.findAll().spliterator(), false) 40 | .map(todo -> new TodoResponse(todo)) 41 | .collect(Collectors.toList()); 42 | return todoResponseList; 43 | } 44 | 45 | @PostMapping 46 | public ResponseEntity post(@RequestBody TodoRequest todoRequest) { 47 | Todo todo = todoRequest.convertToEntity(); 48 | todoService.save(todo); 49 | URI location = ServletUriComponentsBuilder.fromCurrentRequest() 50 | .pathSegment(todo.getId().toString()) 51 | .buildAndExpand() 52 | .toUri(); 53 | return ResponseEntity.created(location).build(); 54 | } 55 | 56 | @PatchMapping("/{id}") 57 | @ResponseStatus(HttpStatus.OK) 58 | public void updateDoneById(@PathVariable Integer id) { 59 | if (todoService.existsById(id) == false) { 60 | throw new ResponseStatusException(HttpStatus.NOT_FOUND, "todo not found"); 61 | } 62 | todoService.updateDoneById(id); 63 | } 64 | 65 | @DeleteMapping("/{id}") 66 | @ResponseStatus(HttpStatus.NO_CONTENT) 67 | public void deleteById(@PathVariable Integer id) { 68 | if (todoService.existsById(id) == false) { 69 | throw new ResponseStatusException(HttpStatus.NOT_FOUND, "todo not found"); 70 | } 71 | todoService.deleteById(id); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /client/src/main/resources/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | TODO一覧 7 | 9 | 10 | 11 |

TODO一覧

12 | 13 |

ユーザーさんログイン中

14 | 15 |
16 | 17 | 18 | 19 | 22 | 23 | 24 | 25 | 28 | 29 |
内容 20 | 21 |
締切 26 | 27 |
30 | 31 |
32 | 33 |
34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 53 | 59 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 79 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 98 | 104 | 105 | 106 |
ID内容登録日時締切完了済み完了済みにする削除する
1牛乳を買う2018-10-31 13:002018-11-05 51 | false 52 | 54 |
55 | 56 | 57 |
58 |
60 |
61 | 62 | 63 |
64 |
2牛乳を買う2018-10-31 13:002018-11-05false 74 |
75 | 76 | 77 |
78 |
80 |
81 | 82 | 83 |
84 |
3牛乳を買う2018-10-31 13:002018-11-05false 93 |
94 | 95 | 96 |
97 |
99 |
100 | 101 | 102 |
103 |
107 | 108 |
109 | 110 |
111 | 112 | 113 | -------------------------------------------------------------------------------- /client/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /resource-server/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /client/src/main/java/com/example/client/security/oauth2/OAuth2TokenService.java: -------------------------------------------------------------------------------- 1 | package com.example.client.security.oauth2; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.boot.web.client.RestTemplateBuilder; 6 | import org.springframework.http.converter.FormHttpMessageConverter; 7 | import org.springframework.security.core.context.SecurityContextHolder; 8 | import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; 9 | import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; 10 | import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; 11 | import org.springframework.security.oauth2.client.endpoint.DefaultRefreshTokenTokenResponseClient; 12 | import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest; 13 | import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler; 14 | import org.springframework.security.oauth2.client.registration.ClientRegistration; 15 | import org.springframework.security.oauth2.core.OAuth2AccessToken; 16 | import org.springframework.security.oauth2.core.OAuth2RefreshToken; 17 | import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; 18 | import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter; 19 | import org.springframework.security.oauth2.core.http.converter.OAuth2ErrorHttpMessageConverter; 20 | import org.springframework.stereotype.Service; 21 | import org.springframework.web.client.RestTemplate; 22 | 23 | import java.time.Duration; 24 | import java.time.Instant; 25 | 26 | @Service 27 | public class OAuth2TokenService { 28 | 29 | private static final Logger logger = LoggerFactory.getLogger(OAuth2TokenService.class); 30 | 31 | private final OAuth2AuthorizedClientService authorizedClientService; 32 | private final DefaultRefreshTokenTokenResponseClient tokenResponseClient; 33 | 34 | public OAuth2TokenService(OAuth2AuthorizedClientService authorizedClientService, RestTemplateBuilder restTemplateBuilder) { 35 | this.authorizedClientService = authorizedClientService; 36 | this.tokenResponseClient = new DefaultRefreshTokenTokenResponseClient(); 37 | RestTemplate restTemplate = restTemplateBuilder 38 | .setConnectTimeout(Duration.ofMillis(300)) 39 | .setReadTimeout(Duration.ofMillis(300)) 40 | .errorHandler(new OAuth2ErrorResponseErrorHandler()) 41 | .messageConverters( 42 | new OAuth2AccessTokenResponseHttpMessageConverter(), 43 | new OAuth2ErrorHttpMessageConverter(), 44 | new FormHttpMessageConverter()) 45 | .build(); 46 | tokenResponseClient.setRestOperations(restTemplate); 47 | } 48 | 49 | /** 50 | * アクセストークンの値を取得する。 51 | */ 52 | public String getAccessTokenValue() { 53 | OAuth2AccessToken accessToken = getAuthorizedClient().getAccessToken(); 54 | // アクセストークンが期限切れだったらリフレッシュ 55 | if (isExpired(accessToken)) { 56 | logger.debug("Access token was expired!"); 57 | accessToken = refresh(); 58 | } 59 | String tokenValue = accessToken.getTokenValue(); 60 | logger.debug("access_token = {}", tokenValue); 61 | return tokenValue; 62 | } 63 | 64 | /** 65 | * リフレッシュトークンの値を取得する。 66 | */ 67 | public String getRefreshTokenValue() { 68 | OAuth2RefreshToken refreshToken = getAuthorizedClient().getRefreshToken(); 69 | String tokenValue = refreshToken.getTokenValue(); 70 | return tokenValue; 71 | } 72 | 73 | /** 74 | * アクセストークンが期限切れならばtrueを返す。 75 | */ 76 | private boolean isExpired(OAuth2AccessToken accessToken) { 77 | return accessToken.getExpiresAt().isBefore(Instant.now()); 78 | } 79 | 80 | /** 81 | * リフレッシュトークンでアクセストークンを再取得する。 82 | */ 83 | private OAuth2AccessToken refresh() { 84 | // トークンをリフレッシュ 85 | OAuth2AuthorizedClient currentAuthorizedClient = getAuthorizedClient(); 86 | ClientRegistration clientRegistration = currentAuthorizedClient.getClientRegistration(); 87 | OAuth2RefreshTokenGrantRequest tokenRequest = 88 | new OAuth2RefreshTokenGrantRequest(clientRegistration, 89 | currentAuthorizedClient.getAccessToken(), 90 | currentAuthorizedClient.getRefreshToken()); 91 | OAuth2AccessTokenResponse tokenResponse = tokenResponseClient.getTokenResponse(tokenRequest); 92 | // インメモリから既存のトークンを削除 93 | authorizedClientService.removeAuthorizedClient( 94 | clientRegistration.getRegistrationId(), 95 | currentAuthorizedClient.getPrincipalName()); 96 | // インメモリに新しいトークンを登録 97 | OAuth2AuthenticationToken authentication = getAuthentication(); 98 | OAuth2AuthorizedClient newAuthorizedClient = new OAuth2AuthorizedClient( 99 | clientRegistration, authentication.getName(), 100 | tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()); 101 | authorizedClientService.saveAuthorizedClient(newAuthorizedClient, authentication); 102 | logger.debug("Refreshing token completed"); 103 | return tokenResponse.getAccessToken(); 104 | } 105 | 106 | /** 107 | * OAuth2AuthorizedClientを取得する。 108 | */ 109 | public OAuth2AuthorizedClient getAuthorizedClient() { 110 | // OAuth2AuthenticationTokenはAuthenticationインタフェース実装クラス 111 | OAuth2AuthenticationToken authentication = getAuthentication(); 112 | // OAuth2AuthorizedClientを取得 113 | OAuth2AuthorizedClient authorizedClient = authorizedClientService.loadAuthorizedClient( 114 | authentication.getAuthorizedClientRegistrationId(), 115 | authentication.getName()); 116 | return authorizedClient; 117 | } 118 | 119 | /** 120 | * OAuth2AuthenticationTokenを取得する。 121 | */ 122 | public OAuth2AuthenticationToken getAuthentication() { 123 | OAuth2AuthenticationToken authentication = 124 | (OAuth2AuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); 125 | return authentication; 126 | } 127 | 128 | } -------------------------------------------------------------------------------- /client/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /resource-server/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | --------------------------------------------------------------------------------