| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"encoding/json" |
| 6 |
"fmt" |
| 7 |
"log/slog" |
| 8 |
"net/http" |
| 9 |
"os" |
| 10 |
"strconv" |
| 11 |
"strings" |
| 12 |
"sync/atomic" |
| 13 |
"time" |
| 14 |
|
| 15 |
"github.com/google/uuid" |
| 16 |
|
| 17 |
"github.com/zitadel/oidc/v3/pkg/client/rp" |
| 18 |
httphelper "github.com/zitadel/oidc/v3/pkg/http" |
| 19 |
"github.com/zitadel/oidc/v3/pkg/oidc" |
| 20 |
) |
| 21 |
|
| 22 |
var ( |
| 23 |
callbackPath = "/auth/callback" |
| 24 |
key = []byte("test1234test1234") |
| 25 |
requestCount atomic.Uint64 |
| 26 |
) |
| 27 |
|
| 28 |
func main() { |
| 29 |
clientID := os.Getenv("CLIENT_ID") |
| 30 |
clientSecret := os.Getenv("CLIENT_SECRET") |
| 31 |
keyPath := os.Getenv("KEY_PATH") |
| 32 |
keyID := os.Getenv("KEY_ID") |
| 33 |
issuer := os.Getenv("ISSUER") |
| 34 |
port := os.Getenv("PORT") |
| 35 |
scopes := strings.Split(os.Getenv("SCOPES"), " ") |
| 36 |
responseMode := os.Getenv("RESPONSE_MODE") |
| 37 |
|
| 38 |
var pkce bool |
| 39 |
if pkceEnv, ok := os.LookupEnv("PKCE"); ok { |
| 40 |
var err error |
| 41 |
pkce, err = strconv.ParseBool(pkceEnv) |
| 42 |
if err != nil { |
| 43 |
slog.Error("error parsing PKCE", "error", err) |
| 44 |
os.Exit(1) |
| 45 |
} |
| 46 |
} |
| 47 |
redirectURI := fmt.Sprintf("http://127.0.0.1:%v%v", port, callbackPath) |
| 48 |
cookieHandler := httphelper.NewCookieHandler(key, key, httphelper.WithUnsecure()) |
| 49 |
|
| 50 |
logger := slog.New( |
| 51 |
slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ |
| 52 |
AddSource: true, |
| 53 |
Level: slog.LevelDebug, |
| 54 |
}), |
| 55 |
) |
| 56 |
slog.SetDefault(logger) |
| 57 |
client := &http.Client{ |
| 58 |
Timeout: time.Minute, |
| 59 |
Transport: loggingRoundTripper{base: http.DefaultTransport}, |
| 60 |
} |
| 61 |
|
| 62 |
options := []rp.Option{ |
| 63 |
rp.WithCookieHandler(cookieHandler), |
| 64 |
rp.WithVerifierOpts(rp.WithIssuedAtOffset(5 * time.Second)), |
| 65 |
rp.WithHTTPClient(client), |
| 66 |
rp.WithSigningAlgsFromDiscovery(), |
| 67 |
} |
| 68 |
if clientSecret == "" { |
| 69 |
options = append(options, rp.WithPKCE(cookieHandler)) |
| 70 |
} |
| 71 |
if keyPath != "" { |
| 72 |
signingKey, err := os.ReadFile(keyPath) |
| 73 |
if err != nil { |
| 74 |
slog.Error("error reading key file", "error", err) |
| 75 |
os.Exit(1) |
| 76 |
} |
| 77 |
options = append(options, rp.WithJWTProfile(rp.SignerFromKeyAndKeyID(signingKey, keyID))) |
| 78 |
} |
| 79 |
if pkce { |
| 80 |
options = append(options, rp.WithPKCE(cookieHandler)) |
| 81 |
} |
| 82 |
|
| 83 |
ctx := context.TODO() |
| 84 |
provider, err := rp.NewRelyingPartyOIDC(ctx, issuer, clientID, clientSecret, redirectURI, scopes, options...) |
| 85 |
if err != nil { |
| 86 |
slog.Error("error creating provider", "error", err) |
| 87 |
os.Exit(1) |
| 88 |
} |
| 89 |
|
| 90 |
// generate some state (representing the state of the user in your application, |
| 91 |
// e.g. the page where he was before sending him to login |
| 92 |
state := func() string { |
| 93 |
return uuid.New().String() |
| 94 |
} |
| 95 |
|
| 96 |
urlOptions := []rp.URLParamOpt{ |
| 97 |
rp.WithPromptURLParam("Welcome back!"), |
| 98 |
} |
| 99 |
|
| 100 |
if responseMode != "" { |
| 101 |
urlOptions = append(urlOptions, rp.WithResponseModeURLParam(oidc.ResponseMode(responseMode))) |
| 102 |
} |
| 103 |
|
| 104 |
// register the AuthURLHandler at your preferred path. |
| 105 |
// the AuthURLHandler creates the auth request and redirects the user to the auth server. |
| 106 |
// including state handling with secure cookie and the possibility to use PKCE. |
| 107 |
// Prompts can optionally be set to inform the server of |
| 108 |
// any messages that need to be prompted back to the user. |
| 109 |
http.Handle("/login", rp.AuthURLHandler( |
| 110 |
state, |
| 111 |
provider, |
| 112 |
urlOptions..., |
| 113 |
)) |
| 114 |
|
| 115 |
// for demonstration purposes the returned userinfo response is written as JSON object onto response |
| 116 |
marshalUserinfo := func(w http.ResponseWriter, r *http.Request, tokens *oidc.Tokens[*oidc.IDTokenClaims], state string, rp rp.RelyingParty, info *oidc.UserInfo) { |
| 117 |
fmt.Println("access token", tokens.AccessToken) |
| 118 |
fmt.Println("refresh token", tokens.RefreshToken) |
| 119 |
fmt.Println("id token", tokens.IDToken) |
| 120 |
|
| 121 |
data, err := json.Marshal(info) |
| 122 |
if err != nil { |
| 123 |
http.Error(w, err.Error(), http.StatusInternalServerError) |
| 124 |
return |
| 125 |
} |
| 126 |
w.Header().Set("content-type", "application/json") |
| 127 |
w.Write(data) |
| 128 |
} |
| 129 |
|
| 130 |
// you could also just take the access_token and id_token without calling the userinfo endpoint: |
| 131 |
// |
| 132 |
// marshalToken := func(w http.ResponseWriter, r *http.Request, tokens *oidc.Tokens, state string, rp rp.RelyingParty) { |
| 133 |
// data, err := json.Marshal(tokens) |
| 134 |
// if err != nil { |
| 135 |
// http.Error(w, err.Error(), http.StatusInternalServerError) |
| 136 |
// return |
| 137 |
// } |
| 138 |
// w.Write(data) |
| 139 |
//} |
| 140 |
|
| 141 |
// you can also try token exchange flow |
| 142 |
// |
| 143 |
// requestTokenExchange := func(w http.ResponseWriter, r *http.Request, tokens *oidc.Tokens, state string, rp rp.RelyingParty, info oidc.UserInfo) { |
| 144 |
// data := make(url.Values) |
| 145 |
// data.Set("grant_type", string(oidc.GrantTypeTokenExchange)) |
| 146 |
// data.Set("requested_token_type", string(oidc.IDTokenType)) |
| 147 |
// data.Set("subject_token", tokens.RefreshToken) |
| 148 |
// data.Set("subject_token_type", string(oidc.RefreshTokenType)) |
| 149 |
// data.Add("scope", "profile custom_scope:impersonate:id2") |
| 150 |
|
| 151 |
// client := &http.Client{} |
| 152 |
// r2, _ := http.NewRequest(http.MethodPost, issuer+"/oauth/token", strings.NewReader(data.Encode())) |
| 153 |
// // r2.Header.Add("Authorization", "Basic "+"d2ViOnNlY3JldA==") |
| 154 |
// r2.Header.Add("Content-Type", "application/x-www-form-urlencoded") |
| 155 |
// r2.SetBasicAuth("web", "secret") |
| 156 |
|
| 157 |
// resp, _ := client.Do(r2) |
| 158 |
// fmt.Println(resp.Status) |
| 159 |
|
| 160 |
// b, _ := io.ReadAll(resp.Body) |
| 161 |
// resp.Body.Close() |
| 162 |
|
| 163 |
// w.Write(b) |
| 164 |
// } |
| 165 |
|
| 166 |
// register the CodeExchangeHandler at the callbackPath |
| 167 |
// the CodeExchangeHandler handles the auth response, creates the token request and calls the callback function |
| 168 |
// with the returned tokens from the token endpoint |
| 169 |
// in this example the callback function itself is wrapped by the UserinfoCallback which |
| 170 |
// will call the Userinfo endpoint, check the sub and pass the info into the callback function |
| 171 |
http.Handle(callbackPath, rp.CodeExchangeHandler(rp.UserinfoCallback(marshalUserinfo), provider)) |
| 172 |
|
| 173 |
// if you would use the callback without calling the userinfo endpoint, simply switch the callback handler for: |
| 174 |
// |
| 175 |
// http.Handle(callbackPath, rp.CodeExchangeHandler(marshalToken, provider)) |
| 176 |
|
| 177 |
lis := fmt.Sprintf("127.0.0.1:%s", port) |
| 178 |
slog.Info("server listening, press ctrl+c to stop", "addr", lis) |
| 179 |
err = http.ListenAndServe(lis, requestLoggingMiddleware(http.DefaultServeMux)) |
| 180 |
if err != http.ErrServerClosed { |
| 181 |
slog.Error("server terminated", "error", err) |
| 182 |
os.Exit(1) |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
// requestLoggingMiddleware demonstrates request IDs and structured incoming |
| 187 |
// request logs using only the standard library. |
| 188 |
func requestLoggingMiddleware(next http.Handler) http.Handler { |
| 189 |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 190 |
requestID := requestCount.Add(1) |
| 191 |
w.Header().Set("X-Request-ID", strconv.FormatUint(requestID, 10)) |
| 192 |
started := time.Now() |
| 193 |
|
| 194 |
next.ServeHTTP(w, r) |
| 195 |
|
| 196 |
slog.InfoContext(r.Context(), "http request", |
| 197 |
"request_id", requestID, |
| 198 |
"method", r.Method, |
| 199 |
"path", r.URL.Path, |
| 200 |
"duration", time.Since(started), |
| 201 |
) |
| 202 |
}) |
| 203 |
} |
| 204 |
|
| 205 |
// loggingRoundTripper demonstrates lightweight tracing of outbound discovery |
| 206 |
// and token requests. A production application could replace this with its |
| 207 |
// preferred tracing transport. |
| 208 |
type loggingRoundTripper struct { |
| 209 |
base http.RoundTripper |
| 210 |
} |
| 211 |
|
| 212 |
func (t loggingRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { |
| 213 |
started := time.Now() |
| 214 |
response, err := t.base.RoundTrip(r) |
| 215 |
if err != nil { |
| 216 |
slog.DebugContext(r.Context(), "http client request", |
| 217 |
"method", r.Method, |
| 218 |
"host", r.URL.Host, |
| 219 |
"path", r.URL.Path, |
| 220 |
"duration", time.Since(started), |
| 221 |
"error", err, |
| 222 |
) |
| 223 |
return nil, err |
| 224 |
} |
| 225 |
slog.DebugContext(r.Context(), "http client request", |
| 226 |
"method", r.Method, |
| 227 |
"host", r.URL.Host, |
| 228 |
"path", r.URL.Path, |
| 229 |
"status_code", response.StatusCode, |
| 230 |
"duration", time.Since(started), |
| 231 |
) |
| 232 |
return response, nil |
| 233 |
} |