Skip to content

Instantly share code, notes, and snippets.

@kadel
Created August 17, 2018 16:42
Show Gist options
  • Select an option

  • Save kadel/c30b3085e2e90a93393b99a2b39f4806 to your computer and use it in GitHub Desktop.

Select an option

Save kadel/c30b3085e2e90a93393b99a2b39f4806 to your computer and use it in GitHub Desktop.
Get OAuth authorization token form OpenShift
package main
import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"golang.org/x/oauth2"
)
func main() {
ctx := context.Background()
conf := &oauth2.Config{
ClientID: "openshift-challenging-client",
// RedirectURL: "https://192.168.99.100:8443/oauth/token/implicit",
Endpoint: oauth2.Endpoint{
// URL cen be obtained from https://192.168.99.100:8443/.well-known/oauth-authorization-server
AuthURL: "https://192.168.99.100:8443/oauth/authorize",
TokenURL: "https://192.168.99.100:8443/oauth/token",
},
}
httpClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
// Skipping TLS verification this has to be handled in more starter way
// always ignoring verification can be dangerous
InsecureSkipVerify: true,
},
},
}
ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient)
// this is special client used only to request code
// CheckRedirect ensures that it is not following 302 redirects and we can parse Location header to get code from it
codeHTTPClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
// get an url where we can obtain code
authCodeUrl := conf.AuthCodeURL("state", oauth2.AccessTypeOffline)
fmt.Printf("authCodeUrl: %s\n", authCodeUrl)
authCodeReq, err := http.NewRequest("GET", authCodeUrl, nil)
authCodeReq.Header.Set("X-CSRF-Token", "1")
authCodeReq.SetBasicAuth("developer", "dev")
authCodeResp, err := codeHTTPClient.Do(authCodeReq)
if err != nil {
panic(err)
}
// we don't really need body, but in case of error there might be usefull information in it
body, err := ioutil.ReadAll(authCodeResp.Body)
if err != nil {
panic(err)
}
fmt.Printf("body: %s\n", string(body[:]))
fmt.Printf("status: %d\n", authCodeResp.StatusCode)
fmt.Printf("location: %s\n", authCodeResp.Header.Get("Location"))
// parse Location and get code from it
urlLocation, err := url.Parse(authCodeResp.Header.Get("Location"))
if err != nil {
panic(err)
}
code := urlLocation.Query().Get("code")
fmt.Printf("code: %s\n", code)
// Exchange code for token
tok, err := conf.Exchange(ctx, code)
if err != nil {
panic(err)
}
// And here we have our token
fmt.Printf("token: %s", tok.AccessToken)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment