you need to send correct values to your endpoints. I just ran my example with “web” flow, and all worked just fine
- call to /autorize → you get the code
- call to /token with the code from #1 and authorization from client id/secret → you get your token
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"regexp"
"strings"
)
const baseUrl = "https://dev-xxxxx.oktapreview.com"
const client_secret = "<app client secret>"
const client_id = "<app client id>"
const redirect_uri = "http://localhost:8080/cb.html"
const scope = "openid"
const username = "<your username>"
const password = "<your password>"
func main() {
fmt.Println("starting")
vals := map[string]string{"username": username, "password": password}
json_data, err := json.Marshal(vals)
if err != nil {
fmt.Println("error encoding json")
return
}
resp, err := http.Post(fmt.Sprintf("%s/api/v1/authn", baseUrl), "application/json", bytes.NewBuffer(json_data))
if err != nil {
fmt.Println("error postin")
return
}
if resp.StatusCode != 200 {
fmt.Println("not 200")
return
}
var body map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&body)
if err != nil {
fmt.Println("error parsing response body")
return
}
var sessionToken string = body["sessionToken"].(string)
fmt.Println("stateToken: " + sessionToken)
authUrl :=
fmt.Sprintf("%s/oauth2/default/v1/authorize?client_id=%s&redirect_uri=%s&sessionToken=%s&scope=%s",
baseUrl, client_id, redirect_uri, sessionToken, scope)
const_part := "&prompt=none&response_type=code&response_mode&nonce=123&state=123"
client := &http.Client {
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
req, err := http.NewRequest("GET", authUrl + const_part, nil)
resp, err = client.Do(req)
if err != nil {
fmt.Println("error sending GET")
fmt.Println(err)
}
if resp.StatusCode != 302 {
fmt.Println("response is not 302")
return
}
fmt.Println("response is ", resp.Header["Location"][0])
r := regexp.MustCompile(`code=(?P<code>[^&]+)`)
m := r.FindStringSubmatch(resp.Header["Location"][0])
code := m[1]
fmt.Println("code:", code)
urlToken := fmt.Sprintf("%v/oauth2/default/v1/token", baseUrl)
formData := url.Values{
"code":{code},
"grant_type":{"authorization_code"},
"redirect_uri": {redirect_uri},
}
client = &http.Client{}
req, err = http.NewRequest("POST", urlToken, strings.NewReader(formData.Encode()))
if err != nil {
fmt.Println("error prepping req to /token")
fmt.Println(err)
}
req.SetBasicAuth(client_id, client_secret)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err = client.Do(req)
if err != nil {
fmt.Println("error posting data to /token")
fmt.Println(err)
}
err = json.NewDecoder(resp.Body).Decode(&body)
if err != nil {
fmt.Println("error decoding body from /token")
fmt.Println(err)
}
fmt.Println("access_token:", body["access_token"])
}