volatiletech / authboss

The boss of http auth.
MIT License
3.85k stars 207 forks source link

Get X-CSRF-TOKEN first time in a single page application #250

Closed frederikhors closed 5 years ago

frederikhors commented 5 years ago

Can you explain it to me why are you using this technique in authboss-sample (https://github.com/volatiletech/authboss-sample/blob/master/blog.go)?

if *flagAPI {
    // In order to have a "proper" API with csrf protection we allow
    // the options request to return the csrf token that's required to complete the request
    // when using post
    optionsHandler := func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("X-CSRF-TOKEN", nosurf.Token(r))
        w.WriteHeader(http.StatusOK)
    }

    // We have to add each of the authboss get/post routes specifically because
    // chi sees the 'Mount' above as overriding the '/*' pattern.
    routes := []string{"login", "logout", "recover", "recover/end", "register"}
    mux.MethodFunc("OPTIONS", "/*", optionsHandler)
    for _, r := range routes {
        mux.MethodFunc("OPTIONS", "/auth/"+r, optionsHandler)
    }
}

My scenario is a SPA (Single page application) which need to:

But to make this login call I also need a X-CSRF-Token header in my javascript call.

How can I get the token from authboss on the first visit?

In the next visits I can create a middleware which creates every time a cookie to be read by javascript (so, NO HTTP-ONLY).

aarondl commented 5 years ago

Let's keep this conversation in the first issue you opened.