diff --git a/cmd/example-app/main.go b/cmd/example-app/main.go index ffa21c29..3ec34e38 100644 --- a/cmd/example-app/main.go +++ b/cmd/example-app/main.go @@ -241,7 +241,7 @@ func (a *app) handleLogin(w http.ResponseWriter, r *http.Request) { authCodeURL := "" scopes = append(scopes, "openid", "profile", "email") - if r.FormValue("offline_acecss") != "yes" { + if r.FormValue("offline_access") != "yes" { authCodeURL = a.oauth2Config(scopes).AuthCodeURL(exampleAppState) } else if a.offlineAsScope { scopes = append(scopes, "offline_access") @@ -254,34 +254,42 @@ func (a *app) handleLogin(w http.ResponseWriter, r *http.Request) { } func (a *app) handleCallback(w http.ResponseWriter, r *http.Request) { - if errMsg := r.FormValue("error"); errMsg != "" { - http.Error(w, errMsg+": "+r.FormValue("error_description"), http.StatusBadRequest) - return - } - - if state := r.FormValue("state"); state != exampleAppState { - http.Error(w, fmt.Sprintf("expected state %q got %q", exampleAppState, state), http.StatusBadRequest) - return - } - - code := r.FormValue("code") - refresh := r.FormValue("refresh_token") var ( err error token *oauth2.Token ) oauth2Config := a.oauth2Config(nil) - switch { - case code != "": + switch r.Method { + case "GET": + // Authorization redirect callback from OAuth2 auth flow. + if errMsg := r.FormValue("error"); errMsg != "" { + http.Error(w, errMsg+": "+r.FormValue("error_description"), http.StatusBadRequest) + return + } + code := r.FormValue("code") + if code == "" { + http.Error(w, fmt.Sprintf("no code in request: %q", r.Form), http.StatusBadRequest) + return + } + if state := r.FormValue("state"); state != exampleAppState { + http.Error(w, fmt.Sprintf("expected state %q got %q", exampleAppState, state), http.StatusBadRequest) + return + } token, err = oauth2Config.Exchange(a.ctx, code) - case refresh != "": + case "POST": + // Form request from frontend to refresh a token. + refresh := r.FormValue("refresh_token") + if refresh == "" { + http.Error(w, fmt.Sprintf("no refresh_token in request: %q", r.Form), http.StatusBadRequest) + return + } t := &oauth2.Token{ RefreshToken: refresh, Expiry: time.Now().Add(-time.Hour), } token, err = oauth2Config.TokenSource(r.Context(), t).Token() default: - http.Error(w, fmt.Sprintf("no code in request: %q", r.Form), http.StatusBadRequest) + http.Error(w, fmt.Sprintf("method not implemented: %s", r.Method), http.StatusBadRequest) return } diff --git a/cmd/example-app/templates.go b/cmd/example-app/templates.go index c0f9dfbd..a870d0f0 100644 --- a/cmd/example-app/templates.go +++ b/cmd/example-app/templates.go @@ -8,7 +8,7 @@ import ( var indexTmpl = template.Must(template.New("index.html").Parse(` -
+

Authenticate for:

@@ -50,8 +50,13 @@ pre {

Token:

{{ .IDToken }}

Claims:

{{ .Claims }}

+ {{ if .RefreshToken }}

Refresh Token:

{{ .RefreshToken }}

-

Redeem refresh token

+ + + +

+ {{ end }} `))