github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/core/middleware/require_cert.go (about)

     1  /*
     2  Copyright hechain. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package middleware
     8  
     9  import (
    10  	"net/http"
    11  )
    12  
    13  type requireCert struct {
    14  	next http.Handler
    15  }
    16  
    17  // RequireCert is used to ensure that a verified TLS client certificate was
    18  // used for authentication.
    19  func RequireCert() Middleware {
    20  	return func(next http.Handler) http.Handler {
    21  		return &requireCert{next: next}
    22  	}
    23  }
    24  
    25  func (r *requireCert) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    26  	switch {
    27  	case req.TLS == nil:
    28  		fallthrough
    29  	case len(req.TLS.VerifiedChains) == 0:
    30  		fallthrough
    31  	case len(req.TLS.VerifiedChains[0]) == 0:
    32  		logger.Warnw("Client request not authorized, client must pass a valid client certificate for this operation", "URL", req.URL, "Method", req.Method, "RemoteAddr", req.RemoteAddr)
    33  		w.WriteHeader(http.StatusUnauthorized)
    34  	default:
    35  		r.next.ServeHTTP(w, req)
    36  	}
    37  }