我正在尝试设置一个使用ssh私钥的自定义位置的Spring Cloud Config服务器。
我需要为 key 指定自定义位置的原因是因为运行该应用程序的用户没有主目录..so,因此我无法使用默认的~/.ssh
目录作为 key 。
我知道可以创建一个只读帐户并在配置中提供用户名/密码,但是ssh方式更加整洁。是否可以设置此方式?
最佳答案
在阅读更多代码之后...我发现了一个相对简单的解决方法,可以让您设置所需的任何SSH key 。
首先:创建一个类,如下所示:
/**
* @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;
}
}
然后向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);
}
}
对于此示例,我将 key 存储在src/main/resources/keys文件夹中,
我正在使用类加载器来获取它们。
removeAllIdentities很重要b/c JSch在我指定的默认ssh key 之前加载了我的默认ssh key ,然后Spring Cloud将b/c对其加密的崩溃了。
这使我能够成功地使用bitbucket进行身份验证。
关于spring - 如何在Spring Cloud Config中使用自定义ssh key 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33798013/