【问题标题】:How to generate client-id & client-secret in spring-boot and store in database?如何在 spring-boot 中生成 client-id 和 client-secret 并存储在数据库中?
【发布时间】:2020-02-18 07:36:39
【问题描述】:

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

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

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

我还通过了 oAuth tutorial。但是,在此 client-idclient-secret 存储在属性文件中,而不是在数据库/其他源中。也好像是单对。

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

【问题讨论】:

    标签: java spring-boot spring-security oauth-2.0 spring-security-oauth2


    【解决方案1】:

    JdbcClientDetailsService 用于此特定目的。

    你需要在你的数据库中定义下表

    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

    【讨论】:

    • generatedpassword 将在将其保存到表 oauth_client_details 之前进行转换/散列,否则将按原样保存? BaseClientDetails 将是一个自定义对象,对吧?在这个结构中,什么时候会生成client_secret,我可以用它把它传递给其他表吗?
    • 非常感谢。现在这对我来说很有意义。我会玩弄你提供的东西。
    • 我有一个问题,我们传递给构造函数的companyId 只不过是client-id 对吗?
    • 是的,只要 companyId 是唯一的,您的 companyId 就可以是客户 ID
    猜你喜欢
    • 2021-03-12
    • 2021-07-28
    • 2015-12-29
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 2018-01-06
    相关资源
    最近更新 更多