Skip to main content

Secure authentication using Go

Published 12 min readMarkdown
Secure authentication using Go

Full code source: secure-login-go

Let's take a look at how authentication works on many modern websites by implementing it ourselves step by step. We're going to take a look at how sessions, cookies, CSRF tokens and of course username and passwords all work together to produce secure authentication for a website.

We're going to make 4 different endpoints:

  • one to CREATE an account

  • one to LOG IN

  • one to LOG OUT

  • and a PROTECTED endpoint which will be only accessible to logged in users

We'll store the user name as a key in a map which maps usernames to log information so this is our in-memory database which we'll use as a stand-in for a real database.

For now the functions which are going to handle these endpoint requests are going to be empty.

// main.go

var users = map[string]Login{}

func main() {
    http.HandleFunc("/register", register)
    http.HandleFunc("/login", login)
    http.HandleFunc("/logout", logout)
    http.HandleFunc("/protected", protected)
    http.ListenAndServe(":8080", nil)
}

func register(w http.ResponseWriter, r *http.Request) {}
func login(w http.ResponseWriter, r *http.Request) {}
func logout(w http.ResponseWriter, r *http.Request) {}
func protected(w http.ResponseWriter, r *http.Request) {}

Registration

The registration function will handle a POST request. POST methods are generally used for requests which send data and create new resources, which is exactly what we're going to do here.

We're going to grab the username and password from the payload form value we'll do some basic length checks as well as check if the user already exists.

// main.go

func register(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        er := http.StatusMethodNotAllowed
        http.Error(w, "Invalid method", er)
    }

    username := r.FormValue("username")
    password := r.FormValue("password")

    if len(username) == 0 || len(password) == 0 {
        er := http.StatusNotAcceptable
        http.Error(w, "Invalid username or password", er)
        return
    }

}

It's common practice to send passwords in plain text since most public APIs use HTTPS. This encrypts the data during transmission. However passwords are always stored in an ofuscated form. This ensures that even if somebody gains access to the database they won't have direct access to the user's passwords.

Hashing

To obfuscate a password we use a hashing function. A hashing function is an algorithm that converts data into a fixed size irreversible string of characters used primarily for data integrity and secure storage like password protection.

The hashing function we'll use is a very commonly used one which is called bcrypt. In a new utils.go file we will import bcrypt from the golang crypto module. The hash password function will take in the password as a string and we'll call bcript.GenerateFromPassword. This takes a bite representation of the password and a cost factor.

// utils.go

package main

import (
    "golang.org/x/crypto/bcrypt"
)

func hashPassword(password string) (string, error) {
    bytes, err := bcrypt.GenerateFromPassword([]byte(password), 10)
    return string(bytes), err
}

The cost factor essentially just controls how slow the algorithm is. A cost factor of 10 means the password is hashed 2 to the power of 10 times. So we hash the password and then hash the hash many many times.

The point of this is to make it slow to generate a hash. This way, if somebody got a hold of the hash passwords they couldn't just quickly run millions of guesses through the hashing function until they found a match.

All right so then the hash is what we store in the database:

// main.go

func register(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        er := http.StatusMethodNotAllowed
        http.Error(w, "Invalid method", er)
    }

    username := r.FormValue("username")
    password := r.FormValue("password")

    if len(username) == 0 || len(password) == 0 {
        er := http.StatusNotAcceptable
        http.Error(w, "Invalid username or password", er)
        return
    }

    if _, ok := users[username]; ok {
        er := http.StatusConflict
        http.Error(w, "User already exists", er)
        return
    }

    hashedPassword, _ := hashPassword(password)
    users[username] = Login{
        HashedPassword: hashedPassword,
    }

    fmt.Fprintln(w, "User registered successfully")

}

Let's try this endpoint out and create a user. So our database now looks like this:

{
    "username": {
        "HashedPassword": "$2a$10$JhuoEe8X...",
        "SessionToken": "",
        "CSRFToken": ""        
    }
}

Logging in

Let's see how we would log in a user. This is where we start to use our session and CSRF tokens. We're going to use a POST method again and grab our password and username in the same way as before. If the username doesn't exist just return an error.

// main.go

func login(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        er := http.StatusMethodNotAllowed
        http.Error(w, "Invalid method", er)
    }

    username := r.FormValue("username")
    password := r.FormValue("password")

    user, ok := users[username]
    if !ok || {
        er := http.StatusUnauthorized
        http.Error(w, "Invalid username or pasword", er)
        return
    }

}

To check the password we got to hash it and compare it to the hash that we have in our database. So let's go back to our util file and create a check password hash function.

// utils.go

func checkPasswordHash(password, hash string) bool {
    err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
    return err == nil
}

The bcrypt package we imported has a CompareHashAndPassword function. This will hash the plain text password and compare it to the hash we have stored, all in one line. If there's an error this means that the passwords didn't match.

Let's now add this check to our if statement.

// main.go

func login(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        er := http.StatusMethodNotAllowed
        http.Error(w, "Invalid method", er)
    }

    username := r.FormValue("username")
    password := r.FormValue("password")

    user, ok := users[username]
    if !ok || !checkPasswordHash(password, user.HashedPassword) {
        er := http.StatusUnauthorized
        http.Error(w, "Invalid username or pasword", er)
        return
    }

    fmt.Fprintln(w, "Login successful!")
}

If we stopped here we'd face a major issue. Each time a request is made to the backend, like fetching or updating user data, the client would need to send the username and password for authentication. This would either require the user repeatedly enter their credentials for the website. Or the web page to store them. Both of which are let's say bad.

This is where session tokens come in. A session token is generated randomly, in a function like this:

// utils.go

func generateToken(length int) string {
    bytes := make([]byte, length)
    if _, err := rand.Read(bytes); err != nil {
        log.Fatalf("Failed to generate token: %v", err)
    }

    return base64.URLEncoding.EncodeToString(bytes)
}

Here we're using the Rand package to generate a random bite and then returning it as a string in base64 representation.

On a side note, base64 is a binary-to-text encoding schema that converts binary data into a string, where the string contains only characters from a specially chosen list of characters. These characters are uppercase letters, lowercase letters, digits as well as the + and / symbol. This avoids us using reserved characters like & or @ for example in our token, which have special uses in HTTP requests.

Session tokens

All right so we'll generate a session token in our login handler.

sessionToken := generateToken(32)

But what are we going to use it for? Well first we'll store the session token in a cookie which we'll send back to the client.

sessionToken := generateToken(32)

//Set session cookie
http.SetCookie(w, &http.Cookie{
    Name:  "session_token",
    Value: sessionToken,
})

Now the way cookies work is they are automatically sent by the browser to the back end every time a request is made to any endpoint in our database. So this session token will be sent anytime a request is made. Now instead of checking login credentials every time, we can just verify that the session token we get in the cookie is the same with the one that we have in our database.

sessionToken := generateToken(32)

//Set session cookie
http.SetCookie(w, &http.Cookie{
    Name:  "session_token",
    Value: sessionToken,
})

Cool! So let's store the session token in our database. Now there are a couple extra things we want to add to our cookie. First is the expiration date. We'll set this to 24 hours. What happens here is the browser will delete the value under that session token key in the cookie after 24 hours. So any subsequent request after 24 hours will have no session token and hence the user gets automatically logged out.

sessionToken := generateToken(32)

//Set session cookie
http.SetCookie(w, &http.Cookie{
    Name:  "session_token",
    Value: sessionToken,
    Expires: time.Now().Add(24 * time.Hour),
    HttpOnly: true,
})

//Store tokens in the database
user.SessionToken = sessionToken
users[username] = user

This next key-value pairs and cookies also have a flag called HttpOnly. This HttpOnly flag ensures that the session token can't be accessed by front-end JavaScript on the web page so it's only available to be sent during HTTP requests. So all good, right? Well.. not exactly.

Using session tokens we've actually introduced a vulnerability called cross-site request forgery. Here's how this would work.

Imagine I'm logged into my bank.com account hence a cookie is stored on my machine with a session token. Suppose I get a link to a malicious website and click on it since I'm logged into my bank.com account. Any requests the malicious site makes, the bank.com will have the cookie data for that site automatically sent along with the request so the banking website will get the valid session token and treat any requests from the malicious site as legit. For example transferring all funds out from an account.

CSRF tokens

This is an issue we can solve with CSRF tokens. We can create one in the same way we create a session token. Here similarly we'll put the CSRF token in the cookie except we'll set HttpOnly to false as well. Let's store this token in the database for the user.

// main.go

func login(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        er := http.StatusMethodNotAllowed
        http.Error(w, "Invalid method", er)
    }

    username := r.FormValue("username")
    password := r.FormValue("password")

    user, ok := users[username]
    if !ok || !CheckPasswordHash(password, user.HashedPassword) {
        er := http.StatusUnauthorized
        http.Error(w, "Invalid username or pasword", er)
        return
    }

    sessionToken := generateToken(32)
    csrfToken := generateToken(32)

    //Set session cookie
    http.SetCookie(w, &http.Cookie{
        Name:     "session_token",
        Value:    sessionToken,
        Expires:  time.Now().Add(24 * time.Hour),
        HttpOnly: true,
    })

    // Set CSRF cookie
    http.SetCookie(w, &http.Cookie{
        Name:     "csrf_token",
        Value:    csrfToken,
        Expires:  time.Now().Add(24 * time.Hour),
        HttpOnly: false,
    })

    //Store tokens in the database
    user.SessionToken = sessionToken
    user.CSFRToken = csrfToken
    users[username] = user

    fmt.Fprintln(w, "Login successful!")
}

Okay, so now how do we actually use this CSRF token? Well, first we need to understand what Same-Origin Policy is. This essentially means that the browser blocks web pages from accessing resources meant for other websites, like cookies for example. So the malicious website can't read the cookie information from bank.com even though the cookie is automatically sent for any requests to bank.com.

Authorization function

So let's see how we can use this information in code. We'll create a session file and start writing our authorized function which will authorize requests. So first we'll grab the username and use that to grab the user data from our database.

So let's see how we can use this information in code. We'll create a session.go file and start writing our authorized function which will authorize requests.

// session.go

package main

import (
    "errors"
    "net/http"
)

var ErrAuth = errors.New("Unauthorized")

func Authorize(r *http.Request) (string, error) {
    var body RequestBody

    err := json.NewDecoder(r.Body).Decode(&body)
    if err != nil {
        return "", ErrAuth
    }

    userName := body.Username
    user, ok := users[userName]
    if !ok {
        fmt.Println("User does not exist!")
        return "", ErrAuth
    }

    st, err := r.Cookie("session_token")
    if err != nil || st.Value == "" || st.Value != user.SessionToken {
        fmt.Println("Invalid session token!")
        return "", ErrAuth
    }

    csrf := r.Header.Get("X-CSRF-Token")
    if csrf == "" || csrf != user.CSFRToken {
        fmt.Println("Invalid CSRF token!")
        return "", ErrAuth
    }

    return userName, nil
}

So first we'll grab the username and use that to grab the user data from our database. We can grab the session token we sent from the cookie using the request object.

We check it was passed in is not empty and that it matches what we have in our database otherwise we reject the request. Now comes the CSRF token. The difference here is that we'll grab this token from the header of the request and not the cookie.

So we expect the client to send an X-CSRF-Token field with the CSRF token we sent in the cookie before. So looking back, remember we set the HttpOnly flag to false for this? This is because we want want to allow the code to actually read the token from the cookie. This way it can add it to the header and send it back. This is important because the browser will only allow this site to read the token from the cookie.

The malicious website can't read this token so if it sends us back the CSRF token as part of the header we know the request is coming from the original site.

Now all we got to do is use this function for any protected routes. In fact, let's Implement our protected route handler.

// main.go

func protected(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        er := http.StatusMethodNotAllowed
        http.Error(w, "Invalid request method", er)
    }

    username, err := Authorize(r)
    if err != nil {
        er := http.StatusUnauthorized
        http.Error(w, "Unauthorized", er)
        return
    }

    fmt.Fprintf(w, "CSRF valudation succesful! Welcome, %s!", username)
}

Here we call the authorized function and deny the request if we get an error back. Otherwise we'll return a welcome message.

Logout

Lastly, we'll just fill out our logout handler. This is pretty easy. All we do is authorize the request again and if everything's okay we clear the tokens from the cookie. And then clear the tokens from our database.

// main.go

func logout(w http.ResponseWriter, r *http.Request) {
    username, err := Authorize(r)
    if err != nil {
        er := http.StatusUnauthorized
        http.Error(w, "Unauthorized", er)
        return
    }

    // Clear cookies
    http.SetCookie(w, &http.Cookie{
        Name:     "session_token",
        Value:    "",
        Expires:  time.Now().Add(-time.Hour),
        HttpOnly: true,
    })
    http.SetCookie(w, &http.Cookie{
        Name:     "csrf_token",
        Value:    "",
        Expires:  time.Now().Add(-time.Hour),
        HttpOnly: false,
    })

    // Clear the tokens from the database
    user := users[username]
    user.SessionToken = ""
    user.CSFRToken = ""
    users[username] = user

    fmt.Fprintln(w, "Logged out successfully!")
}

Testing

All right! Let's test out a secure API and see what happens. For this let's use the Rest Client VSCode extension. It allows sending HTTP request and view the response in VSCode directly.

First we're going to register a user:

### Registration
POST http://localhost:8080/register
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="username"

dragos
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="password"

Next let's try to hit the protected route so we see we get an unauthorized error.

### Access protected resource
POST http://localhost:8080/protected

This is because we need to log in so let's do that.

### Login
POST http://localhost:8080/login
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="username"

dragos
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="password"

password123
------WebKitFormBoundary7MA4YWxkTrZu0gW--

When we do that we get back a session token and a CSRF token.

HTTP/1.1 200 OK
Set-Cookie: session_token=XPbVN-rDbPNNIYqM_kryHMA8xhFpmQx1YXd0p0LZILM=; Expires=Mon, 04 Nov 2024 07:26:35 GMT; HttpOnly,csrf_token=tQSH0mKlze3hE_Q88DW07AL734A0Hwndm_mtEbfDm8c=; Expires=Mon, 04 Nov 2024 07:26:35 GMT
Date: Sun, 03 Nov 2024 07:26:35 GMT
Content-Length: 18
Content-Type: text/plain; charset=utf-8
Connection: close

Login successful!

If we hit the protected route again we get another failure because we didn't pass the CSRF token as part of the header so let's do that.

### Access protected resource
POST http://localhost:8080/protected
X-CSRF-Token: tQSH0mKlze3hE_Q88DW07AL734A0Hwndm_mtEbfDm8c=
Cookie: session_token=XPbVN-rDbPNNIYqM_kryHMA8xhFpmQx1YXd0p0LZILM=
Content-Type: application/json

 {
    "username": "dragos"
 }

Trying again and we got our welcome message:

HTTP/1.1 200 OK
Date: Sun, 03 Nov 2024 07:28:16 GMT
Content-Length: 43
Content-Type: text/plain; charset=utf-8
Connection: close

CSRF valudation succesful! Welcome, dragos!

We can also logout and then try the protected route once more. And we get an unauthorized error as expected.

### Logout 
POST http://localhost:8080/logout
X-CSRF-Token: tQSH0mKlze3hE_Q88DW07AL734A0Hwndm_mtEbfDm8c=
Cookie: session_token=XPbVN-rDbPNNIYqM_kryHMA8xhFpmQx1YXd0p0LZILM=
Content-Type: application/json

 {
    "username": "dragos"
 }

And that's it! That's an overview of how authentication works in many modern sites and how you can build it yourself.

About the author

  • I am a front-end developer experienced working with React and Typescript.

    So far I worked with product owners from multiple areas such as education, supply chain management, event planning, and product startups.

    Before joining the front-end world, I worked as a data analyst, using Excel and Excel VBA as my daily drivers. I also had the opportunity to work as a network administrator where I learned how to build and configure Linux servers.

No comments yet. Be the first to comment.