如何在 spring-boot 中生成 client-id 和 client-secret 并存储在数据库中?

How to generate client-id & client-secret in spring-boot and store in database?

我知道 Whosebug 上已经存在与此类似的问题。当我浏览它们时,它并没有解决我正在寻找的问题。

我有一个 spring-boot 网络服务 作为 Oaut2ClientManagement,我在其中创建了一个 API,基本上注册一个新客户。 当新公司注册时,companyId(它在某些 company_details table 中预定义,是的,公司已添加到列表中但未注册访问 APIs)是基于此发送,我必须生成 client-id & client-secret,我将其存储在 CLIENT_KEY_MANAGEMENT table 中。基于此,我编写了一个 java 代码来生成 accessToken.

所以我的问题是如何根据 companyId 生成 client-id & client-secret 我'收到请求了吗?我经历过这个 answer。但是 spring-boot oauth 中是否有任何预定义的方法可以完成这项工作?下一步是基于它生成访问令牌。

我也通过了 oAuth tutorial。但是,在此 client-idclient-secret 存储在属性文件中而不是 Database/other 源中。也好像是一对。

如果有人可以指导我使用 spring-boot 实现上述场景,那就太好了。

有一个 JdbcClientDetailsService 用于此特定目的。

您需要在数据库中定义以下内容table

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)
);

并如下配置您的 Oauth2 授权服务器

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

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

}

最后,您可以在注册 companyId.

的位置注入 JdbcClientDetailsService bean
@Autowired
JdbcClientDetailsService jdbcClientDetailsService;

...
BaseClientDetails clientDetails = new BaseClientDetails(companyId, resourceIds, scopes, grantTypes, authorities);
clientDetails.setClientSecret("generatedpassword");
jdbcClientDetailsService.addClientDetails(clientDetails);

您终于可以使用这些客户端凭据登录了。

更新

如果您希望对密码进行哈希处理,您可以按如下方式设置 PasswordEncoder。

clients.jdbc(dataSource)
                .passwordEncoder(new BCryptPasswordEncoder())

BaseClientDetails 在包 org.springframework.security.oauth2.provider.client.

中可用

服务不会生成客户端密码。您需要生成它并将其设置为 BaseClientDetails.