How to authenticate for hundreds and thousands of API endpoints?

I am currently building a web application in golang (with Gorilla) and have implemented several API endpoints. However, I noticed that every time I implement a function like

func CreateUserHandler(w http.ResponseWriter, r *http.Request) {}

I need to add the function below to the body of the handler functions to check if the request is allowed:

func checkAuthorizedUser (r * http.Request) error {
    uid, err := CheckRequestUser (r.Cookie("uid"))
    if err != nil {
        return errors.New("Can't find cookie value for uid")
    }
    if !IsValidUser (uid.Value) { 
        return errors.New("Not a valid user")
    }
    return nil
}

What is happening to me right now is that I have to add a checkAuthorizedUser()handler function to each function, and so far I already have many handler functions. I wonder if there is a better way to check if a client is allowed access to a specific endpoint, besides explicitly authenticating each handler function.

+4
1

Gorilla , . . - :

func checkPermissions(h http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        authCheck := true //implement the actual checking

        if authCheck {
            w.WriteError(w, 400, "error")
            return
        }

        h.ServeHttp(w, r)
    }
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    r.HandleFunc("/products", ProductsHandler)
    r.HandleFunc("/articles", ArticlesHandler)
    http.Handle("/", checkPermissions(r))
}

:

https://godoc.org/github.com/gorilla/mux#NewRouter

https://github.com/gorilla/mux

+5

Source: https://habr.com/ru/post/1677295/


All Articles