如何在Spring Cloud Config中使用自定义ssh密钥位置

mvl*_*pan 9 spring spring-cloud spring-cloud-config

我正在尝试设置一个Spring Cloud Config服务器,该服务器使用ssh私钥的自定义位置.我需要为密钥指定自定义位置的原因是因为运行应用程序的用户没有主目录..所以我没有办法使用~/.ssh我的密钥的默认目录.我知道可以选择创建只读帐户并在配置中提供用户/密码,但ssh方式接缝更干净.
有没有办法设置这个?

小智 9

在阅读了更多代码之后...我发现了一个相对简单的工作,允许您设置所需的任何SSH密钥.

第一:创建一个类如下:

/**
 * @file FixedSshSessionFactory.java 
 * 
 * @date Aug 23, 2016 2:16:11 PM 
 * @author jzampieron
 */

import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig.Host;
import org.eclipse.jgit.util.FS;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 * Short Desc Here.
 * 
 * @author jzampieron
 *
 */
public class FixedSshSessionFactory extends JschConfigSessionFactory
{

   protected String[] identityKeyPaths;

   /**
    * @param string
    */
   public FixedSshSessionFactory( String... identityKeyPaths )
   {
      this.identityKeyPaths = identityKeyPaths;
   }

   /* (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();
      for( final String identKeyPath : identityKeyPaths )
      {
         jsch.addIdentity( identKeyPath );
      }
      return jsch;
   }


}
Run Code Online (Sandbox Code Playgroud)

然后用jgit注册它:

...
import org.eclipse.jgit.transport.SshSessionFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer
public class ConfigserverApplication 
{

    public static void main(String[] args) {
       URL res = ConfigserverApplication.class.getClassLoader().getResource( "keys/id_rsa" );
       String path = res.getPath();
       SshSessionFactory.setInstance( new FixedSshSessionFactory( path ) );

       SpringApplication.run(ConfigserverApplication.class, args);
    }

}
Run Code Online (Sandbox Code Playgroud)

对于这个例子,我将密钥存储在src/main/resources/keys文件夹中,我正在使用类加载器来获取它们.

removeAllIdentities非常重要b/c JSch在我指定的密钥之前加载了我的默认ssh密钥,然后Spring Cloud崩溃了b/c加密.

这使我成功通过bitbucket进行身份验证.