diff --git a/consul/consul-oauth-client/pom.xml b/consul/consul-oauth-client/pom.xml new file mode 100644 index 0000000..4651db6 --- /dev/null +++ b/consul/consul-oauth-client/pom.xml @@ -0,0 +1,90 @@ + + + + + consul + kite.springcloud + 1.0-SNAPSHOT + + 4.0.0 + + kite.springcloud + consul-oauth-client + + consul-oauth-client + + + UTF-8 + 1.8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-oauth2 + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + io.jsonwebtoken + jjwt + 0.9.1 + + + + + + + + + maven-clean-plugin + 3.1.0 + + + + maven-resources-plugin + 3.0.2 + + + maven-compiler-plugin + 3.8.0 + + + maven-surefire-plugin + 2.22.1 + + + maven-jar-plugin + 3.0.2 + + + maven-install-plugin + 2.5.2 + + + maven-deploy-plugin + 2.8.2 + + + + maven-site-plugin + 3.7.1 + + + maven-project-info-reports-plugin + 3.0.0 + + + + + diff --git a/consul/consul-oauth-client/src/main/java/kite/springcloud/consul/oauth/client/Application.java b/consul/consul-oauth-client/src/main/java/kite/springcloud/consul/oauth/client/Application.java new file mode 100644 index 0000000..9d1543b --- /dev/null +++ b/consul/consul-oauth-client/src/main/java/kite/springcloud/consul/oauth/client/Application.java @@ -0,0 +1,18 @@ +package kite.springcloud.consul.oauth.client; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +/** + * 启动类 + * @author 故事的风筝 + */ +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/consul/consul-oauth-client/src/main/java/kite/springcloud/consul/oauth/client/config/ResourceServerConfig.java b/consul/consul-oauth-client/src/main/java/kite/springcloud/consul/oauth/client/config/ResourceServerConfig.java new file mode 100644 index 0000000..18b279f --- /dev/null +++ b/consul/consul-oauth-client/src/main/java/kite/springcloud/consul/oauth/client/config/ResourceServerConfig.java @@ -0,0 +1,47 @@ +package kite.springcloud.consul.oauth.client.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; +import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; + +/** + * SecurityConfig + * + * @author fengzheng + * @date 2019/10/11 + */ +@Configuration +@EnableResourceServer +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class ResourceServerConfig extends ResourceServerConfigurerAdapter { + + @Bean + public TokenStore jwtTokenStore() { + return new JwtTokenStore(jwtAccessTokenConverter()); + } + + @Bean + public JwtAccessTokenConverter jwtAccessTokenConverter() { + JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter(); + + accessTokenConverter.setSigningKey("dev"); + accessTokenConverter.setVerifierKey("dev"); + return accessTokenConverter; + } + + @Autowired + private TokenStore jwtTokenStore; + + @Override + public void configure(ResourceServerSecurityConfigurer resources) throws Exception { + resources.tokenStore(jwtTokenStore); + } + +} diff --git a/consul/consul-oauth-client/src/main/java/kite/springcloud/consul/oauth/client/controller/ClientController.java b/consul/consul-oauth-client/src/main/java/kite/springcloud/consul/oauth/client/controller/ClientController.java new file mode 100644 index 0000000..045d4d5 --- /dev/null +++ b/consul/consul-oauth-client/src/main/java/kite/springcloud/consul/oauth/client/controller/ClientController.java @@ -0,0 +1,44 @@ +package kite.springcloud.consul.oauth.client.controller; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.nio.charset.StandardCharsets; + +/** + * OrderController + * + * @author fengzheng + * @date 2019/10/11 + */ +@Slf4j +@RestController +public class ClientController { + + @GetMapping(value = "get") + //@PreAuthorize("hasAuthority('ROLE_ADMIN')") + @PreAuthorize("hasAnyRole('ROLE_ADMIN')") + public Object get(Authentication authentication){ + //Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + authentication.getCredentials(); + OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails(); + String jwtToken = details.getTokenValue(); + Claims claims = Jwts.parser() + .setSigningKey("dev".getBytes(StandardCharsets.UTF_8)) + .parseClaimsJws(jwtToken) + .getBody(); + return claims; + //return "给你"; + } + + @GetMapping(value = "test") + public String test(){ + return "success"; + } +} diff --git a/consul/consul-oauth-client/src/main/resources/application.yml b/consul/consul-oauth-client/src/main/resources/application.yml new file mode 100644 index 0000000..b3c1763 --- /dev/null +++ b/consul/consul-oauth-client/src/main/resources/application.yml @@ -0,0 +1,42 @@ +spring: + application: + name: consul-oauth-client +# redis: +# database: 2 +# host: localhost +# port: 32768 +# password: 1qaz@WSX +# jedis: +# pool: +# max-active: 8 +# max-idle: 8 +# min-idle: 0 +# timeout: 100ms + cloud: + consul: + discovery: + service-name: consul-oauth-client + host: localhost + port: 8500 + +server: + port: 5012 + servlet: + context-path: /consul-oauth-client + +security: + oauth2: + client: + client-id: user-client + client-secret: user-secret-8888 + user-authorization-uri: http://localhost:5010/oauth/authorize + access-token-uri: http://localhost:5010/oauth/token +# resource: +# id: user-client +# user-info-uri: user-info +# authorization: +# check-token-access: http://localhost:6001/oauth/check_token + resource: + jwt: + key-uri: http://localhost:5010/oauth/token_key + key-value: dev diff --git a/consul/consul-oauth-server/pom.xml b/consul/consul-oauth-server/pom.xml new file mode 100644 index 0000000..bb2407a --- /dev/null +++ b/consul/consul-oauth-server/pom.xml @@ -0,0 +1,100 @@ + + + + + consul + kite.springcloud + 1.0-SNAPSHOT + + 4.0.0 + + kite.springcloud + consul-oauth-server + + consul-oauth-server + + + UTF-8 + 1.8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.cloud + spring-cloud-starter-oauth2 + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + org.springframework.boot + spring-boot-starter-actuator + + + + mysql + mysql-connector-java + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + + + + + + maven-clean-plugin + 3.1.0 + + + + maven-resources-plugin + 3.0.2 + + + maven-compiler-plugin + 3.8.0 + + + maven-surefire-plugin + 2.22.1 + + + maven-jar-plugin + 3.0.2 + + + maven-install-plugin + 2.5.2 + + + maven-deploy-plugin + 2.8.2 + + + + maven-site-plugin + 3.7.1 + + + maven-project-info-reports-plugin + 3.0.0 + + + + + diff --git a/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/Application.java b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/Application.java new file mode 100644 index 0000000..8371ba1 --- /dev/null +++ b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/Application.java @@ -0,0 +1,18 @@ +package kite.springcloud.consul.oauth.server; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +/** + * 启动类 + * @author 故事的风筝 + */ +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/JWTokenEnhancer.java b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/JWTokenEnhancer.java new file mode 100644 index 0000000..5038288 --- /dev/null +++ b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/JWTokenEnhancer.java @@ -0,0 +1,26 @@ +package kite.springcloud.consul.oauth.server.config; + +import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.security.oauth2.provider.OAuth2Authentication; +import org.springframework.security.oauth2.provider.token.TokenEnhancer; + +import java.util.HashMap; +import java.util.Map; + +/** + * JWTokenEnhancer + * + * @author fengzheng + * @date 2019/10/12 + */ +public class JWTokenEnhancer implements TokenEnhancer { + + @Override + public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) { + Map info = new HashMap<>(); + info.put("jwt-ext", "JWT 扩展信息"); + ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info); + return oAuth2AccessToken; + } +} diff --git a/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/JwtTokenConfig.java b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/JwtTokenConfig.java new file mode 100644 index 0000000..e05c7ee --- /dev/null +++ b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/JwtTokenConfig.java @@ -0,0 +1,35 @@ +package kite.springcloud.consul.oauth.server.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.provider.token.TokenEnhancer; +import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; +import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; + +/** + * JwtTokenConfig + * + * @author fengzheng + * @date 2019/10/12 + */ +@Configuration +public class JwtTokenConfig { + + @Bean + public TokenStore jwtTokenStore() { + return new JwtTokenStore(jwtAccessTokenConverter()); + } + + @Bean + public JwtAccessTokenConverter jwtAccessTokenConverter() { + JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter(); + accessTokenConverter.setSigningKey("dev"); + return accessTokenConverter; + } + + @Bean + public TokenEnhancer jwtTokenEnhancer(){ + return new JWTokenEnhancer(); + } +} diff --git a/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/KiteUserDetailsService.java b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/KiteUserDetailsService.java new file mode 100644 index 0000000..7ef35cb --- /dev/null +++ b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/KiteUserDetailsService.java @@ -0,0 +1,59 @@ +package kite.springcloud.consul.oauth.server.config; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy; +import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; + +/** + * KiteUserDetailsService + * + * @author fengzheng 古时的风筝 + * @date 2019/3/30 + */ +@Slf4j +@Component(value = "kiteUserDetailsService") +public class KiteUserDetailsService implements UserDetailsService { + + + @Autowired + private PasswordEncoder passwordEncoder; + + private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy(); + + @Autowired + private TokenStore redisTokenStore; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + log.info("usernameis:" + username); + // 查询数据库操作 + if(!username.equals("admin")){ + throw new UsernameNotFoundException("the user is not found"); + }else{ + // 用户角色也应在数据库中获取 + String role = "ROLE_ADMIN"; + List authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(role)); + // 线上环境应该通过用户名查询数据库获取加密后的密码 + String password = passwordEncoder.encode("123456"); + // 返回默认的 User + // return new org.springframework.security.core.userdetails.User(username,password, authorities); + + // 返回自定义的 KiteUserDetails + User user = new User(username,password,authorities); + return user; + } + } +} diff --git a/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/OAuth2Config.java b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/OAuth2Config.java new file mode 100644 index 0000000..edbca1c --- /dev/null +++ b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/OAuth2Config.java @@ -0,0 +1,113 @@ +package kite.springcloud.consul.oauth.server.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.token.TokenEnhancer; +import org.springframework.security.oauth2.provider.token.TokenEnhancerChain; +import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; + +import javax.sql.DataSource; +import java.util.ArrayList; +import java.util.List; + +@Configuration +@EnableAuthorizationServer +public class OAuth2Config extends AuthorizationServerConfigurerAdapter { + + @Autowired + public PasswordEncoder passwordEncoder; + + @Autowired + public UserDetailsService kiteUserDetailsService; + + @Autowired + private AuthenticationManager authenticationManager; + +// @Autowired +// private TokenStore redisTokenStore; + + @Autowired + private DataSource dataSource; + + @Autowired + private TokenStore jwtTokenStore; + + @Autowired + private JwtAccessTokenConverter jwtAccessTokenConverter; + + @Autowired + private TokenEnhancer jwtTokenEnhancer; + + @Override + public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception { + /** + * 普通 jwt 模式 + */ +// endpoints.tokenStore(jwtTokenStore) +// .accessTokenConverter(jwtAccessTokenConverter) +// .userDetailsService(kiteUserDetailsService) +// /** +// * 支持 password 模式 +// */ +// .authenticationManager(authenticationManager); + + /** + * jwt 增强模式 + */ + TokenEnhancerChain enhancerChain = new TokenEnhancerChain(); + List enhancerList = new ArrayList<>(); + enhancerList.add(jwtTokenEnhancer); + enhancerList.add(jwtAccessTokenConverter); + enhancerChain.setTokenEnhancers(enhancerList); + endpoints.tokenStore(jwtTokenStore) + .userDetailsService(kiteUserDetailsService) + /** + * 支持 password 模式 + */ + .authenticationManager(authenticationManager) + .tokenEnhancer(enhancerChain) + .accessTokenConverter(jwtAccessTokenConverter); + + /** + * redis token 方式 + */ +// endpoints.authenticationManager(authenticationManager) +// .tokenStore(redisTokenStore) +// .userDetailsService(kiteUserDetailsService); + + } + + @Override + public void configure(ClientDetailsServiceConfigurer clients) throws Exception { + clients.jdbc(dataSource); + +// clients.inMemory() +// .withClient("order-client") +// .secret(passwordEncoder.encode("order-secret-8888")) +// .authorizedGrantTypes("refresh_token", "authorization_code", "password") +// .accessTokenValiditySeconds(3600) +// .scopes("all") +// .and() +// .withClient("user-client") +// .secret(passwordEncoder.encode("user-secret-8888")) +// .authorizedGrantTypes("refresh_token", "authorization_code", "password") +// .accessTokenValiditySeconds(3600) +// .scopes("all"); + } + + @Override + public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { + security.allowFormAuthenticationForClients(); + security.checkTokenAccess("isAuthenticated()"); + security.tokenKeyAccess("isAuthenticated()"); + } +} \ No newline at end of file diff --git a/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/RedisTokenStoreConfig.java b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/RedisTokenStoreConfig.java new file mode 100644 index 0000000..76d274c --- /dev/null +++ b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/RedisTokenStoreConfig.java @@ -0,0 +1,26 @@ +package kite.springcloud.consul.oauth.server.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; + +/** + * RedisTokenStoreConfig + * + * @author fengzheng + * @date 2019/10/14 + */ +@Configuration +public class RedisTokenStoreConfig { + + @Autowired + private RedisConnectionFactory redisConnectionFactory; + + @Bean + public TokenStore redisTokenStore (){ + return new RedisTokenStore(redisConnectionFactory); + } +} diff --git a/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/WebSecurityConfig.java b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/WebSecurityConfig.java new file mode 100644 index 0000000..394a7a9 --- /dev/null +++ b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/config/WebSecurityConfig.java @@ -0,0 +1,43 @@ +package kite.springcloud.consul.oauth.server.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +/** + * WebSecurityConfig + * + * @author fengzheng + * @date 2019/10/10 + */ +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + /** + * 允许匿名访问所有接口 主要是 oauth 接口 + * @param http + * @throws Exception + */ + @Override + protected void configure(HttpSecurity http) throws Exception { + http.formLogin() + .and() + .authorizeRequests() + .antMatchers("/**").permitAll(); + } +} diff --git a/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/controller/HelloController.java b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/controller/HelloController.java new file mode 100644 index 0000000..bf76685 --- /dev/null +++ b/consul/consul-oauth-server/src/main/java/kite/springcloud/consul/oauth/server/controller/HelloController.java @@ -0,0 +1,29 @@ +package kite.springcloud.consul.oauth.server.controller; + +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * HelloController + * + * @author fengzheng + * @date 2019/10/18 + */ +@RestController +@RequestMapping(value = "hello") +public class HelloController { + + @GetMapping(value = "get") + public String getUserInfo(){ + + return "hello"; + } + public static void main(String[] args){ + System.out.println(new BCryptPasswordEncoder().encode("user-secret-8888")); + System.out.println(new BCryptPasswordEncoder().encode("client-secret-8888")); + System.out.println(new BCryptPasswordEncoder().encode("code-secret-8888")); + } + +} diff --git a/consul/consul-oauth-server/src/main/resources/application.yml b/consul/consul-oauth-server/src/main/resources/application.yml new file mode 100644 index 0000000..63aa1a0 --- /dev/null +++ b/consul/consul-oauth-server/src/main/resources/application.yml @@ -0,0 +1,44 @@ +spring: + application: + name: consul-oauth-server + datasource: + url: jdbc:mysql://localhost:3306/spring_cloud?characterEncoding=UTF-8&useSSL=false + username: root + password: P@ssw0rd + hikari: + connection-timeout: 30000 + idle-timeout: 600000 + max-lifetime: 1800000 + maximum-pool-size: 9 +# redis: +# database: 2 +# host: localhost +# port: 32768 +# password: 1qaz@WSX +# jedis: +# pool: +# max-active: 8 +# max-idle: 8 +# min-idle: 0 +# timeout: 100ms + cloud: + consul: + discovery: + service-name: consul-oauth-server + host: localhost + port: 8500 + +server: + port: 5010 + servlet: + context-path: /oauth-service + +management: + endpoint: + health: + enabled: true + show-details: always + server: + port: 15015 + + diff --git a/consul/consul-user/src/main/java/kite/springcloud/consul/user/controller/UserController.java b/consul/consul-user/src/main/java/kite/springcloud/consul/user/controller/UserController.java new file mode 100644 index 0000000..81bd2af --- /dev/null +++ b/consul/consul-user/src/main/java/kite/springcloud/consul/user/controller/UserController.java @@ -0,0 +1,28 @@ +package kite.springcloud.consul.user.controller; + +import kite.springcloud.consul.user.entity.User; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * UserController + * + * @author fengzheng + * @date 2019/8/29 + */ +@RestController +@RequestMapping(value = "user") +public class UserController { + + @GetMapping(value = "get") + public User getUserInfo(){ + User user = new User(); + user.setName("古时的风筝"); + user.setAge(8); + user.setLocation("北京"); + return user; + } + + +} diff --git a/consul/consul-user/src/main/java/kite/springcloud/consul/user/entity/User.java b/consul/consul-user/src/main/java/kite/springcloud/consul/user/entity/User.java new file mode 100644 index 0000000..a9ad8cf --- /dev/null +++ b/consul/consul-user/src/main/java/kite/springcloud/consul/user/entity/User.java @@ -0,0 +1,20 @@ +package kite.springcloud.consul.user.entity; + +import lombok.Data; + +/** + * User + * + * @author fengzheng + * @date 2019/8/29 + */ +@Data +public class User { + + private String name; + + private int age; + + private String location; + +} diff --git a/consul/gateway/src/main/java/kite/springcloud/gateway/Application.java b/consul/gateway/src/main/java/kite/springcloud/gateway/Application.java index 3ddf40f..5c92d43 100644 --- a/consul/gateway/src/main/java/kite/springcloud/gateway/Application.java +++ b/consul/gateway/src/main/java/kite/springcloud/gateway/Application.java @@ -2,11 +2,12 @@ import kite.springcloud.gateway.config.IpResolver; -import org.joda.time.DateTime; +import kite.springcloud.gateway.config.filter.CustomerFilter; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; -import org.springframework.cloud.gateway.filter.factory.RequestRateLimiterGatewayFilterFactory; +import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; @@ -17,8 +18,6 @@ import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.server.SecurityWebFilterChain; -import java.time.ZonedDateTime; - /** * @author fengzheng * @date 2019-08-01 @@ -31,6 +30,9 @@ public static void main(String[] args) { SpringApplication.run(Application.class, args); } +// @Autowired +// private KeyResolver ipResolver; + @Bean public RouteLocator kiteRouteLocator(RouteLocatorBuilder builder) { return builder.routes() @@ -51,13 +53,23 @@ public RouteLocator kiteRouteLocator(RouteLocatorBuilder builder) { .uri("lb://consul-user") ) .route("limit_route", r -> r.path("/limiter/**") - .filters(f -> f.stripPrefix(1).requestRateLimiter(c -> c.setRateLimiter(redisRateLimiter())/**.setKeyResolver(ipResolver())**/)) + .filters(f -> f.stripPrefix(1) + .requestRateLimiter( + c -> c.setKeyResolver(ipResolver()) + .setRateLimiter(redisRateLimiter()) + ) + ) .uri("lb://consul-user")) + .route("oauth_server", r -> r.path("/oauth-service/**") + .filters(f -> f.filter(new CustomerFilter())) + .uri("http://localhost:5010")) + .route("oauth_client", r -> r.path("/consul-oauth-client/**") + .uri("http://localhost:5012")) .build(); } @Bean - IpResolver ipResolver(){ + IpResolver ipResolver() { return new IpResolver(); } @@ -69,13 +81,17 @@ RedisRateLimiter redisRateLimiter() { @Bean SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception { - return http.httpBasic().and() - .csrf().disable() - .authorizeExchange() - .pathMatchers("/limiter/**").authenticated() + return http.csrf().disable().authorizeExchange() .anyExchange().permitAll() .and() .build(); +// return http.httpBasic().and() +// .csrf().disable() +// .authorizeExchange() +// .pathMatchers("/limiter/**").authenticated() +// .anyExchange().permitAll() +// .and() +// .build(); } @Bean diff --git a/consul/gateway/src/main/java/kite/springcloud/gateway/config/IpResolver.java b/consul/gateway/src/main/java/kite/springcloud/gateway/config/IpResolver.java new file mode 100644 index 0000000..2faf9b1 --- /dev/null +++ b/consul/gateway/src/main/java/kite/springcloud/gateway/config/IpResolver.java @@ -0,0 +1,17 @@ +package kite.springcloud.gateway.config; + + +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +@Slf4j +public class IpResolver implements KeyResolver { + + @Override + public Mono resolve(ServerWebExchange exchange) { + String ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress(); + return Mono.just(ip); + } +} \ No newline at end of file diff --git a/consul/gateway/src/main/java/kite/springcloud/gateway/config/fallback/FallbackController.java b/consul/gateway/src/main/java/kite/springcloud/gateway/config/fallback/FallbackController.java index 32c5da3..36a5eaa 100644 --- a/consul/gateway/src/main/java/kite/springcloud/gateway/config/fallback/FallbackController.java +++ b/consul/gateway/src/main/java/kite/springcloud/gateway/config/fallback/FallbackController.java @@ -3,6 +3,8 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.Calendar; + /** * FallbackController * @@ -14,6 +16,7 @@ public class FallbackController { @RequestMapping("/hystrixfallback") public String hystrixfallback() { + Calendar.getInstance().get(Calendar.MONTH); return "已超时,不用等了"; } } diff --git a/consul/gateway/src/main/java/kite/springcloud/gateway/config/filter/CustomerFilter.java b/consul/gateway/src/main/java/kite/springcloud/gateway/config/filter/CustomerFilter.java new file mode 100644 index 0000000..502474c --- /dev/null +++ b/consul/gateway/src/main/java/kite/springcloud/gateway/config/filter/CustomerFilter.java @@ -0,0 +1,48 @@ +package kite.springcloud.gateway.config.filter; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; +import org.springframework.cloud.gateway.support.ServerWebExchangeUtils; +import org.springframework.core.Ordered; +import org.springframework.http.HttpHeaders; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * CustomerFilterFactory + * + * @author fengzheng + * @date 2019/11/26 + */ +@Slf4j +public class CustomerFilter implements GatewayFilter,Ordered { + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + return chain.filter(exchange).then( + Mono.fromRunnable(() -> { + HttpHeaders headers = exchange.getRequest().getHeaders(); + Iterator>> iterator = headers.entrySet().iterator(); + while (iterator.hasNext()){ + Map.Entry> entry = iterator.next(); + log.info(entry.getKey()); + for(String s : entry.getValue()){ + log.info(s); + } + } + }) + ); + } + + @Override + public int getOrder() { + return 0; + } +} diff --git a/consul/gateway/src/main/resources/application.yml b/consul/gateway/src/main/resources/application.yml index efaa657..a0d90c7 100644 --- a/consul/gateway/src/main/resources/application.yml +++ b/consul/gateway/src/main/resources/application.yml @@ -36,6 +36,22 @@ spring: port: 8500 discovery: service-name: service-gateway + security: + oauth2: + client: + registration: + gateway: + client-id: gateway-client + client-secret: gateway-secret + authorization-grant-type: password + #authorization-grant-type: authorization_code + #redirect-uri-template: '{baseUrl}/login/oauth2/code/{registrationId}' + clientName: gateway + provider: + oauth-server: + user-authorization-uri: http://localhost:5010/oauth-service/oauth/authorize + access-token-uri: http://localhost:5010/oauth-service/oauth/token + jwt-key-uri: dev hystrix: command: diff --git a/consul/pom.xml b/consul/pom.xml index 1d8bfd4..0762267 100644 --- a/consul/pom.xml +++ b/consul/pom.xml @@ -19,6 +19,8 @@ gateway consul-user consul-order + consul-oauth-server + consul-oauth-client diff --git a/oauth2/oauth2-auth-server/src/main/java/kite/springcloud/oauth2/authserver/Application.java b/oauth2/oauth2-auth-server/src/main/java/kite/springcloud/oauth2/authserver/Application.java index 0e929ce..d7dfd7b 100644 --- a/oauth2/oauth2-auth-server/src/main/java/kite/springcloud/oauth2/authserver/Application.java +++ b/oauth2/oauth2-auth-server/src/main/java/kite/springcloud/oauth2/authserver/Application.java @@ -6,7 +6,7 @@ /** * 启动类 - * @author 故事的风筝 + * @author 古时的风筝 */ @SpringBootApplication public class Application { diff --git a/oauth2/oauth2-auth-server/src/main/java/kite/springcloud/oauth2/authserver/controller/HelloController.java b/oauth2/oauth2-auth-server/src/main/java/kite/springcloud/oauth2/authserver/controller/HelloController.java index 36f7e06..ba6bd9e 100644 --- a/oauth2/oauth2-auth-server/src/main/java/kite/springcloud/oauth2/authserver/controller/HelloController.java +++ b/oauth2/oauth2-auth-server/src/main/java/kite/springcloud/oauth2/authserver/controller/HelloController.java @@ -1,16 +1,9 @@ package kite.springcloud.oauth2.authserver.controller; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.oauth2.common.OAuth2RefreshToken; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; -import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import javax.sql.DataSource; - /** * HelloController * @@ -23,6 +16,7 @@ public class HelloController { public static void main(String[] args){ + System.out.println(new BCryptPasswordEncoder().encode("user-secret-8888")); System.out.println(new BCryptPasswordEncoder().encode("client-secret-8888")); System.out.println(new BCryptPasswordEncoder().encode("code-secret-8888")); diff --git a/oauth2/oauth2-client-order-server/src/main/java/kite/springcloud/oauth/client/order/Application.java b/oauth2/oauth2-client-order-server/src/main/java/kite/springcloud/oauth/client/order/Application.java index 16fe6cf..57cbaf2 100644 --- a/oauth2/oauth2-client-order-server/src/main/java/kite/springcloud/oauth/client/order/Application.java +++ b/oauth2/oauth2-client-order-server/src/main/java/kite/springcloud/oauth/client/order/Application.java @@ -7,7 +7,7 @@ /** * 启动类 - * @author 故事的风筝 + * @author 古时的风筝 */ @SpringBootApplication public class Application {