How to use a custom ssh key location with Spring Cloud Config

后端 未结 3 765
难免孤独
难免孤独 2021-02-14 23:25

I am trying to setup a Spring Cloud Config server that uses a custom location for the ssh private key. The reason i need to specify a custom location for the key is because the

3条回答
  •  后悔当初
    2021-02-14 23:43

    The FixedSshSessionFactory solution of @Jeffrey Zampieron is good. However it won't work if packaging the spring boot app as a fat jar.

    Polish it a bit for working with fat jar,

    /**
     * @file FixedSshSessionFactory.java
     * @date Aug 23, 2016 2:16:11 PM
     * @author jzampieron
     */
    
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.JSchException;
    import com.jcraft.jsch.Session;
    import lombok.extern.slf4j.Slf4j;
    import org.eclipse.jgit.transport.JschConfigSessionFactory;
    import org.eclipse.jgit.transport.OpenSshConfig.Host;
    import org.eclipse.jgit.util.FS;
    import org.springframework.util.StreamUtils;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    
    /**
     * Short Desc Here.
     *
     * @author jzampieron
     */
    @Slf4j
    public class FixedSshSessionFactory extends JschConfigSessionFactory {
    
        protected URL[] identityKeyURLs;
    
        /**
         * @param url
         */
        public FixedSshSessionFactory(URL... identityKeyURLs) {
            this.identityKeyURLs = identityKeyURLs;
        }
    
        /* (non-Javadoc)
         * @see org.eclipse.jgit.transport.JschConfigSessionFactory#configure(org.eclipse.jgit.transport.OpenSshConfig.Host, com.jcraft.jsch.Session)
         */
        @Override
        protected void configure(Host hc, Session session) {
            // nothing special needed here.
        }
    
        /* (non-Javadoc)
         * @see org.eclipse.jgit.transport.JschConfigSessionFactory#getJSch(org.eclipse.jgit.transport.OpenSshConfig.Host, org.eclipse.jgit.util.FS)
         */
        @Override
        protected JSch getJSch(Host hc, FS fs) throws JSchException {
            JSch jsch = super.getJSch(hc, fs);
            // Clean out anything 'default' - any encrypted keys
            // that are loaded by default before this will break.
            jsch.removeAllIdentity();
            int count = 0;
            for (final URL identityKey : identityKeyURLs) {
                try (InputStream stream = identityKey.openStream()) {
                    jsch.addIdentity("key" + ++count, StreamUtils.copyToByteArray(stream), null, null);
                } catch (IOException e) {
                    logger.error("Failed to load identity " + identityKey.getPath());
                }
            }
            return jsch;
        }
    
    
    }
    

提交回复
热议问题