我正在学习这个关于为项目启用 https 安全性的简短教程。 https://www.thomasvitale.com/https-spring-boot-ssl-certificate/
然而,当我运行项目时,出现以下错误:
The Tomcat connector configured to listen on port 8443 failed to start. The port may already be in use or the connector may be misconfigured.
我已经生成了教程中提到的 keystore 。
我以前见过这个问题,但没有明确的答案。
端口 8443 未配置正确或其他原因,因为当我在命令行中键入 netstate -ao
时看不到它。
感谢任何帮助。
============
我的文件
1) 应用程序属性
spring.data.rest.base-path=/api
server.port = 8443
server.ssl.key-store-type=PKCS12
server.ssl.key-store=src/main/resources:keystore.p12
server.ssl.key-store-password=Welcome1
server.ssl.key-alias=tomcat
server.servlet.contextPath=/
2) 安全配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login", "/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest()
//.permitAll()
.authenticated()
.and()
.formLogin()
.permitAll();
//.httpBasic();
http.csrf().disable();
}
/*@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}*/
/*
// Create an encoder with strength 16
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16);
String result = encoder.encode("myPassword");
assertTrue(encoder.matches("myPassword", result));
*/
@Bean
public TomcatServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(getHttpConnector());
return tomcat;
}
private Connector getHttpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
3) HelloResource
@RestController
@RequestMapping("/rest/hello")
public class HelloResource {
@GetMapping
public String hello(){
return "Hello World";
}
}
最佳答案
可能会检查您的 keystore 文件路径
server.ssl.key-store=src/main/resources:keystore.p12
to
server.ssl.key-store=src/main/resources/keystore.p12
关于java - 使用 Java Spring 启用 https 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54240294/