> For the complete documentation index, see [llms.txt](https://zakimaliki.gitbook.io/gofiber/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zakimaliki.gitbook.io/gofiber/basic-backend-dengan-gofiber-part-2/menghandle-serangan-xss-cross-site-scripting-di-gofiber.md).

# 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:

1. **Install paket `bluemonday`**: Jalankan perintah berikut untuk menginstall paket `bluemonday`:

   ```bash
   go get github.com/microcosm-cc/bluemonday
   ```
2. **Buat file `xssMiddleware.go` di dalam folder `helpers`**: Buat middleware untuk membersihkan input dari XSS.

   ```go
   // 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
   }
   ```
3. **Perbarui `CategoryControllers.go` untuk menggunakan middleware XSS**:

   ```go
   // 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",
       })
   }
   ```
4. **Perbarui `ProductControllers.go` untuk menggunakan middleware XSS**:

   ```go
   // 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.

sumber : Dokumentasi

{% embed url="<https://github.com/zakimaliki/basic_gofiber_part_1/tree/629e99cbea1aca960b0e57fa7b23752fa96e867a>" %}
