Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request client certificate for authentication

Tags:

ssl

go

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...

like image 361
Druxtan Avatar asked Jun 12 '14 09:06

Druxtan


1 Answers

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

like image 83
Elwinar Avatar answered Nov 03 '22 19:11

Elwinar