RESTful 客户端/服务器的 HTTPS 通信问题



我正在尝试通过HTTPS在我编写的应用程序上设置基于Web的安全性,该应用程序使用Spring Boot来提供RESTful功能。应用程序仅使用 HTTP 按预期工作。

我已经对在应用程序中"启用"HTTPS需要做什么做了大量的研究(至少我认为是这样(,并将提供代码和配置片段来说明我所拥有的。

我认为我已经接近了,但它还没有奏效,我尝试的各种事情都没有成功。

当前实现不要求服务(服务器(验证客户端的凭据。此外,我不需要任何形式的"用户"身份验证。

以下是当前设置的简要说明:

  • 一个"任务规划器"服务,它将对另外两个进行REST调用。 服务来执行一些工作。
  • "路由生成器"服务,当任务规划器调用该服务时,将返回一些数据以进行响应。
  • "路线评估员"服务,当任务规划者调用该服务时,将返回一些数据以进行响应。
  • 一个"客户" 这将向任务规划者发出 REST 调用以"计划任务"。任务计划程序什么也没返回。

还有一个"虚拟"服务,它只是将当前时间返回到来自客户端的 GET 请求。简单的测试仪。

所有这五个元素都以@Service和任务规划器,"路由"服务和虚拟人有相应的控制器(@RestController(,其中映射了REST端点。

我为三个服务(任务规划器和两个"路由"服务-虚拟人仅使用其中一个"路由"证书(生成了证书,这些文件位于"密钥库"位置。我还有一个"信任库"位置,其中包含生成 CA 的公钥。所有五个服务都具有信任库。

我无法让客户端与任何服务通信(为简单起见,使用"虚拟"(。我还尝试通过 Web 浏览器访问虚拟端点,结果似乎表明通信管道的某些部分正在发生,但失败了。

下面是代码片段,希望能从代码角度显示图片。

服务器(以"虚拟"为例(

假人.java:

@Service
@Profile("dummy")
public class Dummy {
public String doIt() {
return Long.toString(System.currentTimeMillis());
}
}

虚拟控制器.java:

@RestController
@RequestMapping("/rst")
@Profile("dummy")
public class DummyController {
@Autowired
private Dummy service;
@GetMapping(value = "/dummy", produces = "text/plain")
public String dummy() {
return service.doIt();
}
}

注意:下面的类和application.yml中的属性是我从网络上找到的示例(https://github.com/indrabasak/spring-tls-example(改编的。我不太理解已经定义的"角色"的概念。这里有很多我仍然不明白的地方。

安全配置.java:

@Configuration
@EnableWebSecurity
@EnableConfigurationProperties(SecurityAuthProperties.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final Logger                 logger = LogManager.getLogger();
private final SecurityAuthProperties properties;
@Autowired
public SecurityConfiguration(SecurityAuthProperties properties) {
this.properties = properties;
}
@Override
public void configure(AuthenticationManagerBuilder auth) {
// properties.getUsers().forEach((key, value) -> {
// try {
// auth.inMemoryAuthentication()
// .passwordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder())
// .withUser(value.getId()).password(value.getPassword()).roles(value.getRoles());
// logger.info("Added user " + value.getId() + " with password " + value.getPassword());
// } catch (Exception e) {
// throw new SecurityConfigurationException(
// "Problem encountered while setting up authentication mananger", e);
// }
// });
}
@Override
public void configure(HttpSecurity http) throws Exception {
properties.getEndpoints().forEach((key, value) -> {
try {
for (HttpMethod method : value.getMethods()) {
// http.authorizeRequests().antMatchers(method, value.getPath())
// .hasAnyAuthority(value.getRoles()).and().httpBasic().and().csrf().disable();
http.authorizeRequests().antMatchers(method, value.getPath()).permitAll().and()
.httpBasic().and().csrf().disable();
logger.info("Added security for path " + value.getPath() + " and method " + method);
}
} catch (Exception e) {
throw new SecurityConfigurationException(
"Problem encountered while setting up endpoint restrictions", e);
}
});
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
public void configure(WebSecurity web) {
// TODO - what (if anything) do we do here?
}
}

安全身份验证属性.java: ("用户"部分目前已取消,因为我们没有使用它。

@ConfigurationProperties("security.auth")
public class SecurityAuthProperties {
private static final String   ROLE_PREFIX    = "ROLE_";
public static final String    ROLE_ANONYMOUS = "ROLE_ANONYMOUS";
private Map<String, Endpoint> endpoints      = new HashMap<>();
// private Map<String, User> users = new HashMap<>();
@PostConstruct
public void init() {
endpoints.forEach((key, value) -> {
List<String> roles = new ArrayList<>();
for (String role : value.getRoles()) {
roles.add(ROLE_PREFIX + role);
}
value.setRoles(roles.toArray(new String[0]));
});
// users.forEach((key, value) -> {
// if (value.getId() == null) {
// value.setId(key);
// }
//
// if (value.getEncoding() != null) {
// value.setPassword("{" + value.getEncoding().trim() + "}" + value.getPassword());
// } else {
// value.setPassword("{noop}" + value.getPassword());
// }
// });
}
public Map<String, Endpoint> getEndpoints() {
return endpoints;
}
public void setEndpoints(Map<String, Endpoint> endpoints) {
this.endpoints = endpoints;
}
// public Map<String, User> getUsers() {
// return users;
// }
//
// public void setUsers(Map<String, User> users) {
// this.users = users;
// }
public static class Endpoint {
private String       path;
private HttpMethod[] methods;
private String[]     roles;
// trivial getters/setters removed for brevity
public String[] getRoles() {
if (roles == null || roles.length == 0) {
roles = new String[1];
roles[0] = ROLE_ANONYMOUS;
}
return roles;
}
}
public static class User {
private String   id;
private String   encoding;
private String   password;
private String[] roles;
// trivial getters/setters removed for brevity
public String[] getRoles() {
if (roles == null || roles.length == 0) {
roles = new String[1];
roles[0] = ROLE_ANONYMOUS;
}
return roles;
}
}
}

application.yml:

...
server:
port: 8443
ssl:
enabled: true
protocol: TLS
trust-store-type: JKS
trust-store: classpath:truststore/server.truststore
trust-store-password: <password>
key-store-type: JKS
security:
auth:
endpoints:
endpoint1:
path: /rst/dummy
methods: GET
roles: 

客户

客户服务.java:

@Service
public class ClientService {
private final Logger        logger            = LogManager.getLogger();
private static final String REST_DUMMY        = "rst/dummy";
// @Autowired
// private RestTemplate template;
@Value("${web.protocol:http}")
private String              protocol;
@Value("${mission-planner.host:localhost}")
private String              missionPlannerHost;
@Value("${mission-planner.port:8443}")
private int                 missionPlannerPort;
@Scheduled(fixedRate = 10000)
public void planMission() {
logger.info("ClientService.planMission()");
RestTemplate template = new RestTemplate();
String url = new URLBuilder.Builder().usingProtocol(protocol).onHost(missionPlannerHost)
.atPort(missionPlannerPort).atEndPoint(REST_DUMMY).build();
String response = template.getForObject(url, String.class);
}
}

我的一个大问题是,如果服务器不需要验证客户端,则需要在客户端进行什么(如果有的话("安全"配置?我确实有一堆类/配置尝试在客户端执行此操作,但目前已禁用。

使用如图所示的代码,当我尝试与虚拟服务通信时,客户端上出现异常:

org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://localhost:8443/rst/dummy": sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

更新

我决定尝试将server.ssl.key-alias(我在运行配置中通过 -D 设置(更改为大写(这是证书似乎具有的内容(,现在得到了一个新的有趣的异常。注意:我还为客户端和虚拟服务设置了javax.net.debug=ssl

scheduling-1, WRITE: TLSv1.2 Handshake, length = 196
scheduling-1, READ: TLSv1.2 Alert, length = 2
scheduling-1, RECV TLSv1.2 ALERT:  fatal, handshake_failure
scheduling-1, called closeSocket()
scheduling-1, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
[2019-08-09 13:28:45.648] scheduling-1 ERROR: support.TaskUtils$LoggingErrorHandler:96 - Unexpected error occurred in scheduled task.
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://localhost:8443/rst/dummy": Received fatal alert: handshake_failure; nested exception is javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

这是我在服务上得到的:

matching alias: route_assessor_1
matching alias: route_assessor_1
qtp1060563153-39, fatal error: 40: no cipher suites in common
javax.net.ssl.SSLHandshakeException: no cipher suites in common
%% Invalidated:  [Session-1, SSL_NULL_WITH_NULL_NULL]
qtp1060563153-39, SEND TLSv1.2 ALERT:  fatal, description = handshake_failure
qtp1060563153-39, WRITE: TLSv1.2 Alert, length = 2
qtp1060563153-39, fatal: engine already closed.  Rethrowing javax.net.ssl.SSLHandshakeException: no cipher suites in common
qtp1060563153-39, called closeOutbound()
qtp1060563153-39, closeOutboundInternal()

这似乎是活动部件太多并且忘记重新打开某些东西的情况。

经过相当多的反复讨论并回到原始源代码(https://github.com/indrabasak/spring-tls-example(并对其进行了一段时间的实验,我看不到作者的工作代码和我的非工作代码之间有任何显着差异。

然后发生了其中一种突然出现的情况,我意识到我没有在我的客户端中使用安全配置的REST 模板(由于我现在不记得的原因,它被注释掉了(。我只使用了一个普通的未配置模板。

我取消了代码的注释,瞧,客户端现在验证服务器的证书。

进入下一个问题。

最新更新