java中使用https的Rest api

0 java rest https web-services rest-security

当我Restservices使用 java等创建时GETPOST我请求它们使用 http protocol. 当我使用 https 时,就会出现错误。

例如: http://localhost:8080/demorest/webapi/aliens工作正常。

但是当我使用相同的查询时https

https://localhost:8080/demorest/webapi/aliens
Run Code Online (Sandbox Code Playgroud)

我收到错误site can not provide secured connection

需要进行哪些修改才能使它们与https.

Kun*_*hra 6

正如您所提到的,您是 API 新手,这里为您提供了详细的答案。

答案基于您使用 tomcat 服务器的假设。有 4 个步骤的方法可以让应用程序在 https 上运行,如下图红色

  1. 获取 SSL 证书或生成自签名 SSL 证书
  2. 在应用程序中启用 HTTPS
  3. 将 HTTP 重定向到 HTTPS
  4. 将 SSL 证书分发给客户端。

如果您还没有 ssl 证书,请使用 keytool 自行生成。Keytool 是与 JDK 一起提供的证书管理实用程序,因此如果安装了 JDK,则应该已经有 keytool 可用。

让我们打开终端提示符并编写以下命令来创建 JKS 密钥库:

keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -keystore keystore.jks -validity 3650 -storepass 密码

要创建 PKCS12 密钥库,我们应该使用以下命令:

keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650 -storepass 密码

让我们仔细看看我们刚刚运行的命令:

genkeypair: generates a key pair;
alias: the alias name for the item we are generating;
keyalg: the cryptographic algorithm to generate the key pair;
keysize: the size of the key. We have used 2048 bits, but 4096 would be a better choice for production;
storetype: the type of keystore;
keystore: the name of the keystore;
validity: validity number of days;
storepass: a password for the keystore.
Run Code Online (Sandbox Code Playgroud)

运行上一个命令时,我们会被要求输入一些信息,但我们可以跳过所有信息(只需按回车键即可跳过一个选项)。当询问信息是否正确时,我们应该输入 yes。最后,我们按回车键也将密钥库密码用作密钥密码。

What is your first and last name? 
    [Unknown]:  What is the name of your organizational unit? 
    [Unknown]:  What is the name of your organization? 
    [Unknown]:  What is the name of your City or Locality? 
    [Unknown]:  What is the name of your State or Province? 
    [Unknown]:  What is the two-letter country code for this unit? 
    [Unknown]:  Is CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct? 
    [no]: yes 

Enter key password for <tomcat> 
    (RETURN if same as keystore password):
Run Code Online (Sandbox Code Playgroud)

验证密钥库内容 要检查 JKS 格式的密钥库内容,我们可以再次使用 keytool:

keytool -list -v -keystore keystore.jks

要测试 PKCS12 格式的密钥库的内容:

keytool -list -v -storetype pkcs12 -keystore keystore.p12

将 JKS 密钥库转换为 PKCS12

如果我们已经有 JKS 密钥库,我们可以选择将其迁移到 PKCS12;keytool 有一个方便的命令:

keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.p12 -deststoretype pkcs12

2.) 在您的项目中启用 https

如果您有 application.properties 文件

server.port=8443

server.ssl.key-store-type=PKCS12
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=password
server.ssl.key-alias=tomcat

security.require-ssl=true
Run Code Online (Sandbox Code Playgroud)

如果您有 application.yml 文件

server:
  ssl:
    key-store: classpath:keystore.p12
    key-store-password: password
    key-store-type: pkcs12
    key-alias: tomcat
    key-password: password
  port: 8443
Run Code Online (Sandbox Code Playgroud)

为了在应用程序中实现,我们需要扩展该类WebSecurityConfigurerAdapter,因为该security.require-ssl属性已被弃用。

如果您使用的是旧版本,那么您可以跳过下面提到的代码。

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .requiresChannel()
            .anyRequest()
            .requiresSecure();
    }
}
Run Code Online (Sandbox Code Playgroud)

3.) 将http重定向到https

现在我们已经在 Spring Boot 应用程序中启用了 HTTPS 并阻止了任何 HTTP 请求,我们希望将所有流量重定向到 HTTPS。

Spring 允许在application.properties (or application.yml). 由于我们已将其用于 HTTPS,因此我们必须以编程方式为 Tomcat Web 服务器设置 HTTP 连接器。

@Configuration
public class ServerConfig {

    @Bean
    public ServletWebServerFactory 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(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setScheme("http");
        connector.setPort(8080);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;
    }
}
Run Code Online (Sandbox Code Playgroud)

4.) 将 SSL 证书分发给客户端 当使用自签名 SSL 证书时,我们的浏览器不会信任我们的应用程序,并会警告用户它不安全。对于任何其他客户来说都是一样的。

通过向客户提供我们的证书,可以让客户信任我们的应用程序。

从密钥库中提取 SSL 证书 我们已将证书存储在密钥库中,因此我们需要提取它。同样,keytool 为我们提供了很好的支持:

keytool -export -keystore keystore.jks -alias tomcat -file myCertificate.crt

让浏览器信任 SSL 证书 当使用行业标准 PKCS12 格式的密钥库时,我们应该能够直接使用它,而无需提取证书。

我建议您查看有关如何将 PKCS12 文件导入特定客户端的官方指南。

如果在本地主机上部署应用程序,我们可能需要从浏览器执行进一步的步骤:启用与localhost.

在Chrome中,我们可以在搜索栏中写入以下URL:chrome://flags/#allow-insecure-localhost并激活相对选项。

在 JRE 密钥库中导入 SSL 证书 为了使 JRE 信任我们的证书,我们需要将其导入到 cacerts 中:JRE 信任库负责保存所有可信任的证书。

首先,我们需要知道 JDK 主目录的路径。如果我们使用 Eclipse 或 STS 作为 IDE,找到它的快速方法是转至 Preferences > Java > Installed JRE。如果使用 IntelliJ IDEA,我们可以通过转到“项目结构”>“SDK”来访问此信息,并查看 JDK 主路径字段的值。

然后,从终端提示符中插入以下命令(我们可能需要通过在其前面加上 sudo 以管理员权限运行它):

keytool -importcert -file myCertificate.crt -alias tomcat -keystore $JDK_HOME/jre/lib/security/cacerts

你可以在这里参考 github 上的项目