├── service-hi ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── .gitignore ├── src │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── service │ │ │ └── hi │ │ │ └── servicehi │ │ │ └── ServiceHiApplicationTests.java │ └── main │ │ ├── java │ │ └── com │ │ │ └── service │ │ │ └── hi │ │ │ └── servicehi │ │ │ ├── ServiceHiApplication.java │ │ │ ├── config │ │ │ ├── ResourceServerConfiguration.java │ │ │ └── OAuth2ClientConfig.java │ │ │ └── controller │ │ │ └── TestEndPointController.java │ │ └── resources │ │ └── application.yml ├── pom.xml ├── mvnw.cmd └── mvnw ├── eureka-server ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── src │ ├── main │ │ ├── resources │ │ │ └── application.yml │ │ └── java │ │ │ └── com │ │ │ └── eureka │ │ │ └── server │ │ │ └── eurekaserver │ │ │ └── EurekaServerApplication.java │ └── test │ │ └── java │ │ └── com │ │ └── eureka │ │ └── server │ │ └── eurekaserver │ │ └── EurekaServerApplicationTests.java ├── .gitignore ├── pom.xml ├── mvnw.cmd └── mvnw ├── service-auth ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── service │ │ │ │ └── auth │ │ │ │ └── serviceauth │ │ │ │ ├── config │ │ │ │ ├── Utils.java │ │ │ │ ├── SecurityConfiguration.java │ │ │ │ └── AuthorizationServerConfiguration.java │ │ │ │ ├── ServiceAuthApplication.java │ │ │ │ ├── controller │ │ │ │ └── UserController.java │ │ │ │ └── customImpl │ │ │ │ └── MyRedisTokenStore.java │ │ └── resources │ │ │ └── application.yml │ └── test │ │ └── java │ │ └── com │ │ └── service │ │ └── auth │ │ └── serviceauth │ │ └── ServiceAuthApplicationTests.java ├── .gitignore ├── pom.xml ├── mvnw.cmd └── mvnw ├── .gitignore ├── pom.xml └── README.md /service-hi/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liangxiaobo/test-security-oauth2/HEAD/service-hi/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /eureka-server/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liangxiaobo/test-security-oauth2/HEAD/eureka-server/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /service-auth/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liangxiaobo/test-security-oauth2/HEAD/service-auth/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /service-hi/.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 | -------------------------------------------------------------------------------- /eureka-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 | -------------------------------------------------------------------------------- /service-auth/.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 | -------------------------------------------------------------------------------- /service-auth/src/main/java/com/service/auth/serviceauth/config/Utils.java: -------------------------------------------------------------------------------- 1 | package com.service.auth.serviceauth.config; 2 | 3 | public class Utils { 4 | public static class RESOURCEIDS { 5 | static final String ORDER = "order"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | 14 | .idea 15 | .DS_Store 16 | *.iml 17 | 18 | -------------------------------------------------------------------------------- /eureka-server/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: eureka-server 4 | server: 5 | port: 8761 6 | eureka: 7 | instance: 8 | hostname: localhost 9 | client: 10 | service-url: 11 | defaultZone: http://localhost:8761/eureka/ 12 | fetch-registry: false 13 | register-with-eureka: false 14 | -------------------------------------------------------------------------------- /service-auth/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: service-auth 4 | 5 | redis: 6 | host: 172.16.10.43 7 | database: 1 8 | 9 | 10 | server: 11 | port: 9098 12 | eureka: 13 | client: 14 | service-url: 15 | defaultZone: http://localhost:8761/eureka/ 16 | 17 | #logging.level.org.springframework.security: DEBUG 18 | 19 | -------------------------------------------------------------------------------- /eureka-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/ -------------------------------------------------------------------------------- /service-auth/.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/ -------------------------------------------------------------------------------- /service-hi/.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/ -------------------------------------------------------------------------------- /service-hi/src/test/java/com/service/hi/servicehi/ServiceHiApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.service.hi.servicehi; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class ServiceHiApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.test.security.oauth2.demo 8 | test-security-oauth2-demo 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /service-auth/src/test/java/com/service/auth/serviceauth/ServiceAuthApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.service.auth.serviceauth; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class ServiceAuthApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /eureka-server/src/test/java/com/eureka/server/eurekaserver/EurekaServerApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.eureka.server.eurekaserver; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class EurekaServerApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /eureka-server/src/main/java/com/eureka/server/eurekaserver/EurekaServerApplication.java: -------------------------------------------------------------------------------- 1 | package com.eureka.server.eurekaserver; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; 6 | 7 | @SpringBootApplication 8 | @EnableEurekaServer 9 | public class EurekaServerApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(EurekaServerApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /service-hi/src/main/java/com/service/hi/servicehi/ServiceHiApplication.java: -------------------------------------------------------------------------------- 1 | package com.service.hi.servicehi; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.netflix.eureka.EnableEurekaClient; 6 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 7 | 8 | @SpringBootApplication 9 | @EnableEurekaClient 10 | public class ServiceHiApplication { 11 | 12 | public static void main(String[] args) { 13 | SpringApplication.run(ServiceHiApplication.class, args); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /service-auth/src/main/java/com/service/auth/serviceauth/ServiceAuthApplication.java: -------------------------------------------------------------------------------- 1 | package com.service.auth.serviceauth; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.cloud.netflix.eureka.EnableEurekaClient; 7 | import org.springframework.context.annotation.ComponentScan; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 10 | 11 | @SpringBootApplication 12 | @EnableResourceServer 13 | @EnableEurekaClient 14 | public class ServiceAuthApplication { 15 | 16 | public static void main(String[] args) { 17 | SpringApplication.run(ServiceAuthApplication.class, args); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /service-hi/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | eureka: 2 | client: 3 | service-url: 4 | defaultZone: http://localhost:8761/eureka/ 5 | server: 6 | port: 8765 7 | spring: 8 | application: 9 | name: service-hi 10 | # datasource: 11 | # driver-class-name: com.mysql.jdbc.Driver 12 | # url: jdbc:mysql://172.16.10.44:3306/spring-cloud-auth?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8 13 | # username: dev 14 | # password: NHdev2015 15 | # 16 | # jpa: 17 | # hibernate: 18 | # ddl-auto: update 19 | # show-sql: true 20 | 21 | security: 22 | oauth2: 23 | resource: 24 | user-info-uri: http://localhost:9098/users/current 25 | client: 26 | id: client_2 27 | client-secret: 123456 28 | access-token-uri: http://localhost:9098/oauth/token 29 | grant-type: client_credentials,password 30 | scope: server 31 | 32 | 33 | -------------------------------------------------------------------------------- /service-auth/src/main/java/com/service/auth/serviceauth/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.service.auth.serviceauth.controller; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RequestMethod; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import java.security.Principal; 10 | 11 | @RestController 12 | @RequestMapping("/users") 13 | public class UserController { 14 | 15 | Logger logger = LoggerFactory.getLogger(UserController.class); 16 | 17 | @RequestMapping(value = "/current", method = RequestMethod.GET) 18 | public Principal getUser(Principal principal) { 19 | logger.info(">>>>>>>>>>>>>>>>>>>>>>>>"); 20 | logger.info(principal.toString()); 21 | logger.info(">>>>>>>>>>>>>>>>>>>>>>>>"); 22 | return principal; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /service-hi/src/main/java/com/service/hi/servicehi/config/ResourceServerConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.service.hi.servicehi.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 5 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 7 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 8 | import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; 9 | 10 | @Configuration 11 | @EnableResourceServer 12 | @EnableGlobalMethodSecurity(prePostEnabled = true) 13 | public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { 14 | 15 | 16 | @Override 17 | public void configure(HttpSecurity http) throws Exception { 18 | http.authorizeRequests() 19 | .antMatchers("/order/**").authenticated(); // 配置order访问控制,必须认证后才可以访问 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /service-hi/src/main/java/com/service/hi/servicehi/config/OAuth2ClientConfig.java: -------------------------------------------------------------------------------- 1 | package com.service.hi.servicehi.config; 2 | 3 | import feign.RequestInterceptor; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 6 | import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; 10 | import org.springframework.security.oauth2.client.OAuth2RestTemplate; 11 | import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; 12 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; 13 | 14 | 15 | @EnableOAuth2Client 16 | @EnableConfigurationProperties 17 | @Configuration 18 | public class OAuth2ClientConfig { 19 | 20 | @Bean 21 | @ConfigurationProperties(prefix = "security.oauth2.client") 22 | public ClientCredentialsResourceDetails clientCredentialsResourceDetails() { 23 | return new ClientCredentialsResourceDetails(); 24 | } 25 | 26 | @Bean 27 | public RequestInterceptor oauth2FeignRequestInterceptor() { 28 | return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), clientCredentialsResourceDetails()); 29 | } 30 | 31 | @Bean 32 | public OAuth2RestTemplate clientCredentialsRestTemplate() { 33 | return new OAuth2RestTemplate(clientCredentialsResourceDetails()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /service-hi/src/main/java/com/service/hi/servicehi/controller/TestEndPointController.java: -------------------------------------------------------------------------------- 1 | package com.service.hi.servicehi.controller; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.security.core.Authentication; 6 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.PathVariable; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import java.security.Principal; 12 | 13 | @RestController 14 | public class TestEndPointController { 15 | 16 | Logger logger = LoggerFactory.getLogger(TestEndPointController.class); 17 | 18 | @GetMapping("/product/{id}") 19 | public String getProduct(@PathVariable String id) { 20 | // Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 21 | return "product id : " + id; 22 | } 23 | 24 | @GetMapping("/order/{id}") 25 | public String getOrder(@PathVariable String id) { 26 | // Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 27 | return "order id : " + id; 28 | } 29 | 30 | @GetMapping("/getPrinciple") 31 | public OAuth2Authentication getPrinciple(OAuth2Authentication oAuth2Authentication, Principal principal, Authentication authentication) { 32 | logger.info(oAuth2Authentication.getUserAuthentication().getAuthorities().toString()); 33 | logger.info(oAuth2Authentication.toString()); 34 | logger.info("principal.toString() " + principal.toString()); 35 | logger.info("principal.getName() " + principal.getName()); 36 | logger.info("authentication: " + authentication.getAuthorities().toString()); 37 | 38 | return oAuth2Authentication; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /eureka-server/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.eureka.server 7 | eureka-server 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | eureka-server 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.4.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Finchley.SR1 26 | 27 | 28 | 29 | 30 | org.springframework.cloud 31 | spring-cloud-starter-netflix-eureka-server 32 | 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-test 37 | test 38 | 39 | 40 | 41 | 42 | 43 | 44 | org.springframework.cloud 45 | spring-cloud-dependencies 46 | ${spring-cloud.version} 47 | pom 48 | import 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | org.springframework.boot 57 | spring-boot-maven-plugin 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /service-auth/src/main/java/com/service/auth/serviceauth/config/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.service.auth.serviceauth.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.authentication.AuthenticationManager; 6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 7 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 8 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 9 | import org.springframework.security.core.userdetails.User; 10 | import org.springframework.security.core.userdetails.UserDetailsService; 11 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 12 | import org.springframework.security.crypto.factory.PasswordEncoderFactories; 13 | import org.springframework.security.crypto.password.PasswordEncoder; 14 | import org.springframework.security.provisioning.InMemoryUserDetailsManager; 15 | 16 | @Configuration 17 | @EnableWebSecurity 18 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 19 | @Bean 20 | @Override 21 | protected UserDetailsService userDetailsService() { 22 | BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); 23 | 24 | String finalPassword = "{bcrypt}"+bCryptPasswordEncoder.encode("123456"); 25 | InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); 26 | manager.createUser(User.withUsername("user_1").password(finalPassword).authorities("USER").build()); 27 | manager.createUser(User.withUsername("user_2").password(finalPassword).authorities("USER").build()); 28 | 29 | return manager; 30 | } 31 | 32 | @Bean 33 | PasswordEncoder passwordEncoder() { 34 | return PasswordEncoderFactories.createDelegatingPasswordEncoder(); 35 | } 36 | 37 | @Bean 38 | @Override 39 | public AuthenticationManager authenticationManagerBean() throws Exception { 40 | AuthenticationManager manager = super.authenticationManagerBean(); 41 | return manager; 42 | } 43 | 44 | @Override 45 | protected void configure(HttpSecurity http) throws Exception { 46 | http.requestMatchers().anyRequest() 47 | .and() 48 | .authorizeRequests() 49 | .antMatchers("/oauth/**").permitAll(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /service-hi/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.service.hi 7 | service-hi 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | service-hi 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.4.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Finchley.SR1 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | org.springframework.cloud 35 | spring-cloud-starter-netflix-eureka-client 36 | 37 | 38 | org.springframework.cloud 39 | spring-cloud-starter-oauth2 40 | 41 | 42 | org.springframework.cloud 43 | spring-cloud-starter-openfeign 44 | 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-test 49 | test 50 | 51 | 52 | 53 | 54 | 55 | 56 | org.springframework.cloud 57 | spring-cloud-dependencies 58 | ${spring-cloud.version} 59 | pom 60 | import 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | org.springframework.boot 69 | spring-boot-maven-plugin 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /service-auth/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.service.auth 7 | service-auth 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | service-auth 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.4.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Finchley.SR1 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-actuator 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-data-redis 36 | 37 | 38 | org.springframework.cloud 39 | spring-cloud-starter-netflix-eureka-client 40 | 41 | 42 | org.springframework.cloud 43 | spring-cloud-starter-oauth2 44 | 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-test 49 | test 50 | 51 | 52 | 53 | 54 | 55 | 56 | org.springframework.cloud 57 | spring-cloud-dependencies 58 | ${spring-cloud.version} 59 | pom 60 | import 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | org.springframework.boot 69 | spring-boot-maven-plugin 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /service-auth/src/main/java/com/service/auth/serviceauth/config/AuthorizationServerConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.service.auth.serviceauth.config; 2 | 3 | import com.service.auth.serviceauth.customImpl.MyRedisTokenStore; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.data.redis.connection.RedisConnectionFactory; 7 | import org.springframework.http.HttpMethod; 8 | import org.springframework.security.authentication.AuthenticationManager; 9 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 10 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 11 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 12 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 13 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 14 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; 15 | 16 | @Configuration 17 | @EnableAuthorizationServer 18 | public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { 19 | @Autowired 20 | AuthenticationManager authenticationManager; 21 | 22 | @Autowired 23 | RedisConnectionFactory redisConnectionFactory; 24 | 25 | @Override 26 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 27 | String finalSecret = "{bcrypt}" + new BCryptPasswordEncoder().encode("123456"); 28 | 29 | // 配置两个客户端,一个用于password认证一个用于client认证 30 | clients.inMemory().withClient("client_1") 31 | // .resourceIds(Utils.RESOURCEIDS.ORDER) 32 | .authorizedGrantTypes("client_credentials", "refresh_token") 33 | .scopes("select") 34 | .authorities("oauth2") 35 | .secret(finalSecret) 36 | .and().withClient("client_2") 37 | // .resourceIds(Utils.RESOURCEIDS.ORDER) 38 | .authorizedGrantTypes("password", "refresh_token") 39 | .scopes("server") 40 | .authorities("oauth2") 41 | .secret(finalSecret); 42 | } 43 | 44 | @Override 45 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 46 | endpoints.tokenStore(new MyRedisTokenStore(redisConnectionFactory)) 47 | .authenticationManager(authenticationManager) 48 | .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); 49 | } 50 | 51 | @Override 52 | public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { 53 | // 允许表单认证 54 | security.allowFormAuthenticationForClients().tokenKeyAccess("permitAll()") 55 | .checkTokenAccess("isAuthenticated()"); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /service-hi/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 | -------------------------------------------------------------------------------- /eureka-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 | -------------------------------------------------------------------------------- /service-auth/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 | -------------------------------------------------------------------------------- /eureka-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 | -------------------------------------------------------------------------------- /service-auth/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 | -------------------------------------------------------------------------------- /service-hi/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 | -------------------------------------------------------------------------------- /service-auth/src/main/java/com/service/auth/serviceauth/customImpl/MyRedisTokenStore.java: -------------------------------------------------------------------------------- 1 | package com.service.auth.serviceauth.customImpl; 2 | 3 | import org.springframework.data.redis.connection.RedisConnection; 4 | import org.springframework.data.redis.connection.RedisConnectionFactory; 5 | import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken; 6 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 7 | import org.springframework.security.oauth2.common.OAuth2RefreshToken; 8 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 9 | import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator; 10 | import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator; 11 | import org.springframework.security.oauth2.provider.token.TokenStore; 12 | import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy; 13 | import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy; 14 | 15 | import java.util.*; 16 | 17 | public class MyRedisTokenStore implements TokenStore {private static final String ACCESS = "access:"; 18 | private static final String AUTH_TO_ACCESS = "auth_to_access:"; 19 | private static final String AUTH = "auth:"; 20 | private static final String REFRESH_AUTH = "refresh_auth:"; 21 | private static final String ACCESS_TO_REFRESH = "access_to_refresh:"; 22 | private static final String REFRESH = "refresh:"; 23 | private static final String REFRESH_TO_ACCESS = "refresh_to_access:"; 24 | private static final String CLIENT_ID_TO_ACCESS = "client_id_to_access:"; 25 | private static final String UNAME_TO_ACCESS = "uname_to_access:"; 26 | private final RedisConnectionFactory connectionFactory; 27 | private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator(); 28 | private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy(); 29 | private String prefix = ""; 30 | 31 | public MyRedisTokenStore(RedisConnectionFactory connectionFactory) { 32 | this.connectionFactory = connectionFactory; 33 | } 34 | 35 | public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) { 36 | this.authenticationKeyGenerator = authenticationKeyGenerator; 37 | } 38 | 39 | public void setSerializationStrategy(RedisTokenStoreSerializationStrategy serializationStrategy) { 40 | this.serializationStrategy = serializationStrategy; 41 | } 42 | 43 | public void setPrefix(String prefix) { 44 | this.prefix = prefix; 45 | } 46 | 47 | private RedisConnection getConnection() { 48 | return this.connectionFactory.getConnection(); 49 | } 50 | 51 | private byte[] serialize(Object object) { 52 | return this.serializationStrategy.serialize(object); 53 | } 54 | 55 | private byte[] serializeKey(String object) { 56 | return this.serialize(this.prefix + object); 57 | } 58 | 59 | private OAuth2AccessToken deserializeAccessToken(byte[] bytes) { 60 | return (OAuth2AccessToken)this.serializationStrategy.deserialize(bytes, OAuth2AccessToken.class); 61 | } 62 | 63 | private OAuth2Authentication deserializeAuthentication(byte[] bytes) { 64 | return (OAuth2Authentication)this.serializationStrategy.deserialize(bytes, OAuth2Authentication.class); 65 | } 66 | 67 | private OAuth2RefreshToken deserializeRefreshToken(byte[] bytes) { 68 | return (OAuth2RefreshToken)this.serializationStrategy.deserialize(bytes, OAuth2RefreshToken.class); 69 | } 70 | 71 | private byte[] serialize(String string) { 72 | return this.serializationStrategy.serialize(string); 73 | } 74 | 75 | private String deserializeString(byte[] bytes) { 76 | return this.serializationStrategy.deserializeString(bytes); 77 | } 78 | 79 | public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { 80 | String key = this.authenticationKeyGenerator.extractKey(authentication); 81 | byte[] serializedKey = this.serializeKey("auth_to_access:" + key); 82 | byte[] bytes = null; 83 | RedisConnection conn = this.getConnection(); 84 | 85 | 86 | try { 87 | bytes = conn.get(serializedKey); 88 | } finally { 89 | conn.close(); 90 | } 91 | 92 | OAuth2AccessToken accessToken = this.deserializeAccessToken(bytes); 93 | if (accessToken != null) { 94 | OAuth2Authentication storedAuthentication = this.readAuthentication(accessToken.getValue()); 95 | if (storedAuthentication == null || !key.equals(this.authenticationKeyGenerator.extractKey(storedAuthentication))) { 96 | this.storeAccessToken(accessToken, authentication); 97 | } 98 | } 99 | 100 | return accessToken; 101 | } 102 | 103 | public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { 104 | return this.readAuthentication(token.getValue()); 105 | } 106 | 107 | public OAuth2Authentication readAuthentication(String token) { 108 | byte[] bytes = null; 109 | RedisConnection conn = this.getConnection(); 110 | 111 | 112 | try { 113 | bytes = conn.get(this.serializeKey("auth:" + token)); 114 | } finally { 115 | conn.close(); 116 | } 117 | 118 | OAuth2Authentication var4 = this.deserializeAuthentication(bytes); 119 | return var4; 120 | } 121 | 122 | public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) { 123 | return this.readAuthenticationForRefreshToken(token.getValue()); 124 | } 125 | 126 | public OAuth2Authentication readAuthenticationForRefreshToken(String token) { 127 | RedisConnection conn = this.getConnection(); 128 | 129 | OAuth2Authentication var5; 130 | try { 131 | byte[] bytes = conn.get(this.serializeKey("refresh_auth:" + token)); 132 | OAuth2Authentication auth = this.deserializeAuthentication(bytes); 133 | var5 = auth; 134 | } finally { 135 | conn.close(); 136 | } 137 | 138 | return var5; 139 | } 140 | 141 | public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { 142 | byte[] serializedAccessToken = this.serialize((Object)token); 143 | byte[] serializedAuth = this.serialize((Object)authentication); 144 | byte[] accessKey = this.serializeKey("access:" + token.getValue()); 145 | byte[] authKey = this.serializeKey("auth:" + token.getValue()); 146 | byte[] authToAccessKey = this.serializeKey("auth_to_access:" + this.authenticationKeyGenerator.extractKey(authentication)); 147 | byte[] approvalKey = this.serializeKey("uname_to_access:" + getApprovalKey(authentication)); 148 | byte[] clientId = this.serializeKey("client_id_to_access:" + authentication.getOAuth2Request().getClientId()); 149 | RedisConnection conn = this.getConnection(); 150 | 151 | try { 152 | conn.openPipeline(); 153 | conn.stringCommands().set(accessKey, serializedAccessToken); 154 | conn.stringCommands().set(authKey, serializedAuth); 155 | conn.stringCommands().set(authToAccessKey, serializedAccessToken); 156 | if (!authentication.isClientOnly()) { 157 | conn.rPush(approvalKey, new byte[][]{serializedAccessToken}); 158 | } 159 | 160 | conn.rPush(clientId, new byte[][]{serializedAccessToken}); 161 | if (token.getExpiration() != null) { 162 | int seconds = token.getExpiresIn(); 163 | conn.expire(accessKey, (long)seconds); 164 | conn.expire(authKey, (long)seconds); 165 | conn.expire(authToAccessKey, (long)seconds); 166 | conn.expire(clientId, (long)seconds); 167 | conn.expire(approvalKey, (long)seconds); 168 | } 169 | 170 | OAuth2RefreshToken refreshToken = token.getRefreshToken(); 171 | if (refreshToken != null && refreshToken.getValue() != null) { 172 | byte[] refresh = this.serialize(token.getRefreshToken().getValue()); 173 | byte[] auth = this.serialize(token.getValue()); 174 | byte[] refreshToAccessKey = this.serializeKey("refresh_to_access:" + token.getRefreshToken().getValue()); 175 | conn.stringCommands().set(refreshToAccessKey, auth); 176 | byte[] accessToRefreshKey = this.serializeKey("access_to_refresh:" + token.getValue()); 177 | conn.stringCommands().set(accessToRefreshKey, refresh); 178 | if (refreshToken instanceof ExpiringOAuth2RefreshToken) { 179 | ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken)refreshToken; 180 | Date expiration = expiringRefreshToken.getExpiration(); 181 | if (expiration != null) { 182 | int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L).intValue(); 183 | conn.expire(refreshToAccessKey, (long)seconds); 184 | conn.expire(accessToRefreshKey, (long)seconds); 185 | } 186 | } 187 | } 188 | 189 | conn.closePipeline(); 190 | } finally { 191 | conn.close(); 192 | } 193 | 194 | } 195 | 196 | private static String getApprovalKey(OAuth2Authentication authentication) { 197 | String userName = authentication.getUserAuthentication() == null ? "" : authentication.getUserAuthentication().getName(); 198 | return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName); 199 | } 200 | 201 | private static String getApprovalKey(String clientId, String userName) { 202 | return clientId + (userName == null ? "" : ":" + userName); 203 | } 204 | 205 | public void removeAccessToken(OAuth2AccessToken accessToken) { 206 | this.removeAccessToken(accessToken.getValue()); 207 | } 208 | 209 | public OAuth2AccessToken readAccessToken(String tokenValue) { 210 | byte[] key = this.serializeKey("access:" + tokenValue); 211 | byte[] bytes = null; 212 | RedisConnection conn = this.getConnection(); 213 | 214 | try { 215 | bytes = conn.get(key); 216 | } finally { 217 | conn.close(); 218 | } 219 | 220 | OAuth2AccessToken var5 = this.deserializeAccessToken(bytes); 221 | return var5; 222 | } 223 | 224 | public void removeAccessToken(String tokenValue) { 225 | byte[] accessKey = this.serializeKey("access:" + tokenValue); 226 | byte[] authKey = this.serializeKey("auth:" + tokenValue); 227 | byte[] accessToRefreshKey = this.serializeKey("access_to_refresh:" + tokenValue); 228 | RedisConnection conn = this.getConnection(); 229 | 230 | try { 231 | conn.openPipeline(); 232 | conn.get(accessKey); 233 | conn.get(authKey); 234 | conn.del(new byte[][]{accessKey}); 235 | conn.del(new byte[][]{accessToRefreshKey}); 236 | conn.del(new byte[][]{authKey}); 237 | List results = conn.closePipeline(); 238 | byte[] access = (byte[])((byte[])results.get(0)); 239 | byte[] auth = (byte[])((byte[])results.get(1)); 240 | OAuth2Authentication authentication = this.deserializeAuthentication(auth); 241 | if (authentication != null) { 242 | String key = this.authenticationKeyGenerator.extractKey(authentication); 243 | byte[] authToAccessKey = this.serializeKey("auth_to_access:" + key); 244 | byte[] unameKey = this.serializeKey("uname_to_access:" + getApprovalKey(authentication)); 245 | byte[] clientId = this.serializeKey("client_id_to_access:" + authentication.getOAuth2Request().getClientId()); 246 | conn.openPipeline(); 247 | conn.del(new byte[][]{authToAccessKey}); 248 | conn.lRem(unameKey, 1L, access); 249 | conn.lRem(clientId, 1L, access); 250 | conn.del(new byte[][]{this.serialize("access:" + key)}); 251 | conn.closePipeline(); 252 | } 253 | } finally { 254 | conn.close(); 255 | } 256 | 257 | } 258 | 259 | public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { 260 | byte[] refreshKey = this.serializeKey("refresh:" + refreshToken.getValue()); 261 | byte[] refreshAuthKey = this.serializeKey("refresh_auth:" + refreshToken.getValue()); 262 | byte[] serializedRefreshToken = this.serialize((Object)refreshToken); 263 | RedisConnection conn = this.getConnection(); 264 | 265 | try { 266 | conn.openPipeline(); 267 | conn.stringCommands().set(refreshKey, serializedRefreshToken); 268 | conn.stringCommands().set(refreshAuthKey, this.serialize((Object)authentication)); 269 | if (refreshToken instanceof ExpiringOAuth2RefreshToken) { 270 | ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken)refreshToken; 271 | Date expiration = expiringRefreshToken.getExpiration(); 272 | if (expiration != null) { 273 | int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L).intValue(); 274 | conn.expire(refreshKey, (long)seconds); 275 | conn.expire(refreshAuthKey, (long)seconds); 276 | } 277 | } 278 | 279 | conn.closePipeline(); 280 | } finally { 281 | conn.close(); 282 | } 283 | 284 | } 285 | 286 | public OAuth2RefreshToken readRefreshToken(String tokenValue) { 287 | byte[] key = this.serializeKey("refresh:" + tokenValue); 288 | byte[] bytes = null; 289 | RedisConnection conn = this.getConnection(); 290 | 291 | try { 292 | bytes = conn.get(key); 293 | } finally { 294 | conn.close(); 295 | } 296 | 297 | OAuth2RefreshToken var5 = this.deserializeRefreshToken(bytes); 298 | return var5; 299 | } 300 | 301 | public void removeRefreshToken(OAuth2RefreshToken refreshToken) { 302 | this.removeRefreshToken(refreshToken.getValue()); 303 | } 304 | 305 | public void removeRefreshToken(String tokenValue) { 306 | byte[] refreshKey = this.serializeKey("refresh:" + tokenValue); 307 | byte[] refreshAuthKey = this.serializeKey("refresh_auth:" + tokenValue); 308 | byte[] refresh2AccessKey = this.serializeKey("refresh_to_access:" + tokenValue); 309 | byte[] access2RefreshKey = this.serializeKey("access_to_refresh:" + tokenValue); 310 | RedisConnection conn = this.getConnection(); 311 | 312 | try { 313 | conn.openPipeline(); 314 | conn.del(new byte[][]{refreshKey}); 315 | conn.del(new byte[][]{refreshAuthKey}); 316 | conn.del(new byte[][]{refresh2AccessKey}); 317 | conn.del(new byte[][]{access2RefreshKey}); 318 | conn.closePipeline(); 319 | } finally { 320 | conn.close(); 321 | } 322 | 323 | } 324 | 325 | public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { 326 | this.removeAccessTokenUsingRefreshToken(refreshToken.getValue()); 327 | } 328 | 329 | private void removeAccessTokenUsingRefreshToken(String refreshToken) { 330 | byte[] key = this.serializeKey("refresh_to_access:" + refreshToken); 331 | List results = null; 332 | RedisConnection conn = this.getConnection(); 333 | 334 | try { 335 | conn.openPipeline(); 336 | conn.get(key); 337 | conn.del(new byte[][]{key}); 338 | results = conn.closePipeline(); 339 | } finally { 340 | conn.close(); 341 | } 342 | 343 | if (results != null) { 344 | byte[] bytes = (byte[])((byte[])results.get(0)); 345 | String accessToken = this.deserializeString(bytes); 346 | if (accessToken != null) { 347 | this.removeAccessToken(accessToken); 348 | } 349 | 350 | } 351 | } 352 | 353 | public Collection findTokensByClientIdAndUserName(String clientId, String userName) { 354 | byte[] approvalKey = this.serializeKey("uname_to_access:" + getApprovalKey(clientId, userName)); 355 | List byteList = null; 356 | RedisConnection conn = this.getConnection(); 357 | 358 | try { 359 | byteList = conn.lRange(approvalKey, 0L, -1L); 360 | } finally { 361 | conn.close(); 362 | } 363 | 364 | if (byteList != null && byteList.size() != 0) { 365 | List accessTokens = new ArrayList(byteList.size()); 366 | Iterator var7 = byteList.iterator(); 367 | 368 | while(var7.hasNext()) { 369 | byte[] bytes = (byte[])var7.next(); 370 | OAuth2AccessToken accessToken = this.deserializeAccessToken(bytes); 371 | accessTokens.add(accessToken); 372 | } 373 | 374 | return Collections.unmodifiableCollection(accessTokens); 375 | } else { 376 | return Collections.emptySet(); 377 | } 378 | } 379 | 380 | public Collection findTokensByClientId(String clientId) { 381 | byte[] key = this.serializeKey("client_id_to_access:" + clientId); 382 | List byteList = null; 383 | RedisConnection conn = this.getConnection(); 384 | 385 | try { 386 | byteList = conn.lRange(key, 0L, -1L); 387 | } finally { 388 | conn.close(); 389 | } 390 | 391 | if (byteList != null && byteList.size() != 0) { 392 | List accessTokens = new ArrayList(byteList.size()); 393 | Iterator var6 = byteList.iterator(); 394 | 395 | while(var6.hasNext()) { 396 | byte[] bytes = (byte[])var6.next(); 397 | OAuth2AccessToken accessToken = this.deserializeAccessToken(bytes); 398 | accessTokens.add(accessToken); 399 | } 400 | 401 | return Collections.unmodifiableCollection(accessTokens); 402 | } else { 403 | return Collections.emptySet(); 404 | } 405 | } 406 | } 407 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | * **master分支是当前文章的项目** 3 | * **master-jdbc分支 是在master基础上以mysql数据库的实现** 4 | * **master-jwt分支 是在oauth2 jwt的实现** 5 | 6 | * 二、[Spring Cloud OAuth2 token存数据库实现](https://www.jianshu.com/p/4ce5577bab74) 7 | * 三、[Spring Cloud Oauth2 JWT 实现](https://www.jianshu.com/p/402bda62a7c3) 8 | 9 | 学习一下Spring Cloud OAuth2,我们分三个项目 eureka-server、service-auth、service-hi 10 | 11 | ![g9.png](https://upload-images.jianshu.io/upload_images/2151905-98b8ab75251c922d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 12 | 13 | 14 | # 1. 创建eureka-server项目 15 | 选择依赖 **spring-cloud-starter-netflix-eureka-server** 16 | ## 1.1 启动类里添加注释 17 | ``` java 18 | @SpringBootApplication 19 | @EnableEurekaServer 20 | public class EurekaServerApplication { 21 | 22 | public static void main(String[] args) { 23 | SpringApplication.run(EurekaServerApplication.class, args); 24 | } 25 | } 26 | ``` 27 | ## 1.2 application.yml 28 | ``` xml 29 | spring: 30 | application: 31 | name: eureka-server 32 | server: 33 | port: 8761 34 | eureka: 35 | instance: 36 | hostname: localhost 37 | client: 38 | service-url: 39 | defaultZone: http://localhost:8761/eureka/ 40 | fetch-registry: false 41 | register-with-eureka: false 42 | ``` 43 | 配置完成可以访问 http://localhost:8761 44 | 45 | #2 创建service-auth项目 46 | ## 2.1 用于获取授权token,项目上目录结构: 47 | ![g4.png](https://upload-images.jianshu.io/upload_images/2151905-82f360b00e6ae1c2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 48 | 49 | > 这里有个有趣的地方,如果包名config和customImpl和启动类不在同一个根包下,会扫不到包,此时必须在启动类上增加 ``` @ComponentScan(basePackages = "包名") ``` 50 | 51 | ##2.2 创建项目依赖 52 | + **spring-boot-starter-data-redis** 把token存到redis中 53 | + **spring-cloud-starter-netflix-eureka-client** 做为EurekaClient 54 | + **spring-cloud-starter-oauth2** 是对spring-cloud-starter-security、spring-security-oauth2、spring-security-jwt这3个依赖的整合 55 | + **spring-boot-starter-actuator** 56 | 57 | 完整pom.xml 58 | ```xml 59 | 60 | 62 | 4.0.0 63 | 64 | com.uaa.service 65 | uaa-service 66 | 0.0.1-SNAPSHOT 67 | jar 68 | 69 | uaa-service 70 | Demo project for Spring Boot 71 | 72 | 73 | org.springframework.boot 74 | spring-boot-starter-parent 75 | 2.0.4.RELEASE 76 | 77 | 78 | 79 | 80 | UTF-8 81 | UTF-8 82 | 1.8 83 | Finchley.SR1 84 | 85 | 86 | 87 | 88 | org.springframework.boot 89 | spring-boot-starter-actuator 90 | 91 | 92 | org.springframework.boot 93 | spring-boot-starter-data-redis 94 | 95 | 96 | org.springframework.cloud 97 | spring-cloud-starter-netflix-eureka-client 98 | 99 | 100 | org.springframework.cloud 101 | spring-cloud-starter-oauth2 102 | 103 | 104 | 105 | org.springframework.boot 106 | spring-boot-starter-test 107 | test 108 | 109 | 110 | 111 | 112 | 113 | 114 | org.springframework.cloud 115 | spring-cloud-dependencies 116 | ${spring-cloud.version} 117 | pom 118 | import 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | org.springframework.boot 127 | spring-boot-maven-plugin 128 | 129 | 130 | 131 | 132 | 133 | 134 | ``` 135 | ## 2.3 application.yml 136 | ```xml 137 | spring: 138 | application: 139 | name: service-auth 140 | redis: 141 | host: 172.16.10.43 142 | database: 0 143 | server: 144 | port: 9098 145 | eureka: 146 | client: 147 | service-url: 148 | defaultZone: http://localhost:8761/eureka/ 149 | ``` 150 | application.yml中配置redis、注册中心 151 | 接下来分别继承 **AuthorizationServerConfigurerAdapter**和**WebSecurityConfigurerAdapter** 152 | + AuthorizationServerConfigurerAdapter 类中3个不同的configure方法分别 153 | + configure(ClientDetailsServiceConfigurer clients) 用来配置客户端详情服务(ClientDetailsService),客户端详情信息在这里进行初始化,你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息; 154 | + configure(AuthorizationServerEndpointsConfigurer endpoints) 用来配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services),还有token的存储方式(tokenStore); 155 | + configure(AuthorizationServerSecurityConfigurer security) 用来配置令牌端点(Token Endpoint)的安全约束; 156 | + WebSecurityConfigurerAdapter 157 | + configure(HttpSecurity http) httpSecurity中配置所有请求的安全验证 158 | + 注入Bean UserDetailsService 159 | + 注入Bean AuthenticationManager 用来做验证 160 | + 注入Bean PasswordEncoder 161 | 162 | ## 2.4 AuthorizationServerConfiguration继承AuthorizationServerConfigurerAdapter 163 | ``` java 164 | @Configuration 165 | @EnableAuthorizationServer 166 | public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { 167 | @Autowired 168 | AuthenticationManager authenticationManager; 169 | 170 | @Autowired 171 | RedisConnectionFactory redisConnectionFactory; 172 | 173 | @Override 174 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 175 | String finalSecret = "{bcrypt}" + new BCryptPasswordEncoder().encode("123456"); 176 | 177 | // 配置两个客户端,一个用于password认证一个用于client认证 178 | clients.inMemory().withClient("client_1") 179 | .resourceIds(Utils.RESOURCEIDS.ORDER) 180 | .authorizedGrantTypes("client_credentials", "refresh_token") 181 | .scopes("select") 182 | .authorities("oauth2") 183 | .secret(finalSecret) 184 | .and().withClient("client_2") 185 | .resourceIds(Utils.RESOURCEIDS.ORDER) 186 | .authorizedGrantTypes("password", "refresh_token") 187 | .scopes("server") 188 | .authorities("oauth2") 189 | .secret(finalSecret); 190 | } 191 | 192 | @Override 193 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 194 | endpoints.tokenStore(new MyRedisTokenStore(redisConnectionFactory)) 195 | .authenticationManager(authenticationManager) 196 | .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); 197 | } 198 | 199 | @Override 200 | public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { 201 | // 允许表单认证 202 | security.allowFormAuthenticationForClients(); 203 | } 204 | } 205 | 206 | 207 | ``` 208 | ##2.5 SecurityConfiguration 继承 WebSecurityConfigurerAdapter 209 | ``` java 210 | @Configuration 211 | @EnableWebSecurity 212 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 213 | @Bean 214 | @Override 215 | protected UserDetailsService userDetailsService() { 216 | BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); 217 | 218 | String finalPassword = "{bcrypt}"+bCryptPasswordEncoder.encode("123456"); 219 | InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); 220 | manager.createUser(User.withUsername("user_1").password(finalPassword).authorities("USER").build()); 221 | manager.createUser(User.withUsername("user_2").password(finalPassword).authorities("USER").build()); 222 | 223 | return manager; 224 | } 225 | 226 | @Bean 227 | PasswordEncoder passwordEncoder() { 228 | return PasswordEncoderFactories.createDelegatingPasswordEncoder(); 229 | } 230 | 231 | @Bean 232 | @Override 233 | public AuthenticationManager authenticationManagerBean() throws Exception { 234 | AuthenticationManager manager = super.authenticationManagerBean(); 235 | return manager; 236 | } 237 | 238 | @Override 239 | protected void configure(HttpSecurity http) throws Exception { 240 | http.requestMatchers().anyRequest() 241 | .and() 242 | .authorizeRequests() 243 | .antMatchers("/oauth/**").permitAll(); 244 | } 245 | } 246 | 247 | ``` 248 | 249 | > 这里在内在中创建了两个用户user_1和user_2,后续会以存mysql数据的方式来完善。 250 | 251 | ##2.6 暴露Remote Token Services 接口 252 | 采用RemoteTokenServices这种方式对token进行验证,如果其他资源服务需要验证token,则需要远程调用授权服务暴露的验证token的api接口,验证token的API接口代码如下: 253 | 254 | ``` java 255 | @RestController 256 | @RequestMapping("/users") 257 | public class UserController { 258 | 259 | Logger logger = LoggerFactory.getLogger(UserController.class); 260 | 261 | @RequestMapping(value = "/current", method = RequestMethod.GET) 262 | public Principal getUser(Principal principal) { 263 | logger.info(">>>>>>>>>>>>>>>>>>>>>>>>"); 264 | logger.info(principal.toString()); 265 | logger.info(">>>>>>>>>>>>>>>>>>>>>>>>"); 266 | return principal; 267 | } 268 | } 269 | 270 | ``` 271 | 272 | 273 | ##2.7 启动类 274 | ``` java 275 | @SpringBootApplication 276 | @EnableResourceServer 277 | @EnableEurekaClient 278 | public class ServiceAuthApplication { 279 | 280 | public static void main(String[] args) { 281 | SpringApplication.run(ServiceAuthApplication.class, args); 282 | } 283 | } 284 | ``` 285 | > 启动类上加上EnableResourceServer注解开启资源服务,因为程序需要对外暴露获取token的API和验证token的API所以该程序也是一个资源服务器。 286 | 287 | *到此,授权服务已经配置完成,可以访问,认证类型以password方式* 288 | 289 | ![g2.png](https://upload-images.jianshu.io/upload_images/2151905-1fb916316cb390c5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 290 | 291 | # 3. 创建资源服务器 service-hi 292 | 创建项目的依赖 spring-cloud-starter-openfeign、spring-cloud-starter-oauth2、spring-cloud-starter-netflix-eureka-client、spring-boot-starter-web 293 | ## 3.1 以下是完整pom.xml 294 | ``` xml 295 | 296 | 298 | 4.0.0 299 | 300 | com.service.hi 301 | service-hi 302 | 0.0.1-SNAPSHOT 303 | jar 304 | 305 | service-hi 306 | Demo project for Spring Boot 307 | 308 | 309 | org.springframework.boot 310 | spring-boot-starter-parent 311 | 2.0.4.RELEASE 312 | 313 | 314 | 315 | 316 | UTF-8 317 | UTF-8 318 | 1.8 319 | Finchley.SR1 320 | 321 | 322 | 323 | 324 | org.springframework.boot 325 | spring-boot-starter-web 326 | 327 | 328 | org.springframework.cloud 329 | spring-cloud-starter-netflix-eureka-client 330 | 331 | 332 | org.springframework.cloud 333 | spring-cloud-starter-oauth2 334 | 335 | 336 | org.springframework.cloud 337 | spring-cloud-starter-openfeign 338 | 339 | 340 | 341 | org.springframework.boot 342 | spring-boot-starter-test 343 | test 344 | 345 | 346 | 347 | 348 | 349 | 350 | org.springframework.cloud 351 | spring-cloud-dependencies 352 | ${spring-cloud.version} 353 | pom 354 | import 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | org.springframework.boot 363 | spring-boot-maven-plugin 364 | 365 | 366 | 367 | 368 | 369 | 370 | ``` 371 | 372 | ## 3.2 配置文件 application.yml 373 | ``` xml 374 | eureka: 375 | client: 376 | service-url: 377 | defaultZone: http://localhost:8761/eureka/ 378 | server: 379 | port: 8765 380 | spring: 381 | application: 382 | name: service-hi 383 | security: 384 | oauth2: 385 | resource: 386 | user-info-uri: http://localhost:9098/users/current 387 | client: 388 | id: client_2 389 | client-secret: 123456 390 | access-token-uri: http://localhost:9098/oauth/token 391 | grant-type: client_credentials,password 392 | scope: server 393 | ``` 394 | > security.oauth2.resource.user-info-uri用于获取当前token的用户信息,配置security.oauth2.client的相关信息以及clientId、client-secret等信息要和service-auth中的配置一一对应。 395 | 396 | ## 3.3 配置Resource Server 397 | ``` java 398 | @Configuration 399 | @EnableResourceServer 400 | @EnableGlobalMethodSecurity(prePostEnabled = true) 401 | public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { 402 | 403 | 404 | @Override 405 | public void configure(HttpSecurity http) throws Exception { 406 | http.authorizeRequests() 407 | .antMatchers("/order/**").authenticated(); // 配置order访问控制,必须认证后才可以访问 408 | } 409 | } 410 | ``` 411 | > 添加EnableResourceServer注解开启资源服务的功能,加注解EnableGlobalMethodSecurity开户方法级别的保护,ResourceServerConfigurerAdapter是配置类,configure(HttpSecurity http)中只配置了"/order/**"需要验证。 412 | 413 | ## 3.4 配置OAuth2 Client 414 | OAuth2 client用来访问被OAuth2保护的资源,service-hi作为OAuth2 Client,配置如下: 415 | ``` java 416 | @EnableOAuth2Client 417 | @EnableConfigurationProperties 418 | @Configuration 419 | public class OAuth2ClientConfig { 420 | 421 | @Bean 422 | @ConfigurationProperties(prefix = "security.oauth2.client") 423 | public ClientCredentialsResourceDetails clientCredentialsResourceDetails() { 424 | return new ClientCredentialsResourceDetails(); 425 | } 426 | 427 | @Bean 428 | public RequestInterceptor oauth2FeignRequestInterceptor() { 429 | return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), clientCredentialsResourceDetails()); 430 | } 431 | 432 | @Bean 433 | public OAuth2RestTemplate clientCredentialsRestTemplate() { 434 | return new OAuth2RestTemplate(clientCredentialsResourceDetails()); 435 | } 436 | } 437 | ``` 438 | > 注解EnableOAuth2Client开启了OAuth2 Client功能,注入一个OAuth2RestTemplate 类型的Bean用于向service-auth服务请求。 439 | ## 3.5 写一个端点测试Controller TestEndPointController 440 | ``` java 441 | @RestController 442 | public class TestEndPointController { 443 | 444 | Logger logger = LoggerFactory.getLogger(TestEndPointController.class); 445 | 446 | @GetMapping("/product/{id}") 447 | public String getProduct(@PathVariable String id) { 448 | return "product id : " + id; 449 | } 450 | 451 | @GetMapping("/order/{id}") 452 | public String getOrder(@PathVariable String id) { 453 | return "order id : " + id; 454 | } 455 | 456 | @GetMapping("/getPrinciple") 457 | public OAuth2Authentication getPrinciple(OAuth2Authentication oAuth2Authentication, Principal principal, Authentication authentication) { 458 | logger.info(oAuth2Authentication.getUserAuthentication().getAuthorities().toString()); 459 | logger.info(oAuth2Authentication.toString()); 460 | logger.info("principal.toString() " + principal.toString()); 461 | logger.info("principal.getName() " + principal.getName()); 462 | logger.info("authentication: " + authentication.getAuthorities().toString()); 463 | 464 | return oAuth2Authentication; 465 | } 466 | } 467 | ``` 468 | ## 3.6 启动类 469 | ``` java 470 | @SpringBootApplication 471 | @EnableEurekaClient 472 | public class ServiceHiApplication { 473 | 474 | public static void main(String[] args) { 475 | SpringApplication.run(ServiceHiApplication.class, args); 476 | } 477 | } 478 | ``` 479 | 到此资源服务的配置也完成,我们可以测试,依次启动 eureka-server、service-auth、service-hi 480 | 访问http://localhost:8761 481 | ![g7.png](https://upload-images.jianshu.io/upload_images/2151905-75e9f3ced3a578b8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/850) 482 | 483 | 访问oauth/token获取token信息 get方式请求: 484 | 485 | http://localhost:9098/oauth/token?username=user_1&password=123456&grant_type=password&scope=server&client_id=client_2&client_secret=123456 486 | 487 | 也可以使用postman用post方式访问。 488 | 请求结果: 489 | ``` json 490 | { 491 | "access_token": "e9a93dff-fd58-4af3-b458-01fbb6079416", 492 | "token_type": "bearer", 493 | "refresh_token": "f31290cf-f421-49ba-8112-95a1a2fe9f09", 494 | "expires_in": 40172, 495 | "scope": "server" 496 | } 497 | ``` 498 | 这时候如果访问service-hi的http://localhost:8765/order/1 不带token信息: 499 | ``` json 500 | { 501 | "error": "unauthorized", 502 | "error_description": "Full authentication is required to access this resource" 503 | } 504 | ``` 505 | 告诉你,没有权限访问该资源 506 | 507 | 正确的访问姿势: 508 | 可以是以url参数形式 http://localhost:8765/order/1?access_token=e9a93dff-fd58-4af3-b458-01fbb6079416 509 | 也可以是headers 的authorization中 bearer token 形式 510 | ![g8.png](https://upload-images.jianshu.io/upload_images/2151905-f24eb03adf19d26d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/850) 511 | 512 | 不需要验证的资源product http://localhost:8765/product/1 513 | ``` 514 | product id : 1 515 | ``` 516 | getPrinciple打印出验证信息 http://localhost:8765/getPrinciple : 517 | ``` json 518 | { 519 | "authorities": [ 520 | { 521 | "authority": "USER" 522 | } 523 | ], 524 | "details": { 525 | "remoteAddress": "0:0:0:0:0:0:0:1", 526 | "sessionId": "8F2D30BA614CA41B6AA03D2A4650EA3E", 527 | "tokenValue": "e9a93dff-fd58-4af3-b458-01fbb6079416", 528 | "tokenType": "Bearer", 529 | "decodedDetails": null 530 | }, 531 | "authenticated": true, 532 | "userAuthentication": { 533 | "authorities": [ 534 | { 535 | "authority": "USER" 536 | } 537 | ], 538 | "details": { 539 | "authorities": [ 540 | { 541 | "authority": "USER" 542 | } 543 | ], 544 | "details": { 545 | "remoteAddress": "127.0.0.1", 546 | "sessionId": null, 547 | "tokenValue": "e9a93dff-fd58-4af3-b458-01fbb6079416", 548 | "tokenType": "Bearer", 549 | "decodedDetails": null 550 | }, 551 | "authenticated": true, 552 | "userAuthentication": { 553 | "authorities": [ 554 | { 555 | "authority": "USER" 556 | } 557 | ], 558 | "details": { 559 | "grant_type": "password", 560 | "scope": "server", 561 | "client_secret": "123456", 562 | "client_id": "client_2", 563 | "username": "user_1" 564 | }, 565 | "authenticated": true, 566 | "principal": { 567 | "password": null, 568 | "username": "user_1", 569 | "authorities": [ 570 | { 571 | "authority": "USER" 572 | } 573 | ], 574 | "accountNonExpired": true, 575 | "accountNonLocked": true, 576 | "credentialsNonExpired": true, 577 | "enabled": true 578 | }, 579 | "credentials": null, 580 | "name": "user_1" 581 | }, 582 | "oauth2Request": { 583 | "clientId": "client_2", 584 | "scope": [ 585 | "server" 586 | ], 587 | "requestParameters": { 588 | "grant_type": "password", 589 | "scope": "server", 590 | "client_id": "client_2", 591 | "username": "user_1" 592 | }, 593 | "resourceIds": [], 594 | "authorities": [ 595 | { 596 | "authority": "oauth2" 597 | } 598 | ], 599 | "approved": true, 600 | "refresh": false, 601 | "redirectUri": null, 602 | "responseTypes": [], 603 | "extensions": {}, 604 | "grantType": "password", 605 | "refreshTokenRequest": null 606 | }, 607 | "principal": { 608 | "password": null, 609 | "username": "user_1", 610 | "authorities": [ 611 | { 612 | "authority": "USER" 613 | } 614 | ], 615 | "accountNonExpired": true, 616 | "accountNonLocked": true, 617 | "credentialsNonExpired": true, 618 | "enabled": true 619 | }, 620 | "credentials": "", 621 | "clientOnly": false, 622 | "name": "user_1" 623 | }, 624 | "authenticated": true, 625 | "principal": "user_1", 626 | "credentials": "N/A", 627 | "name": "user_1" 628 | }, 629 | "clientOnly": false, 630 | "principal": "user_1", 631 | "credentials": "", 632 | "oauth2Request": { 633 | "clientId": null, 634 | "scope": [], 635 | "requestParameters": {}, 636 | "resourceIds": [], 637 | "authorities": [], 638 | "approved": true, 639 | "refresh": false, 640 | "redirectUri": null, 641 | "responseTypes": [], 642 | "extensions": {}, 643 | "grantType": null, 644 | "refreshTokenRequest": null 645 | }, 646 | "name": "user_1" 647 | } 648 | ``` 649 | 650 | --------------------------------------------------------------------------------