Menghandle serangan XSS(Cross-Site Scripting) di Gofiber
Untuk mengatasi serangan XSS (Cross-Site Scripting) dalam aplikasi GoFiber, kita dapat menggunakan paket github.com/microcosm-cc/bluemonday untuk membersihkan input pengguna. Berikut langkah-langkah yang diperlukan untuk mengimplementasikan middleware XSS dan memperbarui controller untuk menggunakan middleware tersebut.
Langkah-langkah:
Install paket bluemonday: Jalankan perintah berikut untuk menginstall paket bluemonday:
go get github.com/microcosm-cc/bluemonday
Buat file xssMiddleware.go di dalam folder helpers: Buat middleware untuk membersihkan input dari XSS.
// src/helpers/xssMiddleware.go
package helpers
import "github.com/microcosm-cc/bluemonday"
func XSSMiddleware(param map[string]interface{}) map[string]interface{} {
policy := bluemonday.UGCPolicy()
// Sanitize all string fields
for key, value := range param {
if str, ok := value.(string); ok {
param[key] = policy.Sanitize(str)
}
}
return param
}
Perbarui CategoryControllers.go untuk menggunakan middleware XSS:
// src/controllers/CategoryControllers.go
package controllers
import (
"strconv"
"github.com/gofiber/fiber/v2"
"github.com/mitchellh/mapstructure"
"gofiber/src/helpers"
"gofiber/src/models"
)
func CreateCategory(c *fiber.Ctx) error {
var category map[string]interface{}
if err := c.BodyParser(&category); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "Failed to parse request body",
})
}
category = helpers.XSSMiddleware(category)
// Convert map to Category model using mapstructure
var newCategory models.Category
mapstructure.Decode(category, &newCategory)
errors := helpers.ValidateStruct(newCategory)
if len(errors) > 0 {
return c.Status(fiber.StatusUnprocessableEntity).JSON(errors)
}
models.PostCategory(&newCategory)
return c.Status(fiber.StatusCreated).JSON(fiber.Map{
"message": "Category created successfully",
})
}
func UpdateCategory(c *fiber.Ctx) error {
id, _ := strconv.Atoi(c.Params("id"))
var updatedCategory map[string]interface{}
if err := c.BodyParser(&updatedCategory); err != nil {
c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"message": "Invalid request body",
})
return err
}
updatedCategory = helpers.XSSMiddleware(updatedCategory)
// Convert map to Category model using mapstructure
var newUpdatedCategory models.Category
mapstructure.Decode(updatedCategory, &newUpdatedCategory)
errors := helpers.ValidateStruct(newUpdatedCategory)
if len(errors) > 0 {
return c.Status(fiber.StatusUnprocessableEntity).JSON(errors)
}
models.UpdateCategory(id, &newUpdatedCategory)
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"message": "Category updated successfully",
})
}
Perbarui ProductControllers.go untuk menggunakan middleware XSS:
// src/controllers/ProductControllers.go
package controllers
import (
"fmt"
"strconv"
"github.com/gofiber/fiber/v2"
"github.com/mitchellh/mapstructure"
"gofiber/src/helpers"
"gofiber/src/models"
)
func CreateProduct(c *fiber.Ctx) error {
var newProduct map[string]interface{}
if err := c.BodyParser(&newProduct); err != nil {
c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"message": "Invalid request body",
})
return err
}
newProduct = helpers.XSSMiddleware(newProduct)
var product models.Product
mapstructure.Decode(newProduct, &product)
errors := helpers.ValidateStruct(product)
if len(errors) > 0 {
return c.Status(fiber.StatusUnprocessableEntity).JSON(errors)
}
models.PostProduct(&product)
return c.Status(fiber.StatusCreated).JSON(fiber.Map{
"message": "Product created successfully",
})
}
func UpdateProduct(c *fiber.Ctx) error {
id, _ := strconv.Atoi(c.Params("id"))
var updatedProduct map[string]interface{}
if err := c.BodyParser(&updatedProduct); err != nil {
c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"message": "Invalid request body",
})
return err
}
updatedProduct = helpers.XSSMiddleware(updatedProduct)
var product models.Product
mapstructure.Decode(updatedProduct, &product)
errors := helpers.ValidateStruct(product)
if len(errors) > 0 {
return c.Status(fiber.StatusUnprocessableEntity).JSON(errors)
}
err := models.UpdateProduct(id, &product)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"message": fmt.Sprintf("Failed to update product with ID %d", id),
})
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"message": fmt.Sprintf("Product with ID %d updated successfully", id),
})
}
Penjelasan Konsep
CORS (Cross-Origin Resource Sharing): CORS adalah mekanisme yang memungkinkan server untuk menentukan sumber (domain, skema, atau port) yang diizinkan untuk mengakses sumber daya di server tersebut. Dalam kode main.go, kita mengaktifkan middleware CORS untuk mengizinkan akses lintas domain dengan konfigurasi yang fleksibel.
Mengatasi XSS (Cross-Site Scripting): XSS adalah serangan di mana penyerang menyisipkan skrip berbahaya ke dalam konten yang dilihat oleh pengguna. Menggunakan github.com/microcosm-cc/bluemonday, kita dapat membersihkan input pengguna dari potensi skrip berbahaya sebelum menyimpannya ke dalam basis data atau menampilkan kembali ke pengguna. File xssMiddleware.go berfungsi untuk membersihkan semua field string dalam input menggunakan kebijakan sanitasi dari bluemonday.
Dengan menerapkan langkah-langkah di atas, kita dapat meningkatkan keamanan aplikasi GoFiber dengan mencegah serangan XSS dan mengizinkan akses lintas domain yang aman melalui CORS.