Skip to content

Instantly share code, notes, and snippets.

@alexellis
Last active August 3, 2019 20:30
Show Gist options
  • Save alexellis/2a2b41951be99593967dbf86391392fc to your computer and use it in GitHub Desktop.
Save alexellis/2a2b41951be99593967dbf86391392fc to your computer and use it in GitHub Desktop.
GitLab OAuth tester

Running the example:

base_url=https://gitlab.your-host client_secret=$client_secret client
_id=$client_id port=8081 go run main.go
2018/10/10 12:57:57 Using port: 8081

Now navigate to http://localhost:8081/start/ to begin the flow.

2018/10/10 12:57:58 URL: /oauth2/authorized?custom_param=1&code=xyz&state=state
2018/10/10 12:57:58 map[custom_param:[1] code:[xyz] state:[state]]
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"strconv"
"time"
)
func main() {
router := http.NewServeMux()
router.HandleFunc("/start/", MakeStartHandler())
router.HandleFunc("/oauth2/", MakeOAuth2Handler())
router.HandleFunc("/home/", MakeHomepageHandler())
timeout := time.Second * 10
port := 8080
if v, exists := os.LookupEnv("port"); exists {
val, _ := strconv.Atoi(v)
port = val
}
log.Printf("Using port: %d\n", port)
s := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: router,
ReadTimeout: timeout,
WriteTimeout: timeout,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())
}
func MakeStartHandler() func(http.ResponseWriter, *http.Request) {
// http://localhost:8081/start
return func(w http.ResponseWriter, r *http.Request) {
redirectRaw := "http://localhost:8081/oauth2/authorized"
redirectURI, _ := url.Parse(redirectRaw)
rQuery := redirectURI.Query()
rQuery.Set("custom_param", "1")
redirectURI.RawQuery = rQuery.Encode()
redirect, _ := url.Parse(os.Getenv("base_url") + "/oauth/authorize")
q := redirect.Query()
q.Set("client_id", os.Getenv("client_id"))
q.Set("response_type", "code")
q.Set("state", "state")
q.Set("redirect_uri", redirectURI.String())
redirect.RawQuery = q.Encode()
w.Write([]byte(`<html><head></head>Redirecting.. <a href="redirect">to login</a>. <script>window.location.replace("` + redirect.String() + `");</script></html>`))
}
}
func MakeHomepageHandler() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
}
}
func MakeOAuth2Handler() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
log.Printf("URL: %s", r.URL)
if r.URL.Path != "/oauth2/authorized" {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized OAuth callback."))
return
}
if r.Body != nil {
defer r.Body.Close()
}
log.Println(r.URL.Query())
w.Write([]byte(fmt.Sprintf("OK, got a code: %s", r.URL.Query().Get("code"))))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment