1.首先进入阿里云服务器,搜索ssl证书,免费申请,dns会自动解析该证书,所以不用设置

2.下载tomcat和nginx服务器类型的证书

3.将tomcat服务器类型的文件解压,打开,获得pfx文件,放入项目的resources文件中

4.打开yml配置文件,进行SSL配置,并将http重定向到https

custom:http:port: 8002 # 自定义http启动端口server: # https端口port: 8443ssl:key-store: classpath:8002091_suqiqaq.cn.pfx # pfk存放路径key-store-type: PKCS12  # tomcat服务器类型默认key-store-password: 1TFM7IpB # txt密码粘贴即可

这里注意,server.port必须是https的端口,不然会出现https和http占用同一个端口

5.添加配置类,让http重定向到https

package com.guigusuqi.commonutils.config;import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** https配置,将http请求全部转发到https*/
@Configuration
public class HttpsConfig
{@Value("${custom.http.port}")private Integer httpPort;@Value("${server.port}")private Integer httpsPort;@Beanpublic TomcatServletWebServerFactory servletContainer() {// 将http请求转换为https请求TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {@Overrideprotected void postProcessContext(Context context) {SecurityConstraint constraint = new SecurityConstraint();// 默认为NONEconstraint.setUserConstraint("CONFIDENTIAL");SecurityCollection collection = new SecurityCollection();// 所有的东西都httpscollection.addPattern("/*");constraint.addCollection(collection);context.addConstraint(constraint);}};tomcat.addAdditionalTomcatConnectors(httpConnector());return tomcat;}/*** 强制将所有的http请求转发到https* @return httpConnector*/@Beanpublic Connector httpConnector() {Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");connector.setScheme("http");// connector监听的http端口号connector.setPort(httpPort);connector.setSecure(false);// 监听到http的端口号后转向到的https的端口号connector.setRedirectPort(httpsPort);return connector;}
}

如果我们不想强制所有的请求都重定向到https或者某些功能接口需要http的支持等等,我们也可以同时开启http协议和https协议。

package cn.zlc.servicehttps.config;import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class HttpsConfig {@Value("${server.port}")private Integer httpPort;@Beanpublic TomcatServletWebServerFactory servletContainer() {TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();tomcat.addAdditionalTomcatConnectors(httpConnector());return tomcat;}@Beanpublic Connector httpConnector() {Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");connector.setPort(httpPort);return connector;}}

如果我们通过http端口请求的话,不会自动重定向到https端口,而且也不会提示需要TLS端口请求。而使用https请求的时候就会提示不安全,如果是放到服务器上访问https就正常了;

6.将SpringBoot项目打为Jar包放置到Linux服务器下

如果是宝塔 记得把--server.port=8002删掉,这里yaml配置的是8443端口,不然会覆盖掉yaml的配置,导致https和http又公用了一个端口

访问后端接口文档成功

6. 安全组放行443端口,这个端口类似于http的80端口

7.配置 nginx ,使用域名进行访问 

将前端的http协议,重定向到https协议,https协议默认是443端口,所以还需要在443端口进行配置,这里需要配置ssl证书路径

server
{listen 80;server_name suqiqaq.cn;index index.php index.html index.htm default.php default.htm default.html;# ssl证书路径ssl_certificate     /home/cert/8002091_suqiqaq.cn.pem;ssl_certificate_key /home/cert/8002091_suqiqaq.cn.key;root /home/hospital/app-api/dist;# $request_uri #包含请求参数的原始URI,不包含主机名# 如:”/foo/bar/arg”# $server_name #服务器名称# 将请求转成https,https协议默认是443端口,所以还需要在443端口进行配置return 301 https://$server_name$request_uri;
}

在nginx主配置文件中监听443端口,并将请求反向代理到https协议的8443端口

注意,这里需要把前端项目路径加上,不然宝塔一直提示没有该站点

server
{listen 443 ssl;root /home/hospital/app-api/dist;index index.php index.html index.htm default.php default.htm default.html;server_name suqiqaq.cn;ssl_certificate     /home/cert/8002091_suqiqaq.cn.pem;ssl_certificate_key /home/cert/8002091_suqiqaq.cn.key;location ^~ /hospitalApi/{proxy_pass   https://127.0.0.1:8443/;# 这里是重点,如果上面的proxy_pass写成https的话这段是必须要配置的,不然只能访问页面,而页面调用端口不行proxy_ssl_certificate     /home/cert/8002091_suqiqaq.cn.pem;proxy_ssl_certificate_key /home/cert/8002091_suqiqaq.cn.key;proxy_ssl_protocols       TLSv1 TLSV1.1 TLSv1.2;proxy_ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;proxy_ssl_session_reuse  on;proxy_redirect off;proxy_set_header Host $proxy_host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Nginx-Proxt true;proxy_set_header HTTP_X_FORWORDED_FOR $remote_addr;}
}

8.将前端的baseURL改为/hospitalApi,并把前端vue.config.js改为https协议,打包上线

vue.config.js:

'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')function resolve(dir) {return path.join(__dirname, dir)
}const name = defaultSettings.title; // page title// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = 8080 // dev port// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {/*** You will need to set publicPath if you plan to deploy your site under a sub path,* for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,* then publicPath should be set to "/bar/".* In most cases please use '/' !!!* Detail: https://cli.vuejs.org/config/#publicpath*/publicPath: '/',outputDir: 'dist',assetsDir: 'static',lintOnSave: process.env.NODE_ENV === 'development',productionSourceMap: false,devServer: {port: port,open: true,overlay: {warnings: false,errors: true},https: true // 开启https协议// before: require('./mock/mock-server.js')},configureWebpack: {// provide the app's title in webpack's name field, so that// it can be accessed in index.html to inject the correct title.name: name,resolve: {alias: {'@': resolve('src')}}},chainWebpack(config) {// it can improve the speed of the first screen, it is recommended to turn on preloadconfig.plugin('preload').tap(() => [{rel: 'preload',// to ignore runtime.js// https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],include: 'initial'}])// when there are many pages, it will cause too many meaningless requestsconfig.plugins.delete('prefetch')// set svg-sprite-loaderconfig.module.rule('svg').exclude.add(resolve('src/icons')).end()config.module.rule('icons').test(/\.svg$/).include.add(resolve('src/icons')).end().use('svg-sprite-loader').loader('svg-sprite-loader').options({symbolId: 'icon-[name]'}).end()config.when(process.env.NODE_ENV !== 'development',config => {config.plugin('ScriptExtHtmlWebpackPlugin').after('html').use('script-ext-html-webpack-plugin', [{// `runtime` must same as runtimeChunk name. default is `runtime`inline: /runtime\..*\.js$/}]).end()config.optimization.splitChunks({chunks: 'all',cacheGroups: {libs: {name: 'chunk-libs',test: /[\\/]node_modules[\\/]/,priority: 10,chunks: 'initial' // only package third parties that are initially dependent},elementUI: {name: 'chunk-elementUI', // split elementUI into a single packagepriority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or apptest: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm},commons: {name: 'chunk-commons',test: resolve('src/components'), // can customize your rulesminChunks: 3, //  minimum common numberpriority: 5,reuseExistingChunk: true}}})// https:// webpack.js.org/configuration/optimization/#optimizationruntimechunkconfig.optimization.runtimeChunk('single')})}
}

request.js:

import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
import {config} from "@vue/test-utils";// 创建axios实例
const service = axios.create({// baseURL:process.env.VUE_APP_BASE_API,baseURL: "/hospitalApi", // api 的 base_url// baseURL: "http://suqiqaq.cn:8002", // api 的 base_urltimeout: 10000000 // 请求超时时间
})
// http://suqiqaq.cn:8002/doc.html#/%E8%8B%8F%E4%B8%83/%E7%99%BB%E5%BD%95%E7%AE%A1%E7%90%86/loginUsingPOST
// request拦截器
service.interceptors.request.use(config => {config.headers['Content-Type'] = "application/json;charset=utf-8";if (store.getters.token) {config.headers['Authorization'] = getToken() // 让每个请求携带token}return config},error => {// Do something with request errorconsole.log(error); // for debugPromise.reject(error)}
)// response 拦截器
service.interceptors.response.use(response => {/*** code为非200是抛错 可结合自己业务进行修改*/const res = response.data;if (res.code !== 200){Message({message: res.message,type: 'response error',duration: 5 * 1000});// 408:非法的token; 400:其他客户端登录了;  401:Token 过期了;if (res.code === 408 || res.code === 400 || res.code === 401){if (getToken()){MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录','确定登出',{confirmButtonText: '重新登录',cancelButtonText: '取消',type: 'warning',duration: 5 * 1000}).then(() => {store.dispatch('FedLogOut').then(() => {location.reload() // 为了重新实例化vue-router对象 避免bug})})}}return Promise.reject('error')} else{return response.data}},error => {console.log('err' + error) // for debugMessage({message: error.message,type: 'error',duration: 5 * 1000})return Promise.reject(error)}
)export default service

把前端项目上传到服务器之后即可,搞定!

springboot项目配置ssl证书相关推荐

  1. SpringBoot项目配置SSL证书微信小程序jar包

    本文主要针对SpringBoot微信小程序jar包运行的项目如何配置SSL证书. 关于域名:请确定域名已经获得ICP备案,服务器对外端口开放. 根据⼩程序官⽅⽂档描述,微信⼩程序的wx.request ...

  2. Spring Boot项目配置ssl证书及自定义ssl端口号

    好吧,一切不带s的http裸奔都是耍流氓. 我们知道在一个Web服务器(e.g. Tomcat, Websphere, Nginx)上配置ssl证书很容易,那么如何在SpringBoot这种内嵌了服务 ...

  3. Nginx部署前后端分离项目,配置SSL证书,结果刷新报500异常

    在之前还没有配置SSL证书的时候,项目使用一切正常,也不会出现什么刷新报500错误,就在今天,我进行了SSL证书配置之后,就显得不正常了,页面刷新会报500异常,经过一段时间排查,最终找到了产生问题的 ...

  4. SpringBoot框架部署配置SSL证书

    1.拿到证书,解压得到证书文件以及password.txt 2.使用jdk自带的keytool将文件转换为JKS格式 3.cmd进入java的jdk的bin目录 输入:keytool -importk ...

  5. node配置ssl证书_在Linux服务器上部署node项目(git部署,forever持续运行,配置SSL证书)...

    一.环境部署 1.下载安装包: wget https://nodejs.org/dist/v9.9.0/node-v9.9.0-linux-x64.tar.xz 2.解压并进入目录: xz -d no ...

  6. JavaWeb项目部署服务器并配置ssl证书教程

    JavaWeb项目部署服务器并配置ssl证书教程 相信大家学了1.2年的编程后可能已经学会了自己写web项目,但是也只能在自己本地玩耍,十分的打击学习热情(主要是没办法跟朋友装杯).本文是一篇较为详细 ...

  7. windows配置NGINX、NGINX配置SSL证书通过HTTPS访问、使用HTTPS通过NGINX代理访问服务器端项目

    1.windows配置nginx 1)在nginx官网下载稳定版nginx,nginx官网:http://nginx.org/en/download.html 2)解压文件,注:存放目录最好不要带有中 ...

  8. springboot配置SSL证书设置https协议访问的端口

    配置SSL证书需要证书文件 和 密钥 1. 将证书文件移动到resources目录下 2. 在yml配置文件中配置如下: server:port: 443 #服务端口ssl:key-store: cl ...

  9. Springboot配置SSL证书后启动提示端口被占用

    Springboot配置SSL证书后启动提示端口被占用 最近在做小程序,然后因为小程序只支持https的请求 所以给域名申请了一个SSL证书进行配置 配置SSL证书的方法在这里也捎带提一下吧 用的是s ...

最新文章

  1. 微信推送模板消息的PHP代码整理
  2. 一文看懂70年的人工智能简史
  3. opencv中的push_back()函数
  4. java 平均值_Java岗招聘标准差强人意,薪资比拼,Java程序员表示“我太难了”...
  5. python计算每月工资-5万的工资,用Python算一算少交多少税?
  6. Web Deploy发布网站及常见问题解决方法(图文)
  7. windows下的工具链 树莓派_Windows下交叉编译Qt 5.14.2至树莓派平台 QEMU模拟树莓派...
  8. python小型编程_学习Python编程的11个资源
  9. swoole 启动流程_Swoole 启动一个服务,开启了哪些进程和线程?
  10. Python——匿名函数lambda
  11. Python Cookbook手记II
  12. beta 发布的相关评论
  13. 如何在 Git 里撤销(几乎)任何操作
  14. win10绿联usb转串口_USB转串口DB9驱动安装与设置方法
  15. 网络协议学习---LLDP协议学习
  16. webgl点光源的漫反射
  17. java怎么实现历史修改记录_java历史记录封装实现
  18. G2O和Sliding Window中的Marginalization
  19. 50.纯 CSS 创作一个永动的牛顿摆
  20. 好好学习:个人知识管理精进指南

热门文章

  1. Linux安装FTP及使用python上传下载ftp
  2. centos7设置密码策略_CentOS7 设置密码复杂度
  3. 【Vscode+Latex】Mac 系统Vscode的LaTeX中插入参考文献
  4. Java反射之创建对象的四种方式
  5. Ravens rise to 8th most valuable NFL franchise
  6. Picamera2初体验(四):延时摄影
  7. 数位dp(邦的轩辕)
  8. 计算机安全防护厂商,全球安全行业共抗暴雷 中国厂商表现抢眼
  9. EOJ #3601 恢复古诗
  10. 带有表情符号的文本情感分类实验