使用https在Java中休息API [英] Rest api in java using https

查看:82
本文介绍了使用https在Java中休息API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 GET POST 等在Java中创建 Restservices 时,然后使用 http协议.一旦我使用https,就会出现错误.

when I am creating Restservices in java using GET, POST etc then I am requesting them using http protocol. as soon as i use https it gives error.

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

但是当我使用 https

https://localhost:8080/demorest/webapi/aliens

我收到错误消息网站无法提供安全的连接

需要进行哪些修改才能使其与 https 兼容.

what modification is required to make them compatible with https.

推荐答案

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

As you mentioned you are new to APIs here is a detailed answer for you.

答案基于您正在使用tomcat服务器的假设.有4个步骤可让应用程序在https上运行,下面是红色

Answer is based on assumption that you are using tomcat server. There is 4 step approach to have application running on https, red below

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

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

If you dont already have ssl certificate generate yourself using keytool. Keytool is a certificate management utility provided together with the JDK, so if you have the JDK installed, you should already have keytool available.

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

Let's open our Terminal prompt and write the following command to create a JKS keystore:

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

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

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

To create a PKCS12 keystore, and we should, the command is the following:

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

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

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

Let's have a closer look at the command we just run:

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.

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

When running the previous command, we will be asked to input some information, but we are free to skip all of it (just press Return to skip an option). When asked if the information is correct, we should type yes. Finally, we hit return to use the keystore password as key password as well.

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

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

Verify the keystore content To check the content of the keystore following the JKS format, we can use keytool again:

keytool -list -v -keystore keystore.jks

keytool -list -v -keystore keystore.jks

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

To test the content of a keystore following the PKCS12 format:

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

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

将JKS密钥库转换为PKCS12

Convert a JKS keystore into PKCS12

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

Should we have already a JKS keystore, we have the option to migrate it to PKCS12; keytool has a convenient command for that:

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

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

2.)要在项目中启用https

2.) To Enable https in your project

如果您有一个application.properties文件

If you have a application.properties file

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

如果有application.yml文件

If you have application.yml file

server:
  ssl:
    key-store: classpath:keystore.p12
    key-store-password: password
    key-store-type: pkcs12
    key-alias: tomcat
    key-password: password
  port: 8443

要在应用程序中实现,我们需要扩展 WebSecurityConfigurerAdapter 类,因为不推荐使用 security.require-ssl 属性.

To achieve in application, we need to extend the WebSecurityConfigurerAdapter class, since the security.require-ssl property has been deprecated.

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

if you are on older version then you can skip below mentioned code.

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .requiresChannel()
            .anyRequest()
            .requiresSecure();
    }
}

3.)将http重定向到https

3.) Redirect http to https

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

Now that we have enabled HTTPS in our Spring Boot application and blocked any HTTP request, we want to redirect all traffic to HTTPS.

Spring允许在 application.properties(或application.yml)中仅定义一个网络连接器.由于我们已将其用于HTTPS,因此必须以编程方式为Tomcat Web服务器设置HTTP连接器.

Spring allows defining just one network connector in application.properties (or application.yml). Since we have used it for HTTPS, we have to set the HTTP connector programmatically for our Tomcat web server.

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

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

4.) Distribute the SSL certificate to clients When using a self-signed SSL certificate, our browser won't trust our application and will warn the user that it's not secure. And that'll be the same with any other client.

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

It's possible to make a client trust our application by providing it with our certificate.

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

Extract an SSL certificate from a keystore We have stored our certificate inside a keystore, so we need to extract it. Again, keytool supports us very well:

keytool-出口-keystore keystore.jks-别名tomcat-文件myCertificate.crt

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

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

Make a browser trust an SSL certificate When using a keystore in the industry-standard PKCS12 format, we should be able to use it directly without extracting the certificate.

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

I suggest you check the official guide on how to import a PKCS12 file into your specific client.

如果要在localhost上部署应用程序,我们可能需要从浏览器中进一步采取步骤:启用与 localhost 的不安全连接.

If deploying the application on localhost, we may need to do a further step from our browser: enabling insecure connections with localhost.

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

In Chrome, we can write the following URL in the search bar: chrome://flags/#allow-insecure-localhost and activate the relative option.

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

Import an SSL certificate inside the JRE keystore To make the JRE trust our certificate, we need to import it inside cacerts: the JRE trust store in charge of holding all certificates that can be trusted.

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

First, we need to know the path to our JDK home. A quick way to find it, if we are using Eclipse or STS as our IDE, is by going to Preferences > Java > Installed JREs. If using IntelliJ IDEA, we can access this information by going to Project Structure > SDKs and look at the value of the JDK home path field.

然后,在终端提示下,插入以下命令(我们可能需要通过以sudo为前缀来以管理员权限运行它):

Then, from our Terminal prompt, let's insert the following command (we might need to run it with administrator privileges by prefixing it with sudo):

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

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

您可以在github 此处上引用项目.

you can refer project on github here

这篇关于使用https在Java中休息API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆