当前位置:   article > 正文

springsecurity+oauth2.0 分布式认证授权-授权码存储到数据库7_clientdetailsserviceconfigurer.jdbc

clientdetailsserviceconfigurer.jdbc

一 说明

1.1 概要说明

前面文章的介绍了,客户单和授权码存储在内存中,现在需要存储到数据库中。

本操作在第5章节的基础上进行操作。

1.2 这里配置说明

1.配置好需要的的两个表: oauth_client_details 和oauth_code

2.进行各种配置文件的配置。

3.不需要自己写查询sql语句的逻辑。

二 操作

2.1 客户端认证信息的配置

2.1.1 在数据库中创建oauth_client_details

DROP TABLE IF EXISTS `oauth_client_details`; CREATE TABLE `oauth_client_details` ( `client_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '客户端标 识',`resource_ids` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '接入资源列表', `client_secret` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '客户端秘钥', `scope` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `authorized_grant_types` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `web_server_redirect_uri` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `authorities` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `access_token_validity` int(11) NULL DEFAULT NULL, `refresh_token_validity` int(11) NULL DEFAULT NULL, `additional_information` longtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL, `create_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0), `archived` tinyint(4) NULL DEFAULT NULL, `trusted` tinyint(4) NULL DEFAULT NULL, `autoapprove` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`client_id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '接入客户端信息' ROW_FORMAT = Dynamic; INSERT INTO `oauth_client_details` VALUES ('c1', 'res1', '$2a$10$NlBC84MVb7F95EXYTXwLneXgCca6/GipyWR5NHm8K0203bSQMLpvm', 'ROLE_ADMIN,ROLE_USER,ROLE_API', 'client_credentials,password,authorization_code,implicit,refresh_token', 'http://www.baidu.com', NULL, 7200, 259200, NULL, '2019‐09‐09 16:04:28', 0, 0, 'false'); INSERT INTO `oauth_client_details` VALUES ('c2', 'res2', '$2a$10$NlBC84MVb7F95EXYTXwLneXgCca6/GipyWR5NHm8K0203bSQMLpvm', 'ROLE_API', 'client_credentials,password,authorization_code,implicit,refresh_token', 'http://www.baidu.com', NULL, 31536000, 2592000, NULL, '2019‐09‐09 21:48:51', 0, 0, 'false');

2.1.2 在数据库中创建oauth_code

DROP TABLE IF EXISTS `oauth_code`; CREATE TABLE `oauth_code` ( `create_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP, `code` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `authentication` blob NULL, INDEX `code_index`(`code`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

2.2 配置授权服务

2.2.1 修改AuthorizationServer

ClientDetailsService AuthorizationCodeServices 从数据库读取数据。
1.在WebSecurityConfig中初始化PasswordEncoder

 2.AuthorizationServer中进行配置

 配置授权码,存储数据库

  1. package com.ljf.springsecurity.oauth.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.http.HttpMethod;
  6. import org.springframework.security.authentication.AuthenticationManager;
  7. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  8. import org.springframework.security.crypto.password.PasswordEncoder;
  9. import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
  10. import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
  11. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
  12. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
  13. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
  14. import org.springframework.security.oauth2.provider.ClientDetailsService;
  15. import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
  16. import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
  17. import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
  18. import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
  19. import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
  20. import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
  21. import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
  22. import org.springframework.security.oauth2.provider.token.TokenStore;
  23. import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
  24. import javax.sql.DataSource;
  25. import java.util.Arrays;
  26. /**
  27. * @ClassName: AuthorizationServer
  28. * @Description: TODO
  29. * @Author: liujianfu
  30. * @Date: 2021/08/29 12:46:21 
  31. * @Version: V1.0
  32. **/
  33. @Configuration
  34. @EnableAuthorizationServer
  35. public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
  36. @Autowired
  37. private TokenStore tokenStore;
  38. @Autowired
  39. private ClientDetailsService clientDetailsService;
  40. @Autowired
  41. private AuthorizationCodeServices authorizationCodeServices;
  42. @Autowired
  43. private AuthenticationManager authenticationManager;
  44. @Autowired
  45. private JwtAccessTokenConverter accessTokenConverter;
  46. @Autowired
  47. private PasswordEncoder passwordEncoder;
  48. //将客户端信息存储到数据库
  49. @Bean
  50. public ClientDetailsService clientDetailsService(DataSource dataSource) {
  51. ClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
  52. ((JdbcClientDetailsService) clientDetailsService).setPasswordEncoder(passwordEncoder);
  53. return clientDetailsService;
  54. }
  55. //step1:客户端详情服务
  56. @Override
  57. public void configure(ClientDetailsServiceConfigurer clients)
  58. throws Exception {
  59. clients.withClientDetails(clientDetailsService);
  60. /**
  61. clients.inMemory()// 使用in-memory存储
  62. .withClient("c1")// client_id
  63. .secret(new BCryptPasswordEncoder().encode("secret"))//客户端密钥
  64. .resourceIds("res1")//资源列表
  65. .authorizedGrantTypes("authorization_code", "password","client_credentials","implicit","refresh_token")// 该client允许的授权类型authorization_code,password,refresh_token,implicit,client_credentials
  66. .scopes("all")// 允许的授权范围
  67. .autoApprove(false)//false跳转到授权页面
  68. //加上验证回调地址
  69. .redirectUris("http://www.baidu.com");
  70. **/
  71. }
  72. //step2; 令牌管理服务
  73. @Bean
  74. public AuthorizationServerTokenServices tokenService() {
  75. DefaultTokenServices service=new DefaultTokenServices();
  76. service.setClientDetailsService(clientDetailsService);//客户端详情服务
  77. service.setSupportRefreshToken(true);//支持刷新令牌
  78. service.setTokenStore(tokenStore);//令牌存储策略
  79. //令牌增强
  80. TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
  81. tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
  82. service.setTokenEnhancer(tokenEnhancerChain);
  83. service.setAccessTokenValiditySeconds(7200); // 令牌默认有效期2小时
  84. service.setRefreshTokenValiditySeconds(259200); // 刷新令牌默认有效期3
  85. return service;
  86. }
  87. //step3: 设置授权码模式的授权码如何存取,暂时采用内存方式
  88. /**
  89. @Bean
  90. public AuthorizationCodeServices authorizationCodeServices() {
  91. return new InMemoryAuthorizationCodeServices();
  92. }
  93. **/
  94. @Bean
  95. public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) {
  96. return new JdbcAuthorizationCodeServices(dataSource);
  97. }
  98. //step4: 令牌服务端点
  99. @Override
  100. public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
  101. endpoints
  102. .authenticationManager(authenticationManager)//认证管理器
  103. .authorizationCodeServices(authorizationCodeServices)//授权码服务
  104. .tokenServices(tokenService())//令牌管理服务
  105. .allowedTokenEndpointRequestMethods(HttpMethod.POST);
  106. }
  107. //step5: 令牌安全约束
  108. @Override
  109. public void configure(AuthorizationServerSecurityConfigurer security){
  110. security
  111. .tokenKeyAccess("permitAll()") //oauth/token_key是公开
  112. .checkTokenAccess("permitAll()") //oauth/check_token公开
  113. .allowFormAuthenticationForClients() //表单认证(申请令牌)
  114. ;
  115. }
  116. }

2.3 密码方式客户端信息存储

2.3.1 启动服务

1.启动认证服务

2.3.2 认证请求测试

2.postman进行测试

原因在于:要对client_secret的密码明文设置为加密

3.使用加密工具类, 将secret设置进行加密:

4. 加密后存储到数据库中

5.再次访问:http://localhost:53020/uaa/oauth/token

其中 :请求方式为:post 

表单提交方式为: x-www-form-urlencoded

2.3.3 验证token

表单提交方式为: x-www-form-urlencoded 这种提交方式

  地址:http://localhost:53020/uaa/oauth/check_token

表单提交方式为: x-www-form-urlencoded 这种提交方式

token=xxx,为上一步求得的token值,复制到此处,进行请求访问

 2.4 授权码方式存储code测试

2.4.1 请求访问

地址:http://localhost:53020/uaa/oauth/authorize?client_id=c1&response_type=code&scope=ROLE_API&redirect_uri=http://www.baidu.com

 注意: scope=ROLE_API 这个参数scope不再是all。

 1.请求访问

登录界面 

2.确认授权

 3.授权码

4.查看数据库:授权码code=UM4lcA已经存储到库中

5.获取acesstoken

http://localhost:53020/uaa/oauth/token

表单提交方式为: x-www-form-urlencoded 这种提交方式

2.4.2 验证token

表单提交方式为: x-www-form-urlencoded 这种提交方式

  地址:http://localhost:53020/uaa/oauth/check_token

表单提交方式为: x-www-form-urlencoded 这种提交方式

token=xxx,为上一步求得的token值,复制到此处,进行请求访问

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/83490
推荐阅读
相关标签
  

闽ICP备14008679号