Cookie Authentication in Go

2916 VIEWS

· · ·

HTTP is stateless and might need to store data on your client to simulate a form of state. Browsers and other client-based applications support using cookies to store data on the client for server-defined purposes. This article will teach you how to implement cookies for storing data on the client in your Go web applications.

What Are Cookies

Cookies (web cookies) are data that is stored on the user’s client application for various purposes.

Cookies are popular for implementing and storing sessions (authenticating if users are logged in or logged out) and storing temporary, insensitive data on the application’s client side.

Client cookies are usually key-value pairs of names and user-related data.

Getting Started With HTTP Cookies in Go

To fully understand this tutorial, you’ll need to know about building web applications in Go. Check out this article on Sweetcode to learn how to build a simple web API in Go without dependencies.

Most of the functionalities you’ll need to implement cookies in Go are provided in the http package, and you won’t have to install any external dependencies or packages.

Import these packages in your Go file for this tutorial.

import (
  "fmt"
  "log"
  "net/http"
)

You’ll use the fmt package to write to the client and the log package for fatal error handling.

The Cookie struct type in the http package  is the model for cookies in Go. The fields represent the values, names, and types you can store in a cookie with the http package.

type Cookie struct {
  Name  string
  Value string

  Path       string    // optional
  Domain     string    // optional
  Expires    time.Time // optional
  RawExpires string    // for reading cookies only

  // MaxAge=0 means no 'Max-Age' attribute specified.
  // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
  // MaxAge>0 means Max-Age attribute present and given in seconds
  MaxAge   int
  Secure   bool
  HttpOnly bool
  SameSite SameSite
  Raw      string
  Unparsed []string // Raw text of unparsed attribute-value pairs
}

You will add cookies to the request’s header with the name field that you’ll use to access the cookie from the header when you need to.

Setting Cookies on the Client Side

You’ll implement a simple sign-in handler function for your application’s client.

Here’s how you can set a cookie on the client side of your application.

func signIn(writer http.ResponseWriter, request *http.Request) {
  // your business logic here
  http.SetCookie(writer, &http.Cookie{
    Name:  "signed in cookie",
    Value: "True",
  })

}

The SetCookie function of the http package provides the functionality you need to set a cookie on the client. The SetCookie method takes in the response writer instance and the reference to the instantiated cookie struct.

In the signIn handler function, the cookie instance has instantiated the Name and Value fields. You can instantiate as many fields as you want to store data on the client.

However, an important part of knowing how to implement cookies is also knowing how to revoke them.

Revoking Cookies on the Client (Signing Out)

There are many ways you can revoke cookies on the client side. First, you’ll have to retrieve the cookie from the client’s request header successfully before making changes to the cookie based on your operation.

Here’s an example of how you can revoke a client’s cookie after retrieving the cookie from the request’s header.

func signOut(writer http.ResponseWriter, request *http.Request) {
  cookies, err := request.Cookie("signed in cookie")
  if err != nil {
    http.Redirect(writer, request, "/set", http.StatusSeeOther)
    fmt.Fprintf(writer, "There's an error in your request, Cookies not found")
  }
  cookies.MaxAge = -1
  http.SetCookie(writer, cookies)

}

You can retrieve the cookie with the Cookie method of your HTTP request instance. The cookies variable holds the cookie from the request header, and the err variable is for possible error handling.

In this case, the MaxAge field of the cookie instance was replaced with the -1 value, and in cases of authentication, you can check the status of the cookie age to authenticate the user.

Conclusion

In this tutorial, you learned about cookie authentication in Go. Specifically, you learned how cookies work in Go, and how to implement cookies in your Go web apps without any external dependencies.

Since intruders can hijack cookies, it is important not to save any sensitive information in cookies.


Ukeje Goodness Chukwuemeriwo is a Software developer and DevOps Enthusiast writing Go code day-in day-out.


Discussion

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu
Skip to toolbar