fix: Refactor to use oauth2 package

This commit is contained in:
2024-03-10 15:48:44 +11:00
parent 907fc9249c
commit bb4bd5111f
3 changed files with 63 additions and 72 deletions

View File

@ -7,63 +7,51 @@ import (
"net/http"
"os"
"os/signal"
"pkg/spamasaurusrex/pkg/graphhelper"
"syscall"
"time"
_ "github.com/breml/rootcerts"
"github.com/davecgh/go-spew/spew"
"github.com/gorilla/mux"
"github.com/davecgh/go-spew/spew"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
"golang.org/x/oauth2"
"golang.org/x/oauth2/microsoft"
)
func handler(w http.ResponseWriter, r *http.Request) {
clientId := "dccb4b93-3f75-4775-a94a-da39216d7daf"
tenantId := "ceeae22e-f163-4ac9-b7c2-45972d3aed4f"
redirectURI := "https://alias.spamasaurus.com/"
scopes := []string{"user.read"}
queryParams := r.URL.Query()
var config = oauth2.Config{
ClientID: "dccb4b93-3f75-4775-a94a-da39216d7daf",
ClientSecret: "tiL8Q~qahoaZUck4ZG4sc5w.V_I.1c60bwkW6aYJ",
Endpoint: microsoft.AzureADEndpoint("ceeae22e-f163-4ac9-b7c2-45972d3aed4f"),
RedirectURL: "https://alias.spamasaurus.com//callback",
Scopes: []string{"User.Read"},
}
ctx := context.Background()
func rootHandler(w http.ResponseWriter, r *http.Request) {
url := config.AuthCodeURL("state", oauth2.AccessTypeOffline)
http.Redirect(w, r, url, http.StatusFound)
}
// confidential clients have a credential, such as a secret or a certificate
cred, err := confidential.NewCredFromSecret("client_secret")
func callbackHandler(w http.ResponseWriter, r *http.Request) {
// Handle the callback after successful authentication
code := r.URL.Query().Get("code")
token, err := config.Exchange(r.Context(), code)
if err != nil {
// TODO: handle error
}
confidentialClient, err := confidential.New("https://login.microsoftonline.com/"+tenantId, clientId, cred)
if err != nil {
// TODO: handle error
http.Error(w, "Error exchanging code for token", http.StatusInternalServerError)
return
}
result, err := confidentialClient.AcquireTokenSilent(ctx, scopes)
if err != nil {
// cache miss, authenticate with another AcquireToken... method
// result, err = confidentialClient.AcquireTokenByCredential(ctx, scopes)
result, err = confidentialClient.AcquireTokenByAuthCode(ctx, queryParams["code"][0], redirectURI, scopes)
if err != nil {
// TODO: handle error
}
}
// accessToken := result.AccessToken
w.Write([]byte(fmt.Sprintf("Hello, %s\n", spew.Sdump(result))))
// Use the token to make MS Graph queries
// Example: Fetch user profile information
// ...
w.Write([]byte(spew.Sdump(token)))
fmt.Fprintln(w, "Authentication successful!")
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
clientId := "dccb4b93-3f75-4775-a94a-da39216d7daf"
tenantId := "ceeae22e-f163-4ac9-b7c2-45972d3aed4f"
redirectURI := "https://alias.spamasaurus.com/"
http.Redirect(w, r,
"https://login.microsoftonline.com/"+tenantId+"/oauth2/v2.0/authorize?client_id="+clientId+"&response_type=code&redirect_uri="+redirectURI+"&scope=openid profile offline_access", http.StatusMovedPermanently)
}
func readinessHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
@ -71,9 +59,9 @@ func readinessHandler(w http.ResponseWriter, r *http.Request) {
func main() {
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.HandleFunc("/", rootHandler)
r.HandleFunc("/health", healthHandler)
r.HandleFunc("/login", loginHandler)
r.HandleFunc("/callback", callbackHandler)
r.HandleFunc("/readiness", readinessHandler)
srv := &http.Server{
@ -110,24 +98,3 @@ func waitForShutdown(srv *http.Server) {
log.Println("Shutting down")
os.Exit(0)
}
func initializeGraph(graphHelper *graphhelper.GraphHelper) {
err := graphHelper.InitializeGraphForUserAuth()
if err != nil {
log.Panicf("Error initializing Graph for user auth: %v\n", err)
}
}
func displayAccessToken(graphHelper *graphhelper.GraphHelper) {
token, err := graphHelper.GetUserToken()
if err != nil {
log.Panicf("Error getting user token: %v\n", err)
}
fmt.Printf("User token: %s", *token)
fmt.Println()
}
func makeGraphCall(graphHelper *graphhelper.GraphHelper) {
// TODO
}