Debian Codegraph @

example/client/device/device.go

raw
1 // Command device is an example Oauth2 Device Authorization Grant app.
2 // It creates a new Device Authorization request on the Issuer and then polls for tokens.
3 // The user is then prompted to visit a URL and enter the user code.
4 // Or, the complete URL can be used instead to omit manual entry.
5 // In practice then can be a "magic link" in the form or a QR.
6 //
7 // The following environment variables are used for configuration:
8 //
9 // ISSUER: URL to the OP, required.
10 // CLIENT_ID: ID of the application, required.
11 // CLIENT_SECRET: Secret to authenticate the app using basic auth. Only required if the OP expects this type of authentication.
12 // KEY_PATH: Path to a private key file, used to for JWT authentication of the App. Only required if the OP expects this type of authentication.
13 // SCOPES: Scopes of the Authentication Request. Optional.
14 //
15 // Basic usage:
16 //
17 // cd example/client/device
18 // export ISSUER="http://localhost:9000" CLIENT_ID="246048465824634593@demo"
19 //
20 // Get an Access Token:
21 //
22 // SCOPES="email profile" go run .
23 //
24 // Get an Access Token and ID Token:
25 //
26 // SCOPES="email profile openid" go run .
27 //
28 // Get an Access Token and Refresh Token
29 //
30 // SCOPES="email profile offline_access" go run .
31 //
32 // Get Access, Refresh and ID Tokens:
33 //
34 // SCOPES="email profile offline_access openid" go run .
35 package main
36
37 import (
38 "context"
39 "fmt"
40 "log/slog"
41 "os"
42 "os/signal"
43 "strings"
44 "syscall"
45 "time"
46
47 "github.com/zitadel/oidc/v3/pkg/client/rp"
48 httphelper "github.com/zitadel/oidc/v3/pkg/http"
49 "github.com/zitadel/oidc/v3/pkg/oidc"
50 )
51
52 var (
53 key = []byte("test1234test1234")
54 )
55
56 func main() {
57 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGINT)
58 defer stop()
59
60 clientID := os.Getenv("CLIENT_ID")
61 clientSecret := os.Getenv("CLIENT_SECRET")
62 keyPath := os.Getenv("KEY_PATH")
63 keyID := os.Getenv("KEY_ID")
64 issuer := os.Getenv("ISSUER")
65 scopes := strings.Split(os.Getenv("SCOPES"), " ")
66
67 cookieHandler := httphelper.NewCookieHandler(key, key, httphelper.WithUnsecure())
68
69 var options []rp.Option
70 if clientSecret == "" {
71 options = append(options, rp.WithPKCE(cookieHandler))
72 }
73 if keyPath != "" {
74 signingKey, err := os.ReadFile(keyPath)
75 if err != nil {
76 slog.Error("error reading key file", "error", err)
77 os.Exit(1)
78 }
79 options = append(options, rp.WithJWTProfile(rp.SignerFromKeyAndKeyID(signingKey, keyID)))
80 }
81
82 provider, err := rp.NewRelyingPartyOIDC(ctx, issuer, clientID, clientSecret, "", scopes, options...)
83 if err != nil {
84 slog.Error("error creating provider", "error", err)
85 os.Exit(1)
86 }
87
88 slog.Info("starting device authorization flow")
89 resp, err := rp.DeviceAuthorization(ctx, scopes, provider, nil)
90 if err != nil {
91 slog.Error("device authorization failed", "error", err)
92 os.Exit(1)
93 }
94 slog.Info("device authorization response", "response", resp)
95 fmt.Printf("\nPlease browse to %s and enter code %s\n", resp.VerificationURI, resp.UserCode)
96
97 slog.Info("start polling")
98 token, err := rp.DeviceAccessToken(ctx, resp.DeviceCode, time.Duration(resp.Interval)*time.Second, provider)
99 if err != nil {
100 slog.Error("device access token failed", "error", err)
101 os.Exit(1)
102 }
103 slog.Info("successfully obtained token", "token", token)
104
105 slog.Info("going to refresh token")
106 refreshedToken, err := rp.RefreshTokens[*oidc.IDTokenClaims](ctx, provider, token.RefreshToken, "", "")
107 if err != nil {
108 slog.Error("refresh token failed", "error", err)
109 os.Exit(1)
110 }
111 slog.Info("refreshed token", "token", refreshedToken.Token)
112
113 slog.Info("going to revoke token")
114 err = rp.RevokeToken(ctx, provider, token.AccessToken, "refresh_token")
115 if err != nil {
116 slog.Error("revoke token failed", "error", err)
117 os.Exit(1)
118 }
119 slog.Info("token revoked")
120 }