Commit 86a550e181b5647e58baf3fd51a473690b635afe

Parents: d9ac6d02c2d9e4659b8200d8ee0d44290f4014d6

From: Moritz Poldrack <git@moritz.sh>
Date: Sat Dec 23 21:31:01 2023 +0700

add example

		

Stats

example/main.go +55/-0

Changeset

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
diff --git a/example/main.go b/example/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c331618b4a6bf9950d1eec3eec9656ff24d2ffd6
--- /dev/null
+++ b/example/main.go
@@ -0,0 +1,55 @@
+package main
+
+// SPDX-FileCopyrightText: © Moritz Poldrack
+// SPDX-License-Identifier: MPL-2.0
+
+import (
+	"log"
+	"net/http"
+
+	"mpldr.codes/oidc"
+)
+
+const (
+	issuer       = "https://sso.provi.de/application/o/my-cool-app"
+	clientID     = "my-cool-app"
+	clientSecret = "my-cool-app-secret"
+)
+
+var cfg *oidc.Configuration
+
+func main() {
+	log.Print("Setting up OpenID Connect")
+	var err error
+	cfg, err = oidc.Configure(issuer, "http://localhost:1561/callback")
+	if err != nil {
+		log.Fatalf("Failed to setup OpenID Connect: %v", err)
+	}
+	cfg.SetCredentials(clientID, clientSecret)
+	cfg.SetScopes("openid", "email") // optional: set scopes
+
+	log.Print("Setting up server")
+	http.HandleFunc("/callback", callbackHandler)
+	go http.ListenAndServe(":1561", nil)
+
+	log.Printf("Open %s in your browser", cfg.GetAuthorizationURL())
+	<-make(chan struct{})
+}
+
+func callbackHandler(w http.ResponseWriter, r *http.Request) {
+	tok, err := cfg.Callback(r.FormValue("code"), r.FormValue("state"))
+	if err != nil {
+		http.Error(w, err.Error(), http.StatusUnauthorized)
+		log.Printf("Error exchanging token: %v", err)
+		return
+	}
+
+	accessToken, err := tok.Token()
+	if err != nil {
+		http.Error(w, err.Error(), http.StatusUnauthorized)
+		log.Printf("Error getting access token: %v", err)
+		return
+	}
+
+	log.Printf("got access token: %s", accessToken.AccessToken)
+}