feat(security): #286 use csrf token for delete request
This commit was merged in pull request #304.
This commit is contained in:
@@ -86,16 +86,7 @@ func (handler AuthImpl) handleSignIn() http.HandlerFunc {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cookie := http.Cookie{
|
||||
Name: "id",
|
||||
Value: session.Id,
|
||||
MaxAge: 60 * 60 * 8, // 8 hours
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Path: "/",
|
||||
}
|
||||
|
||||
cookie := middleware.CreateSessionCookie(session.Id)
|
||||
http.SetCookie(w, &cookie)
|
||||
|
||||
return session.User, nil
|
||||
|
||||
@@ -30,6 +30,7 @@ func (rr *csrfResponseWriter) Write(data []byte) (int, error) {
|
||||
if err == nil {
|
||||
csrfField := fmt.Sprintf(`<input type="hidden" name="csrf-token" value="%s">`, csrfToken)
|
||||
dataStr = strings.ReplaceAll(dataStr, "</form>", csrfField+"</form>")
|
||||
dataStr = strings.ReplaceAll(dataStr, "CSRF_TOKEN", csrfToken)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,30 +53,21 @@ func CrossSiteRequestForgery(auth service.Auth) func(http.Handler) http.Handler
|
||||
r.Method == http.MethodPatch {
|
||||
|
||||
csrfToken := r.FormValue("csrf-token")
|
||||
if csrfToken == "" {
|
||||
csrfToken = r.Header.Get("csrf-token")
|
||||
}
|
||||
if csrfToken == "" || !auth.IsCsrfTokenValid(csrfToken, session.Id) {
|
||||
http.Error(w, "", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if session == nil {
|
||||
var err error
|
||||
session, err = auth.SignInAnonymous()
|
||||
if err != nil {
|
||||
http.Error(w, "", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if session == nil && (strings.Contains(r.RequestURI, "/auth/signup") || strings.Contains(r.RequestURI, "/auth/signin")) {
|
||||
session, _ = auth.SignInAnonymous()
|
||||
|
||||
cookie := CreateSessionCookie(session.Id)
|
||||
http.SetCookie(w, &cookie)
|
||||
}
|
||||
cookie := http.Cookie{
|
||||
Name: "id",
|
||||
Value: session.Id,
|
||||
MaxAge: 60 * 60 * 8, // 8 hours
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Path: "/",
|
||||
}
|
||||
http.SetCookie(w, &cookie)
|
||||
|
||||
responseWriter := newCsrfResponseWriter(w, auth, session)
|
||||
next.ServeHTTP(responseWriter, r)
|
||||
|
||||
15
handler/middleware/default.go
Normal file
15
handler/middleware/default.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
func CreateSessionCookie(sessionId string) http.Cookie {
|
||||
return http.Cookie{
|
||||
Name: "id",
|
||||
Value: sessionId,
|
||||
MaxAge: 60 * 60 * 8, // 8 hours
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Path: "/",
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user