Created
April 1, 2019 15:53
-
-
Save chrisvdg/b8392f5886448a79630246fc83ca75e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"crypto/tls" | |
"fmt" | |
"log" | |
"net/http" | |
"golang.org/x/oauth2" | |
) | |
const ( | |
clientID = "hello" # iyo org | |
clientSecret = "world" # org api key | |
) | |
func main() { | |
config := oauth2.Config{ | |
ClientID: clientID, | |
ClientSecret: clientSecret, | |
Endpoint: oauth2.Endpoint{ | |
AuthURL: "https://staging.itsyou.online/v1/oauth/authorize", | |
TokenURL: "https://staging.itsyou.online/v1/oauth/access_token", | |
}, | |
RedirectURL: "http://127.0.0.1:5556/callback", | |
Scopes: []string{"openid,user:name,user:validated:email,user:validated:phone"}, | |
} | |
state := "foobar" // Don't do this in production. | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
http.Redirect(w, r, config.AuthCodeURL(state), http.StatusFound) | |
}) | |
http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { | |
if r.URL.Query().Get("state") != state { | |
http.Error(w, "state did not match", http.StatusBadRequest) | |
return | |
} | |
// skip verifying certificate | |
tr := &http.Transport{ | |
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, | |
} | |
sslcli := &http.Client{Transport: tr} | |
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, sslcli) | |
oauth2Token, err := config.Exchange(ctx, r.URL.Query().Get("code")) | |
if err != nil { | |
http.Error(w, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError) | |
return | |
} | |
rawIDToken, ok := oauth2Token.Extra("id_token").(string) | |
if !ok { | |
w.Write([]byte("No id_token field in oauth2 token." + "\n")) | |
} | |
w.Write([]byte(fmt.Sprintf("Token: %s\n", rawIDToken))) | |
scope, ok := oauth2Token.Extra("scope").(string) | |
if ok { | |
w.Write([]byte("\nscope: " + scope + "\n")) | |
} | |
}) | |
log.Printf("listening on http://%s/", "127.0.0.1:5556") | |
log.Fatal(http.ListenAndServe("127.0.0.1:5556", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment