Learn Fiber · 10/14

Authentication and Security

7 min read

Authentication and Security 🛡️

Welcome to the "Authentication and Security" guide for the Fiber course. Here, we'll explore how to protect your web applications from unauthorized access and common security threats.

1. Securing Routes: Introduction to Auth

Definition and Problem:

Authentication is the process of verifying the identity of a user or system. In web development, it's crucial to restrict access to certain parts of your application. For example, you wouldn't want just anyone to be able to view a user's private profile or delete data from your database. The problem is how to allow legitimate users access while keeping unauthorized individuals out.

How it Solves the Problem:

Authentication solves this by providing a mechanism for users to prove who they are. Once a user is authenticated, your application can then grant them access to the appropriate resources. This is typically done by having the user provide credentials, such as a username and password, which the server then validates.

Think of it like a bouncer at a club. The bouncer's job is to check IDs to make sure only people who are supposed to be there get in. In this analogy, the bouncer is your authentication middleware, and the ID is the user's credentials.


2. Implementing Basic Auth Middleware

Definition and Problem:

HTTP Basic Authentication is a simple authentication scheme built into the HTTP protocol. It allows a user agent (like a web browser) to provide a username and password when making a request. The problem with basic auth is that it's, well, basic. It sends credentials in a way that's easily decodable if not used over a secure connection (HTTPS). However, for simple, internal tools or APIs where security isn't a top concern, it can be a quick and easy way to add a layer of protection.

How it Solves the Problem:

Fiber provides a BasicAuth middleware that makes implementing basic authentication straightforward. It works by checking for an Authorization header in incoming requests. If the header is missing or the credentials are invalid, it responds with a 401 Unauthorized status, prompting the user for their username and password.

Getting Started:

First, you'll need to have Fiber installed. If you don't, you can install it with the following command:

bash
go get -u github.com/gofiber/fiber/v2

Example:

Here's a simple example of how to use the BasicAuth middleware to protect a route:

go
package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/basicauth"
)

func main() {
    app := fiber.New()

    // Provide a minimal config
    app.Use(basicauth.New(basicauth.Config{
        Users: map[string]string{
            "john":  "doe",
            "admin": "123456",
        },
    }))

    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, World!")
    })

    app.Listen(":3000")
}

In this example, we've created a new Fiber app and used the basicauth.New middleware. We've configured it with a map of users and their passwords. Now, if you try to access the / route, you'll be prompted for a username and password.


3. Stateless Authentication with JSON Web Tokens (JWT)

Definition and Problem:

JSON Web Token (JWT) is an open standard for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs are a popular method for handling authentication in a stateless way. This means that the server doesn't need to store any information about the user's session. Each request from the client includes the JWT, which the server can then use to identify the user and determine their permissions.

How it Solves the Problem:

JWTs solve the problem of session management in a scalable way. In traditional session-based authentication, the server has to store session data for every logged-in user. This can become a bottleneck as the number of users grows. With JWTs, the session data is stored on the client-side, in the token itself. This makes it easy to scale your application across multiple servers without having to worry about synchronizing session data.

How JWT Works:

A JWT is made up of three parts: a header, a payload, and a signature.

  • Header: The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.
  • Payload: The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data.
  • Signature: To create the signature part, you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign it.

Getting Started:

To use JWT with Fiber, you'll need to install the Fiber JWT middleware and the Go JWT library:

bash
go get -u github.com/gofiber/contrib/jwt
go get -u github.com/golang-jwt/jwt/v5

Example:

Here's an example of how to implement JWT authentication in a Fiber app:

go
package main

import (
    "time"

    "github.com/gofiber/fiber/v2"
    jwtware "github.com/gofiber/contrib/jwt"
    "github.com/golang-jwt/jwt/v5"
)

func main() {
    app := fiber.New()

    // Login route
    app.Post("/login", login)

    // Unauthenticated route
    app.Get("/", accessible)

    // JWT Middleware
    app.Use(jwtware.New(jwtware.Config{
        SigningKey: jwtware.SigningKey{Key: []byte("secret")},
    }))

    // Restricted Routes
    app.Get("/restricted", restricted)

    app.Listen(":3000")
}

func login(c *fiber.Ctx) error {
    user := c.FormValue("user")
    pass := c.FormValue("pass")

    // Throws Unauthorized error
    if user != "john" || pass != "doe" {
        return c.SendStatus(fiber.StatusUnauthorized)
    }

    // Create token
    token := jwt.New(jwt.SigningMethodHS256)

    // Set claims
    claims := token.Claims.(jwt.MapClaims)
    claims["name"] = "John Doe"
    claims["admin"] = true
    claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

    // Generate encoded token and send it as response.
    t, err := token.SignedString([]byte("secret"))
    if err != nil {
        return c.SendStatus(fiber.StatusInternalServerError)
    }

    return c.JSON(fiber.Map{"token": t})
}

func accessible(c *fiber.Ctx) error {
    return c.SendString("Accessible")
}

func restricted(c *fiber.Ctx) error {
    user := c.Locals("user").(*jwt.Token)
    claims := user.Claims.(jwt.MapClaims)
    name := claims["name"].(string)
    return c.SendString("Welcome " + name)
}

In this example, we have a /login route that generates a JWT for the user. The JWT is then used to access the /restricted route, which is protected by the JWT middleware.


4. Protecting Against Common Vulnerabilities: Helmet and CSRF

Definition and Problem:

Web applications are constantly under attack from a variety of threats. Some of the most common vulnerabilities include Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), and clickjacking. These attacks can be used to steal user data, hijack sessions, and even take control of the entire application.

How it Solves the Problem:

Fiber provides middleware to help protect against these common vulnerabilities. The Helmet middleware sets various HTTP headers to help secure your app, while the CSRF middleware protects against Cross-Site Request Forgery attacks.

Helmet Middleware:

The Helmet middleware is a collection of smaller middleware functions that set security-related HTTP headers. These headers can help protect against a variety of attacks, including:

  • XSS Protection: Helps prevent cross-site scripting attacks.
  • Content-Type No Sniff: Prevents the browser from MIME-sniffing a response away from the declared content-type.
  • X-Frame-Options: Provides clickjacking protection.
  • HSTS Max Age: Sets the Strict-Transport-Security header, which tells browsers to only communicate with your server over HTTPS.

Getting Started with Helmet:

To use the Helmet middleware, you first need to install it:

bash
go get -u github.com/gofiber/helmet/v2

Example of Helmet:

Here's how to use the Helmet middleware in your Fiber app:

go
package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/helmet/v2"
)

func main() {
    app := fiber.New()

    app.Use(helmet.New())

    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, World!")
    })

    app.Listen(":3000")
}

CSRF Middleware:

Cross-Site Request Forgery (CSRF) is an attack that tricks the victim into submitting a malicious request. It inherits the identity and privileges of the victim to perform an undesired function on the victim's behalf.

The CSRF middleware for Fiber helps protect against these attacks by creating and validating a CSRF token for each user session.

Getting Started with CSRF:

To use the CSRF middleware, you'll first need to install it:

bash
go get -u github.com/gofiber/fiber/v2/middleware/csrf

Example of CSRF:

Here's an example of how to use the CSRF middleware in your Fiber app:

go
package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/csrf"
    "github.com/gofiber/fiber/v2/middleware/session"
)

func main() {
    app := fiber.New()

    // Create a new session store
    store := session.New()

    // Use the CSRF middleware
    app.Use(csrf.New(csrf.Config{
        Session: store,
    }))

    app.Get("/", func(c *fiber.Ctx) error {
        // Pass the CSRF token to the template
        return c.Render("index", fiber.Map{
            "csrf": c.Locals("csrf"),
        })
    })

    app.Listen(":3000")
}

By using the Helmet and CSRF middleware, you can significantly improve the security of your Fiber applications.

📚 References for Extra Reading:

Challenge

Challenge

Your task is to build a secure Fiber web application by implementing multiple layers of middleware for security. You will protect a group of administrative routes using Basic Authentication while also applying global security enhancements.

Requirements:

  1. Create a new Fiber application instance.
  2. Apply the Helmet middleware to the entire application using its default configuration to add general security headers.
  3. Apply the CSRF middleware globally, also with its default configuration, to protect against Cross-Site Request Forgery attacks.
  4. Define an /admin route group.
  5. Protect the entire /admin group using Fiber's BasicAuth middleware.
  6. Configure the BasicAuth middleware to only accept the username admin and the password s3cr3t!. All other credentials must be rejected.
  7. Inside the protected /admin group, create a GET route at /dashboard that sends the string "Admin Dashboard Access Granted" as a response.
  8. Create one public GET route at the root path / that responds with the string "Public Home Page".

Expected result

Your final code should be a complete, runnable Fiber application that correctly configures and applies the specified middleware. The solution must include:

  • A call to fiber.New() to initialize the app.
  • The helmet and csrf middleware applied globally using app.Use().
  • An /admin route group created using app.Group("/admin").
  • The basicauth middleware applied specifically to the admin group.
  • A basicauth.Config struct that defines the users who are allowed access. The configuration must validate that the username is admin and the password is s3cr3t!.
  • A GET handler for the /admin/dashboard route defined within the admin group.
  • A GET handler for the / route defined on the main app instance.
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.