英文:
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
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论