-
Notifications
You must be signed in to change notification settings - Fork 571
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Document csrf protection #136
Comments
I just added #159 to start addressing this issue. I've also added some code to my project to replace SetState with a version that returns random strings. Not sure whether that sort of thing should go into gothic itself, but at the very least it would be good to have it in the example. If you'd like a PR for either approach @markbates, let me know. |
Following up on my previous comment, I ran into a slight issue updating Since changing the The general idea is to generate the state token before Here's an example: import "crypto/rand"
const gothStateKey = "goth.state"
gothic.SetState = func(r *http.Request) string {
if state, ok := r.Context().Value(gothStateKey).(string); ok {
return state
}
panic("State not found on request context")
}
func getRandomString(n int) (string, error) {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(b), nil
}
func providerAuth(w http.ResponseWriter, r *http.Request) {
// Check for existing session...
state, err := getRandomString(stateTokenLength)
if err != nil {
http.Error(w, http.StatusText(code), code)
return
}
ctx := context.WithValue(r.Context(), gothStateKey, state)
gothic.BeginAuthHandler(w, r.WithContext(ctx))
} Combining this code with the check I added in #159 should do everything a gothic user would need to generate and verify state tokens to prevent CSRF attacks. Setting the As for integrating this logic into gothic, there are a couple potential issues I can see. First, we may not want to do the work of generating state tokens in gothic if Second, I don't think r.context is really supposed to be used this way. There are other approaches to tracking the request/state mapping, but they all seem worse. Maybe from inside gothic a closure could be used somehow to avoid the issue. As an alternative to all this, |
Closing this due to age, feel free to re-open if it's still an issue. Also, I'm comfortable with the CSRF protection as of #159. |
Is the intention that users who want csrf protection should overwrite
gothic.SetState
to set a random state, add the state to the session, and verify in the callback handler? If that's right, it would be useful to document. Also, would you be interested in implementing csrf in gothic by default?The text was updated successfully, but these errors were encountered: