Skip to content

Instantly share code, notes, and snippets.

@chriswhitcombe
Created August 11, 2015 07:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriswhitcombe/ffc640fb7d07c58f8e5b to your computer and use it in GitHub Desktop.
Save chriswhitcombe/ffc640fb7d07c58f8e5b to your computer and use it in GitHub Desktop.
func testImplicitAuth() {
conf := &oauth2.Config{
ClientID: "clientid",
RedirectURL: "https://server.com",
Endpoint: oauth2.Endpoint{
TokenURL: "http://test.com/auth/token",
AuthURL: "http://test.com/auth/authorize",
},
}
//fix to get the implicit auth url
authURL := strings.Replace(conf.AuthCodeURL("should_be_random"), "response_type=code", "response_type=token", -1)
fmt.Println(authURL)
var wg sync.WaitGroup
var returnURL *url.URL
wg.Add(1)
//ensure we timeout if needed
go func() {
<-time.After(time.Second * 2)
fmt.Println("Request timeout")
wg.Done()
}()
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
returnURL = req.URL
wg.Done()
return errors.New("Dont follow redirects")
},
}
form := url.Values{}
form.Set("login", "username")
form.Set("password", "password")
client.PostForm(authURL, form)
wg.Wait()
fmt.Println(returnURL.String())
splits := strings.Split(returnURL.String(), "#")
vals, _ := url.ParseQuery(splits[1])
fmt.Println(vals.Get("access_token"))
//chuck all that info into a token object and create a connection
expires, _ := strconv.Atoi(vals.Get("expires_in"))
tkn := &oauth2.Token{
AccessToken: vals.Get("access_token"),
TokenType: vals.Get("token_type"),
RefreshToken: vals.Get("refresh_token"),
Expiry: time.Now().Add(time.Duration(expires) * time.Second),
}
myClient := conf.Client(oauth2.NoContext, tkn)
response, _ := myClient.Get("http://server.com/protected")
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
fmt.Printf("%s\n", string(contents))
}
@aeneasr
Copy link

aeneasr commented Mar 21, 2016

Instead of returnURL = req.URL why not do this fragment = req.URL.Fragment. Saves you the string splitting part

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment