一、启动https
beego实现https,通过配置文件conf/app.conf,加入https相关配置
EnableDocs = true
EnableHTTPS=true
EnableHttpTLS = true
HttpsPort = 8010
HTTPSCertFile = "conf/server.crt"
HTTPSKeyFile = "conf/server.key"
二、如何实现https的双向认证
我们都是知道,c/s 架构中,一般都是https单向认证模式,那么如何实现双向认证呢?
查看beego的官方文档并没有找到开启双向认证的地方,通过查看beego源码,具体实现在beego–>app.go里,在beego–>config.go 文件中发现相关配置参数,如下:
// Listen holds for http and https related config
type Listen struct {
Graceful bool // Graceful means use graceful module to start the server
ServerTimeOut int64
ListenTCP4 bool
EnableHTTP bool
HTTPAddr string
HTTPPort int
AutoTLS bool
Domains []string
TLSCacheDir string
EnableHTTPS bool
EnableMutualHTTPS bool --> 开启双向认证
HTTPSAddr string
HTTPSPort int
HTTPSCertFile string
HTTPSKeyFile string
TrustCaFile string --> 配置ca证书
ClientAuth tls.ClientAuthType
EnableAdmin bool
AdminAddr string
AdminPort int
EnableFcgi bool
EnableStdIo bool // EnableStdIo works with EnableFcgi Use FCGI via standard I/O
}
同步conf/app.conf中添加如下配合
EnableMutualHTTPS=true --> 启用双向认证
EnableHttpTLS = true
HttpsPort = 8010
HTTPSCertFile = "conf/server.crt"
HTTPSKeyFile = "conf/server.key"
TrustCaFile = "conf/ca.crt" --> 配置ca.crt证书
三、服务端开启双向认证,客户端也要有相应的实现
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net/http"
)
var CA_CRT string = "conf/ca.crt"
var CLIENT_CRT string = "conf/client.crt"
var CLIENT_KEY string = "conf/client.key"
func main() {
pool := x509.NewCertPool()
caCertPath := CA_CRT
caCrt, err := ioutil.ReadFile(caCertPath)
if err != nil {
fmt.Println("ReadFile err:", err)
return
}
pool.AppendCertsFromPEM(caCrt)
cliCrt, err := tls.LoadX509KeyPair(CLIENT_CRT, CLIENT_KEY)
if err != nil {
fmt.Println("Loadx509keypair err:", err)
return
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: pool,
Certificates: []tls.Certificate{cliCrt},
},
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://127.0.0.1:8010")
if err != nil {
fmt.Println("Get error:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}