请求客户端证书进行身份验证

huangapple go评论85阅读模式
英文:

Request client certificate for authentication

问题

我想要为浏览器请求一个用于认证成员的证书。

在Node.js中,我们有类似于http://nategood.com/nodejs-ssl-client-cert-auth-api-rest的东西。

我已经阅读了一些关于TLS的文章,但我真的不太明白如何使用它...

英文:

I would like request a certificate to the browser for authenticate members.

In nodejs we have something like http://nategood.com/nodejs-ssl-client-cert-auth-api-rest

I have read some articles about tls, but I don't really understand how use it...

答案1

得分: 12

这是一个要求客户端证书的简短示例。关键是手动创建和配置http.Server,而不是使用实用程序例程。

package main

import (
	"crypto/tls"
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello cert")
	})
	
	server := &http.Server{
		Addr: ":8090",
		TLSConfig: &tls.Config{
			ClientAuth: tls.RequireAndVerifyClientCert,
		},
	}
	
	server.ListenAndServeTLS("cert.pem", "cert.key")
}

重要的部分是tls.Config结构体,它控制服务器在TLS方面的行为。字段ClientAuth表示客户端证书策略,在我们的例子中是要求客户端证书并验证它。请注意,还有其他可用的策略...

您还应该查看同一结构体的ClientCAs字段,它允许您使用客户端必须验证的根CA列表。

注意:我假设您在服务器端也使用了证书来加密通信。server.ListenAndServeTLS方法仍然会为您完成大部分工作。如果您不需要它,您将需要深入了解此method以手动完成(并使用更低级别的方法server.Serve)。

英文:

Here is a short example of how to require client certificate. The trick is to manually create and configure the http.Server instead of using the utilitary routines.

package main

import (
	"crypto/tls"
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello cert")
	})
	
	server := &http.Server{
		Addr: ":8090",
		TLSConfig: &tls.Config{
			ClientAuth: tls.RequireAndVerifyClientCert,
		},
	}
	
	server.ListenAndServeTLS("cert.pem", "cert.key")
}

The important part is the tls.Config struct which control the way the server will behave with TLS. The field ClientAuth hold the client certificate policy, in our case Require a client certificate and verify it. Note that other policies are available…

You should also have a look at the ClientCAs field of the same struct, that allow you to use a list of root CA the client must verify against.

Note: I assume that you are also using a certificate server side to encrypt the communication. The server.ListenAndServeTLS method still do a lot of the work for you as a side-effect. If you don't need it, you will have to dive into this method to do it manually (and use the even-lower-level method server.Serve).

huangapple
  • 本文由 发表于 2014年6月12日 17:36:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/24181081.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定