Test Golang HTTPS Server CSRF Using Gorilla CSRF - Golang Web Development

Опубликовано: 12 Март 2025
на канале: Maharlikans Code
268
5

In this Golang Web Development Series #11, we're testing the Gorilla CSRF with a secure connection from our production web server which is the Ubuntu 20.04 LTS with Nginx Let's Encrypt (Certbot) compliance server with step by step guide here in Golang's Web Development Series.

Test the Maharlikans Code Site:
https://maharlikanscode.com/

Get Linode Account:
https://www.linode.com/?r=6aae17162e9...

Maharlikans Code Github:
https://github.com/maharlikanscode/go...

#MaharlikansCode
#GolangWebDevelopment11
#GolangHTTPSServerCSRF
#SecureGorillaCSRF
#GolangTutorial
#LearnGolangWebDevelopment
#Golang
#LifeAsSoftwareDeveloper
#Maharlikans
#FilipinoSoftwareDeveloper

If you go with extra mile for buying me a cup of coffee, I appreciate it guys: https://ko-fi.com/maharlikanscode

Source Codes:
api/auth.go:
package api

import (
"encoding/json"
"fmt"
"gowebapp/config"
"io/ioutil"
"net/http"
"strconv"
"strings"

"github.com/gorilla/mux"
"github.com/itrepablik/itrlog"
"github.com/itrepablik/tago"
)

// AuthRouters are the collection of all URLs for the Auth App.
func AuthRouters(r *mux.Router) {
r.HandleFunc("/api/v1/user/login", LoginUserEndpoint).Methods("POST")
}

// LoginUserEndpoint is to validate the user's login credential
func LoginUserEndpoint(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
w.WriteHeader(http.StatusOK)

body, errBody := ioutil.ReadAll(r.Body)
if errBody != nil {
itrlog.Error(errBody)
panic(errBody.Error())
}

keyVal := make(map[string]string)
json.Unmarshal(body, &keyVal)

userName := strings.TrimSpace(keyVal["username"])
password := keyVal["password"]
isSiteKeepMe, _ := strconv.ParseBool(keyVal["isSiteKeepMe"])

fmt.Print("userName: ", userName)
fmt.Print("password: ", password)
fmt.Print("isSiteKeepMe: ", isSiteKeepMe)

// Check if username is empty
if len(strings.TrimSpace(userName)) == 0 {
w.Write([]byte(`{ "isSuccess": "false", "alertTitle": "Username is Required BK", "alertMsg": "Please enter your username.", "alertType": "error" }`))
return
}

// Check if password is empty
if len(strings.TrimSpace(password)) == 0 {
w.Write([]byte(`{ "isSuccess": "false", "alertTitle": "Password is Required BK", "alertMsg": "Please enter your password.", "alertType": "error" }`))
return
}

// Set the cookie expiry in days.
expDays := "1" // default to expire in 1 day.
if isSiteKeepMe == true {
expDays = config.UserCookieExp
}

// Encrypt the username value to store it from the user's cookie.
encryptedUserName, err := tago.Encrypt(userName, config.MyEncryptDecryptSK)
if err != nil {
itrlog.Error(err)
}

w.Write([]byte(`{ "isSuccess": "true", "alertTitle": "Login Successful", "alertMsg": "Your account has been verified and it's successfully logged-in.",
"alertType": "success", "redirectTo": "` + config.SiteBaseURL + `dashboard", "eUsr": "` + encryptedUserName + `", "expDays": "` + expDays + `" }`))
}
ajax post/index.html:
function loginForm()
{
//Get the form instance
username = $("#username").val();
password = $("#password").val();
isSiteKeepMe = $('#isSiteKeepMe').is(':checked');

var obj = { username: username, password: password, isSiteKeepMe: new String(isSiteKeepMe) };
var data = JSON.stringify(obj);

$.ajax({
method: "POST",
headers: {
'X-CSRF-TOKEN':csrfToken,
'Content-Type':'application/json'
},
url: BASE_URL+'api/v1/user/login',
data: data,
cache: false,
dataType: "json",
beforeSend: function(){
//Start displaying button's working animation
var loadingText = 'signing in...';
if ($("#btnLogin").html() !== loadingText) {
$("#btnLogin").data('original-text', $("#btnLogin").html());
$("#btnLogin").html(loadingText);
}
},
success: function(response)
{
$("#btnLogin").html($("#btnLogin").data('original-text')); //stop animation and switch back to original text
if (response.isSuccess === "false") {
Swal.fire(response.alertTitle, response.alertMsg, response.alertType);
}else{
Swal.fire(response.alertTitle, response.alertMsg, response.alertType);
}
}
});
}