How to add a client using JDBC for ClientDetailsServiceConfigurer in Spring?

后端 未结 5 1540
迷失自我
迷失自我 2021-01-30 09:58

I have the in memory thing working as follows:

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

        clients.inMemo         


        
5条回答
  •  醉酒成梦
    2021-01-30 10:33

    @Override
    public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
    
        JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(dataSource);
    
        if(!jdbcClientDetailsService.listClientDetails().isEmpty() ) {          
        jdbcClientDetailsService.removeClientDetails(CLIEN_ID);     
        }
    
        if(jdbcClientDetailsService.listClientDetails().isEmpty() ) {
            configurer.jdbc(dataSource).withClient(CLIEN_ID).secret(encoder.encode(CLIENT_SECRET))
            .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT)
            .scopes(SCOPE_READ, SCOPE_WRITE, TRUST).accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
            .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS).and().build();                
        }       
        configurer.jdbc(dataSource).build().loadClientByClientId(CLIEN_ID); 
    }
    

    Here i am checking there is any client exist in the database table oauth_client_details. If there is any client exist I am removing that entry because the first time it will work without any error but when you restart your application then it gives primary key errors while adding entry in database. Thats why I added this code:

     if(!jdbcClientDetailsService.listClientDetails().isEmpty() ) { 
    
        jdbcClientDetailsService.removeClientDetails(CLIEN_ID);
    
        }
    

    After removing the client entry you need to add client here is the code for adding client :

    if(jdbcClientDetailsService.listClientDetails().isEmpty() ) {
            configurer.jdbc(dataSource).withClient(CLIEN_ID).secret(encoder.encode(CLIENT_SECRET))
            .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT)
            .scopes(SCOPE_READ, SCOPE_WRITE, TRUST).accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
            .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS).and().build();
    
        } 
    

    In this code you can change configuration as you want because we are removing client entry each time after restarting your application.

    here we are loading all client details :

    configurer.jdbc(dataSource).build().loadClientByClientId(CLIEN_ID);
    

    It will works fine for you without any errors. Thanks

提交回复
热议问题