oauth2-客户端模式案例

x33g5p2x  于2022-04-17 转载在 其他  
字(14.5k)|赞(0)|评价(0)|浏览(341)

1.项目结构

2.搭建授权服务器(auth-server)

1.pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.2.5.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.yl</groupId>
  12. <artifactId>auth-server</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>auth-server</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>11</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-web</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-jdbc</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>com.alibaba</groupId>
  30. <artifactId>druid-spring-boot-starter</artifactId>
  31. <version>1.1.10</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>mysql</groupId>
  35. <artifactId>mysql-connector-java</artifactId>
  36. <scope>runtime</scope>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-data-redis</artifactId>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.springframework.cloud</groupId>
  44. <artifactId>spring-cloud-security</artifactId>
  45. <version>2.2.5.RELEASE</version>
  46. </dependency>
  47. <dependency>
  48. <groupId>org.springframework.cloud</groupId>
  49. <artifactId>spring-cloud-starter-oauth2</artifactId>
  50. <version>2.2.5.RELEASE</version>
  51. </dependency>
  52. <dependency>
  53. <groupId>org.springframework.boot</groupId>
  54. <artifactId>spring-boot-starter-test</artifactId>
  55. <scope>test</scope>
  56. </dependency>
  57. </dependencies>
  58. <build>
  59. <plugins>
  60. <plugin>
  61. <groupId>org.springframework.boot</groupId>
  62. <artifactId>spring-boot-maven-plugin</artifactId>
  63. </plugin>
  64. </plugins>
  65. </build>
  66. </project>

2.application.properties

  1. spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
  2. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  3. spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
  4. spring.datasource.username=root
  5. spring.datasource.password=root
  6. spring.main.allow-bean-definition-overriding=true
  7. # redis的配置
  8. spring.redis.host=192.168.244.138
  9. spring.redis.port=6379
  10. spring.redis.password=root123
  11. spring.redis.database=0

3.token的配置

  1. package com.yl.authserver.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.data.redis.connection.RedisConnectionFactory;
  6. import org.springframework.security.oauth2.provider.token.TokenStore;
  7. import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
  8. import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
  9. // Token暂时保存在内存中
  10. @Configuration
  11. public class AccessTokenConfig {
  12. //token存储方式一:存在内存中
  13. // @Bean
  14. // TokenStore tokenStore() {
  15. // return new InMemoryTokenStore();
  16. // }
  17. //token存储方式二:存在redis中,由于redis中,可以设置过期时间,所以在redis中存储token有一种天然的优势
  18. @Autowired
  19. RedisConnectionFactory redisConnectionFactory;
  20. @Bean
  21. TokenStore tokenStore() {
  22. return new RedisTokenStore(redisConnectionFactory);
  23. }
  24. }

4.security的配置

  1. package com.yl.authserver.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.security.authentication.AuthenticationManager;
  5. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  6. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  7. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  8. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  9. import org.springframework.security.crypto.password.PasswordEncoder;
  10. @Configuration
  11. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  12. @Bean
  13. PasswordEncoder passwordEncoder() {
  14. return new BCryptPasswordEncoder();
  15. }
  16. @Bean
  17. @Override
  18. public AuthenticationManager authenticationManagerBean() throws Exception {
  19. return super.authenticationManagerBean();
  20. }
  21. @Override
  22. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  23. auth.inMemoryAuthentication()
  24. .withUser("admin")
  25. .password(passwordEncoder().encode("123"))
  26. .roles("admin")
  27. .and()
  28. .withUser("root")
  29. .password(passwordEncoder().encode("123"))
  30. .roles("root");
  31. }
  32. @Override
  33. protected void configure(HttpSecurity http) throws Exception {
  34. http.csrf().disable().formLogin();
  35. }
  36. }

5.授权服务器的配置

  1. package com.yl.authserver.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  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.crypto.password.PasswordEncoder;
  7. import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
  8. import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
  9. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
  10. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
  11. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
  12. import org.springframework.security.oauth2.provider.ClientDetailsService;
  13. import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
  14. import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
  15. import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
  16. import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
  17. import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
  18. import org.springframework.security.oauth2.provider.token.TokenStore;
  19. import javax.sql.DataSource;
  20. //配置授权服务器
  21. @Configuration
  22. @EnableAuthorizationServer
  23. public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  24. @Autowired
  25. TokenStore tokenStore;
  26. // 客户端信息
  27. @Autowired
  28. ClientDetailsService clientDetailsService;
  29. @Autowired
  30. PasswordEncoder passwordEncoder;
  31. @Autowired
  32. AuthenticationManager authenticationManager;
  33. // @Autowired
  34. // DataSource dataSource;
  35. //
  36. // @Bean
  37. // ClientDetailsService clientDetailsService() {
  38. // return new JdbcClientDetailsService(dataSource);
  39. // }
  40. //配置Token服务
  41. AuthorizationServerTokenServices authorizationServerTokenServices() {
  42. DefaultTokenServices tokenServices = new DefaultTokenServices();
  43. tokenServices.setClientDetailsService(clientDetailsService);
  44. tokenServices.setSupportRefreshToken(true);
  45. tokenServices.setAccessTokenValiditySeconds(60 * 60 * 2); //token有限期设置为2小时
  46. tokenServices.setTokenStore(tokenStore);
  47. tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);//
  48. return tokenServices;
  49. }
  50. //配置token
  51. @Override
  52. public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
  53. security.checkTokenAccess("permitAll()")// /oauth/check_token 带时候会调用这个请求来校验token
  54. .checkTokenAccess("isAuthenticated()")
  55. .allowFormAuthenticationForClients();
  56. }
  57. //配置客户端的信息(客户端信息存于内存)
  58. @Override
  59. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  60. clients.inMemory()
  61. .withClient("yl") //客户端名
  62. .secret(passwordEncoder.encode("123")) //客户端密码
  63. .scopes("all")
  64. .resourceIds("res1") //资源id
  65. .authorizedGrantTypes("authorization_code","refresh_token","implicit","password","client_credentials")
  66. // authorization_code授权码模式,password密码模式,implicit简化模式,client_credentials客户端模式,可以设置同时支持多种模式
  67. .autoApprove(true) //自动授权
  68. // .redirectUris("http://localhost:8082/index.html"); //授权码模式界面
  69. // .redirectUris("http://localhost:8082/01.html");//简化模式界面
  70. .redirectUris("http://localhost:8082/02.html");//密码模式界面
  71. }
  72. // //配置客户端的信息(客户端信息存于数据库)
  73. // @Override
  74. // public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  75. // clients.withClientDetails(clientDetailsService());
  76. // }
  77. //配置端点信息(主要获取授权码,要先拿到授权码,然后再根据授权码去获取token)
  78. @Override
  79. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  80. endpoints.authorizationCodeServices(authorizationCodeServices())
  81. .authenticationManager(authenticationManager)
  82. .tokenServices(authorizationServerTokenServices());
  83. }
  84. @Bean
  85. AuthorizationCodeServices authorizationCodeServices() {
  86. return new InMemoryAuthorizationCodeServices();
  87. }
  88. }

3.搭建资源服务器(user-server)

1.pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.2.5.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.yl</groupId>
  12. <artifactId>user-server</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>user-server</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>11</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-web</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.cloud</groupId>
  26. <artifactId>spring-cloud-security</artifactId>
  27. <version>2.2.5.RELEASE</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.cloud</groupId>
  31. <artifactId>spring-cloud-starter-oauth2</artifactId>
  32. <version>2.2.5.RELEASE</version>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-test</artifactId>
  37. <scope>test</scope>
  38. </dependency>
  39. </dependencies>
  40. <build>
  41. <plugins>
  42. <plugin>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-maven-plugin</artifactId>
  45. </plugin>
  46. </plugins>
  47. </build>
  48. </project>

2.application.properties

  1. server.port=8081

3.controller

  1. package com.yl.userserver.controller;
  2. import org.springframework.web.bind.annotation.CrossOrigin;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. @CrossOrigin(value = "*")
  7. public class HelloController {
  8. @GetMapping("/hello")
  9. public String hello() {
  10. return "hello";
  11. }
  12. @GetMapping("/admin")
  13. public String admin() {
  14. return "hello admin";
  15. }
  16. }

4.资源服务器的配置

  1. package com.yl.userserver.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  5. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
  6. import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
  7. import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
  8. import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
  9. //配置资源服务器
  10. @Configuration
  11. @EnableResourceServer
  12. public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  13. @Bean
  14. RemoteTokenServices remoteTokenServices() {
  15. RemoteTokenServices services = new RemoteTokenServices();
  16. services.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
  17. services.setClientId("yl");
  18. services.setClientSecret("123");
  19. return services;
  20. }
  21. @Override
  22. public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
  23. resources.resourceId("res1")
  24. .tokenServices(remoteTokenServices())
  25. .stateless(true);
  26. }
  27. @Override
  28. public void configure(HttpSecurity http) throws Exception {
  29. http.authorizeRequests()
  30. .antMatchers("/admin/**")
  31. .hasRole("admin")
  32. .anyRequest().authenticated()
  33. .and().cors();
  34. }
  35. }

4.测试

1.启动redis
2.启动授权服务器和资源服务器

3.在client-app里的Test里测试

  1. package com.yl.clientapp;
  2. import org.junit.jupiter.api.Test;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.boot.test.context.SpringBootTest;
  5. import org.springframework.http.HttpEntity;
  6. import org.springframework.http.HttpHeaders;
  7. import org.springframework.http.HttpMethod;
  8. import org.springframework.http.ResponseEntity;
  9. import org.springframework.util.LinkedMultiValueMap;
  10. import org.springframework.util.MultiValueMap;
  11. import org.springframework.web.client.RestTemplate;
  12. import java.util.Map;
  13. @SpringBootTest
  14. class ClientAppApplicationTests {
  15. @Autowired
  16. RestTemplate restTemplate;
  17. @Test
  18. void contextLoads() {
  19. MultiValueMap<String,String> map = new LinkedMultiValueMap<>();
  20. map.add("client_id","yl");
  21. map.add("grant_type","client_credentials");
  22. map.add("client_secret","123");
  23. //调用授权服务器接口,获取token
  24. Map resp = restTemplate.postForObject("http://localhost:8080/oauth/token", map, Map.class);
  25. HttpHeaders headers = new HttpHeaders();
  26. //传入token
  27. headers.add("Authorization","Bearer "+resp.get("access_token"));
  28. HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
  29. //调用资源服务器获取资源
  30. ResponseEntity<String> entity = restTemplate.exchange("http://localhost:8081/hello", HttpMethod.GET, httpEntity, String.class);
  31. System.out.println(entity.getBody());
  32. }
  33. }

4.结果可以看到能访问资源服务器的hello接口

相关文章