spring-security-oauth2 配置(一)数据持久化


前言

上一篇 OAuth2与spring-security-oauth2
基于上文配置好之后继续

client数据库配置

java配置

之前在DemoAuthorizationServerConfiguration中的配置

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
   
   

		// @formatter:off
		clients.inMemory()
				.withClient("test-client").secret("$2a$08$YGw560YLRWHg3Hl29ZlmdOfAeyRQ2u0kDiqUyQ62Y1pkW5n4a.hjO")
				.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
				.authorities("ROLE_CLIENT").redirectUris("http://localhost:8084/oauth/callback")
				.scopes("read", "write", "all");// 请求参数scope必须为集合中的某个值
		// @formatter:on
	}

这里使用的是内存型的ClientDetailsService的实现类InMemoryClientDetailsService,现在需要配置成数据库型ClientDetailsService的实现类JdbcClientDetailsService

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
   
   
		
		clients.withClientDetails(new JdbcClientDetailsService(dataSource));
		
	}

sql脚本

使用JdbcClientDetailsService需要创建对应的表,这些建表sql在spring-security-oauth2源码中,有兴趣的可以去源码中找一找。这些建表sql默认为mysql语法。

-- used in tests that use HSQL
create table oauth_client_details (
  client_id VARCHAR(256) PRIMARY KEY,
  resource_ids VARCHAR(256),
  client_secret VARCHAR(256),
  scope VARCHAR(256),
  authorized_grant_types VARCHAR(256),
  web_server_redirect_uri VARCHAR(256),
  authorities VARCHAR(256),
  access_token_validity INTEGER,
  refresh_token_validity INTEGER,
  additional_information VARCHAR(4096),
  autoapprove VARCHAR(256)
);

INSERT INTO `oauth_client
### 配置和使用 `ClientDetailsService` 的方法 在 Spring Security OAuth2 Authorization Server 中,`ClientDetailsService` 负责管理客户端详情信息。为了配置并使用这个服务,在应用程序中可以采用多种方式。 #### 使用内存中的客户端细节存储 对于开发环境或简单的应用场景,可以直接通过 Java Config 定义内嵌式的 `InMemoryClientDetailsService`. 这种做法简单明了,适合快速原型设计[^2]. ```java @Configuration public class ClientConfig { @Bean public ClientRegistrationRepository clientRegistrationRepository() { List<ClientRegistration> clients = Arrays.asList( CommonOAuth2Provider.GITHUB.getBuilder("github").clientId("client-id") .clientSecret("secret").scope("read:user").build() ); return new InMemoryClientRegistrationRepository(clients); } } ``` 请注意上述代码片段仅作为示意,并不完全适用于所有场景;实际应用时应根据需求调整参数设置. #### 数据库驱动的 `JdbcClientDetailsService` 当需要持久化保存多个客户端的信息或者希望这些数据能够在不同实例间共享时,则可以选择基于数据库的方式。此时会涉及到创建相应的表结构以及编写 SQL 初始化脚本[^1]. ```sql CREATE TABLE IF NOT EXISTS oauth_client_details ( client_id VARCHAR(256) PRIMARY KEY, resource_ids VARCHAR(256), client_secret VARCHAR(256), scope VARCHAR(256), authorized_grant_types VARCHAR(256), web_server_redirect_uri VARCHAR(256), authorities VARCHAR(256), access_token_validity INTEGER, refresh_token_validity INTEGER, additional_information VARCHAR(4096), autoapprove VARCHAR(256) ); -- 插入测试数据 INSERT INTO oauth_client_details (...) VALUES ('sample-client', 'resource-server-read-write', '{bcrypt}password', 'openid profile email offline_access','refresh_token password authorization_code implicit client_credentials', 'http://localhost:8080/callback', NULL, 7200, 2592000, '{}', 'true'); ``` 接着可以在 Spring Boot 应用程序里注入 `DataSource`, 并将其传递给 `JdbcClientDetailsService`. ```java @Bean public ClientDetailsService jdbcClientDetails(final DataSource dataSource){ JdbcClientDetailsService service = new JdbcClientDetailsService(dataSource); PasswordEncoder encoder = new BCryptPasswordEncoder(); service.setPasswordEncoder(encoder); return service; } ``` 此部分展示了如何利用 JDBC 来加载来自关系型数据库内的客户端注册记录[^3]. #### 自定义实现 如果默认提供的选项无法满足特定业务逻辑的需求,还可以考虑构建自己的 `ClientDetailsService` 实现类。这通常涉及继承抽象基类或是接口编程模式下的全新实现[^4]. ```java @Component public class CustomClientDetailsService implements ClientDetailsService{ private final Map<String, RegisteredClient> registeredClients; public CustomClientDetailsService(){ this.registeredClients = new ConcurrentHashMap<>(); // Initialize with some predefined values... } @Override public ClientDetails loadClientByClientId(String clientId) throws OAuth2Exception { RegisteredClient rc = registeredClients.get(clientId); if(rc != null){ return new AuthorizedClientCredentialsTokenResponse(rc.getClientId(), rc.getClientSecret()); }else{ throw new InvalidGrantException("Invalid credentials"); } } } ``` 这段伪代码说明了个可能的基础框架用于定制化的解决方案.
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值