使用Java Spring启用https的问题

时间:2019-01-17 16:29:55

标签: java spring security https server

我正在按照这个简短的教程为项目启用https安全性。 https://www.thomasvitale.com/https-spring-boot-ssl-certificate/

但是,当我运行项目时,出现以下错误:

  

配置为侦听端口8443的Tomcat连接器无法   开始。该端口可能已在使用中,或者连接器可能已在使用中   配置错误。

我已经生成了本教程中提到的密钥库。 我之前曾看到过这个问题,但没有明确的答案。 在命令行中输入netstate -ao时,端口8443的配置不正确或某种我看不到的东西。

我们将尽一切帮助。

============

我的文件

1) application.properties

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) SecurityConfig

@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";
  }
}

2 个答案:

答案 0 :(得分:1)

可能是检查您的密钥存储文件路径

server.ssl.key-store=src/main/resources:keystore.p12
to
server.ssl.key-store=src/main/resources/keystore.p12

答案 1 :(得分:0)

在配置中将端口更改为443。

server.port = 443