oauth2_proxy/providers/provider_default.go

71 lines
1.7 KiB
Go
Raw Normal View History

2015-05-21 03:23:48 +00:00
package providers
import (
"bytes"
"encoding/json"
"errors"
2015-06-06 18:15:43 +00:00
"fmt"
2015-05-21 03:23:48 +00:00
"io/ioutil"
"net/http"
"net/url"
2015-06-06 18:15:43 +00:00
"strings"
2015-05-21 03:23:48 +00:00
)
func (p *ProviderData) Redeem(redirectUrl, code string) (body []byte, token string, err error) {
if code == "" {
err = errors.New("missing code")
return
}
params := url.Values{}
params.Add("redirect_uri", redirectUrl)
params.Add("client_id", p.ClientID)
params.Add("client_secret", p.ClientSecret)
params.Add("code", code)
params.Add("grant_type", "authorization_code")
req, err := http.NewRequest("POST", p.RedeemUrl.String(), bytes.NewBufferString(params.Encode()))
if err != nil {
return nil, "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, "", err
}
body, err = ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, "", err
}
2015-06-06 18:15:43 +00:00
if resp.StatusCode != 200 {
return body, "", fmt.Errorf("got %d from %q %s", resp.StatusCode, p.RedeemUrl.String(), body)
}
2015-05-21 03:23:48 +00:00
// blindly try json and x-www-form-urlencoded
var jsonResponse struct {
AccessToken string `json:"access_token"`
}
err = json.Unmarshal(body, &jsonResponse)
if err == nil {
return body, jsonResponse.AccessToken, nil
}
v, err := url.ParseQuery(string(body))
return body, v.Get("access_token"), err
}
2015-06-06 18:15:43 +00:00
func (p *ProviderData) GetLoginURL(redirectURI, finalRedirect string) string {
params := url.Values{}
params.Add("redirect_uri", redirectURI)
params.Add("approval_prompt", "force")
params.Add("scope", p.Scope)
params.Add("client_id", p.ClientID)
params.Add("response_type", "code")
if strings.HasPrefix(finalRedirect, "/") {
params.Add("state", finalRedirect)
}
return fmt.Sprintf("%s?%s", p.LoginUrl, params.Encode())
}