package main
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// Create main Gin engine
r := gin.Default()
// Token authentication middleware for /api/files server
filesServer := gin.New()
filesServer.Use(tokenAuthMiddleware())
// Endpoint handler for /api/files
filesServer.GET("/api/files", mtlsAuthMiddleware(), func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "mTLS protected API endpoint accessed successfully!"})
})
// Start the server for /api/files
go func() {
if err := filesServer.RunTLS(":8081", "server.crt", "server.key"); err != nil {
log.Fatalf("Failed to start /api/files server: %v", err)
}
}()
// Load CA certificate for /api/protected server
caCert, err := ioutil.ReadFile("ca.crt")
if err != nil {
log.Fatalf("Failed to read CA certificate: %v", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
// Configure TLS with client certificate validation for /api/protected server
tlsConfig := &tls.Config{
ClientCAs: caCertPool,
ClientAuth: tls.RequireAndVerifyClientCert,
}
// Enable client certificate validation for /api/protected server
protectedServer := &http.Server{
Addr: ":8080",
Handler: r,
TLSConfig: tlsConfig,
}
// Endpoint handler for /api/protected
r.GET("/api/protected", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Protected API endpoint accessed successfully!"})
})
// Start the server for /api/protected
log.Printf("Server for /api/protected started. Listening on port 8080...")
if err := protectedServer.ListenAndServeTLS("server.crt", "server.key"); err != nil {
log.Fatalf("Failed to start /api/protected server: %v", err)
}
}
// Token authentication middleware
func tokenAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
if token != "Bearer your_token" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
c.Next()
}
}
// mTLS authentication middleware
func mtlsAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Check if the client presented a certificate
if len(c.Request.TLS.PeerCertificates) == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
// Verify the client certificate
_, err := c.Request.TLS.PeerCertificates[0].Verify(x509.VerifyOptions{
Roots: c.Request.TLS.Config.ClientCAs,
Intermediates: x509.NewCertPool(),
})
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
c.Next()
}
}
No comments:
Post a Comment