示例
golang.org/x/oauth2 v0.36.0: exchange authorization code for access token and create authenticated HTTP client with oauth2.Config
已验证示例 — golang golang.org/x/oauth2 v0.36.0: exchange authorization code for access token and create authenticated HTTP client with oauth2.Config. contract 在…
sha256:ee09b96fb789881da6468472a47acfd6953017b9f72fb46486a1e4bb91019caf
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 2
- 构建过它的签名密钥
- 1
声明的环境
linux 24 · ubuntu · glibc 2.39 x64 go
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | FAIL | compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f… |
2026-08-28 |
| go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f… |
2026-08-30 |
案例
HOW- 目标
- exchange authorization code for access token and create authenticated HTTP client with oauth2.Config
- 符号
-
- oauth2.Config.Client
- oauth2.Config.Exchange
- 创建时间
- 2026-08-28T10:44:26Z
契约
- oauth2.Config.AuthCodeURL generates authorization URL with state, client_id, redirect_uri, and scopes
- oauth2.Config.Exchange exchanges authorization code for Token with access_token, token_type, and expiry from token server
- oauth2.Config.Exchange returns error when token server responds with HTTP error or invalid grant
- oauth2.Config.Client creates an http.Client whose transport adds Authorization Bearer header with the access token
- oauth2.Token.Valid returns true for non-empty unexpired token and false for expired token
- oauth2.Config.TokenSource returns a TokenSource that automatically refreshes an expired token using refresh_token
文件
- PROMPT.md
- csx.json
- go.mod
- go.sum
- main.go
- spec.json
- test/contract.go
源代码
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: exchange authorization code for access token and create authenticated HTTP client with oauth2.Config
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:golang/golang.org/x/oauth2@v0.36.0
Demonstrate these symbols/APIs:
- oauth2.Config.Client
- oauth2.Config.Exchange
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:b84c58efc0da1d4dc35866e3d99533d63d1da80501b84e47adfe9b3cba1d43f7","contract":["oauth2.Config.AuthCodeURL generates authorization URL with state, client_id, redirect_uri, and scopes","oauth2.Config.Exchange exchanges authorization code for Token with access_token, token_type, and expiry from token server","oauth2.Config.Exchange returns error when token server responds with HTTP error or invalid grant","oauth2.Config.Client creates an http.Client whose transport adds Authorization Bearer header with the access token","oauth2.Token.Valid returns true for non-empty unexpired token and false for expired token","oauth2.Config.TokenSource returns a TokenSource that automatically refreshes an expired token using refresh_token"],"goal":"exchange authorization code for access token and create authenticated HTTP client with oauth2.Config","kind":"HOW","packages":["pkg:golang/golang.org/x/oauth2@v0.36.0"],"schemaVersion":1,"symbols":["oauth2.Config.Client","oauth2.Config.Exchange"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/oauth2@v0.36.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/oauth2@v0.36.0","symbols":["oauth2.Config.Client","oauth2.Config.Exchange"],"verifierAdapter":"golang@1"}
module example.com/sample
go 1.25.0
require golang.org/x/oauth2 v0.36.0
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"time"
"golang.org/x/oauth2"
)
func main() {
ctx := context.Background()
// 1. Mock OAuth2 provider server (token endpoint and protected API endpoint)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/oauth/token":
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
_ = r.ParseForm()
grantType := r.Form.Get("grant_type")
if grantType == "authorization_code" {
code := r.Form.Get("code")
if code == "sample-auth-code" {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"access_token": "access-token-xyz-123",
"token_type": "Bearer",
"refresh_token": "refresh-token-xyz-456",
"expires_in": 3600,
})
return
}
http.Error(w, `{"error":"invalid_grant"}`, http.StatusBadRequest)
return
}
http.Error(w, `{"error":"unsupported_grant_type"}`, http.StatusBadRequest)
return
case "/api/userinfo":
authHeader := r.Header.Get("Authorization")
if authHeader != "Bearer access-token-xyz-123" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"sub":"user-42","name":"Demo User"}`)
return
default:
http.NotFound(w, r)
}
}))
defer ts.Close()
// 2. Configure OAuth2 client
conf := &oauth2.Config{
ClientID: "demo-client-id",
ClientSecret: "demo-client-secret",
Scopes: []string{"profile", "email"},
RedirectURL: "https://example.com/oauth/callback",
Endpoint: oauth2.Endpoint{
AuthURL: ts.URL + "/oauth/authorize",
TokenURL: ts.URL + "/oauth/token",
},
}
// 3. Generate authorization code URL
authURL := conf.AuthCodeURL("random-state-12345", oauth2.AccessTypeOffline)
fmt.Printf("Authorization URL: %s\n", authURL)
// 4. Exchange authorization code for token
token, err := conf.Exchange(ctx, "sample-auth-code")
if err != nil {
log.Fatalf("Failed to exchange code: %v", err)
}
fmt.Printf("Obtained Access Token: %s (Type: %s, Expiry: %s)\n",
token.AccessToken, token.TokenType, token.Expiry.Format(time.RFC3339))
// 5. Create authenticated HTTP client
client := conf.Client(ctx, token)
resp, err := client.Get(ts.URL + "/api/userinfo")
if err != nil {
log.Fatalf("Failed to fetch userinfo: %v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Failed to read response body: %v", err)
}
fmt.Printf("Userinfo Response: %s\n", string(body))
}
{
"schemaVersion": 1,
"goal": "exchange authorization code for access token and create authenticated HTTP client with oauth2.Config",
"kind": "HOW",
"packages": [
"pkg:golang/golang.org/x/oauth2@v0.36.0"
],
"symbols": [
"oauth2.Config.Client",
"oauth2.Config.Exchange"
]
}
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"time"
"golang.org/x/oauth2"
)
func main() {
ctx := context.Background()
// 1. oauth2.Config.AuthCodeURL generates authorization URL with state, client_id, redirect_uri, and scopes
conf := &oauth2.Config{
ClientID: "test-client-id-42",
ClientSecret: "test-client-secret-99",
Scopes: []string{"read", "write"},
RedirectURL: "https://example.com/callback",
Endpoint: oauth2.Endpoint{
AuthURL: "https://example.com/oauth/authorize",
TokenURL: "https://example.com/oauth/token",
},
}
authURLStr := conf.AuthCodeURL("random-state-abc", oauth2.AccessTypeOffline)
parsedURL, err := url.Parse(authURLStr)
if err != nil {
fmt.Fprintf(os.Stderr, "AuthCodeURL produced invalid URL: %v\n", err)
os.Exit(1)
}
query := parsedURL.Query()
if query.Get("state") != "random-state-abc" {
fmt.Fprintf(os.Stderr, "AuthCodeURL state mismatch: got %q, want 'random-state-abc'\n", query.Get("state"))
os.Exit(1)
}
if query.Get("client_id") != "test-client-id-42" {
fmt.Fprintf(os.Stderr, "AuthCodeURL client_id mismatch: got %q, want 'test-client-id-42'\n", query.Get("client_id"))
os.Exit(1)
}
if query.Get("redirect_uri") != "https://example.com/callback" {
fmt.Fprintf(os.Stderr, "AuthCodeURL redirect_uri mismatch: got %q\n", query.Get("redirect_uri"))
os.Exit(1)
}
if query.Get("response_type") != "code" {
fmt.Fprintf(os.Stderr, "AuthCodeURL response_type mismatch: got %q, want 'code'\n", query.Get("response_type"))
os.Exit(1)
}
if !strings.Contains(query.Get("scope"), "read") || !strings.Contains(query.Get("scope"), "write") {
fmt.Fprintf(os.Stderr, "AuthCodeURL scope missing expected scopes: got %q\n", query.Get("scope"))
os.Exit(1)
}
// 2. Setup mock OAuth2 token and resource server for Exchange and Client tests
var tokenRequests []*http.Request
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/token":
_ = r.ParseForm()
grantType := r.Form.Get("grant_type")
if grantType == "authorization_code" {
code := r.Form.Get("code")
if code == "valid-auth-code-123" {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"access_token": "access-token-live-abc",
"token_type": "Bearer",
"refresh_token": "refresh-token-live-xyz",
"expires_in": 3600,
})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": "invalid_grant",
"error_description": "code is invalid or expired",
})
return
} else if grantType == "refresh_token" {
refreshToken := r.Form.Get("refresh_token")
if refreshToken == "refresh-token-live-xyz" {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"access_token": "access-token-refreshed-789",
"token_type": "Bearer",
"refresh_token": "refresh-token-live-xyz",
"expires_in": 3600,
})
return
}
w.WriteHeader(http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusBadRequest)
case "/protected/profile":
authHeader := r.Header.Get("Authorization")
if authHeader == "Bearer access-token-live-abc" {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"id":"user-100","status":"active"}`)
return
}
w.WriteHeader(http.StatusUnauthorized)
default:
http.NotFound(w, r)
}
}))
defer ts.Close()
serverConf := &oauth2.Config{
ClientID: "mock-client-id",
ClientSecret: "mock-client-secret",
Endpoint: oauth2.Endpoint{
AuthURL: ts.URL + "/authorize",
TokenURL: ts.URL + "/token",
},
}
// 2. oauth2.Config.Exchange exchanges authorization code for Token with access_token, token_type, and expiry from token server
tok, err := serverConf.Exchange(ctx, "valid-auth-code-123")
if err != nil {
fmt.Fprintf(os.Stderr, "Exchange failed for valid code: %v\n", err)
os.Exit(1)
}
if tok.AccessToken != "access-token-live-abc" {
fmt.Fprintf(os.Stderr, "Exchange access_token mismatch: got %q\n", tok.AccessToken)
os.Exit(1)
}
if tok.TokenType != "Bearer" {
fmt.Fprintf(os.Stderr, "Exchange token_type mismatch: got %q\n", tok.TokenType)
os.Exit(1)
}
if tok.RefreshToken != "refresh-token-live-xyz" {
fmt.Fprintf(os.Stderr, "Exchange refresh_token mismatch: got %q\n", tok.RefreshToken)
os.Exit(1)
}
if !tok.Valid() {
fmt.Fprintf(os.Stderr, "Exchange token expected to be valid, got invalid\n")
os.Exit(1)
}
// 3. oauth2.Config.Exchange returns error when token server responds with HTTP error or invalid grant
_, err = serverConf.Exchange(ctx, "bad-code-999")
if err == nil {
fmt.Fprintf(os.Stderr, "Exchange expected error for invalid code, got nil\n")
os.Exit(1)
}
var retrieveErr *oauth2.RetrieveError
if !strings.Contains(err.Error(), "invalid_grant") && !strings.Contains(err.Error(), "oauth2: cannot fetch token") {
fmt.Fprintf(os.Stderr, "Exchange returned unexpected error format: %v\n", err)
os.Exit(1)
}
// 4. oauth2.Config.Client creates an http.Client whose transport adds Authorization Bearer header with the access token
client := serverConf.Client(ctx, tok)
resp, err := client.Get(ts.URL + "/protected/profile")
if err != nil {
fmt.Fprintf(os.Stderr, "Client.Get failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Fprintf(os.Stderr, "Client.Get status code mismatch: got %d, want 200\n", resp.StatusCode)
os.Exit(1)
}
respBytes, err := io.ReadAll(resp.Body)
if err != nil || !strings.Contains(string(respBytes), `"user-100"`) {
fmt.Fprintf(os.Stderr, "Client.Get response body mismatch: %s\n", string(respBytes))
os.Exit(1)
}
// 5. oauth2.Token.Valid returns true for non-empty unexpired token and false for expired token
expiredTok := &oauth2.Token{
AccessToken: "expired-token-123",
TokenType: "Bearer",
RefreshToken: "refresh-token-live-xyz",
Expiry: time.Now().Add(-10 * time.Minute),
}
if expiredTok.Valid() {
fmt.Fprintf(os.Stderr, "expiredTok.Valid() expected false, got true\n")
os.Exit(1)
}
futureTok := &oauth2.Token{
AccessToken: "future-token-123",
TokenType: "Bearer",
Expiry: time.Now().Add(10 * time.Minute),
}
if !futureTok.Valid() {
fmt.Fprintf(os.Stderr, "futureTok.Valid() expected true, got false\n")
os.Exit(1)
}
// 6. oauth2.Config.TokenSource returns a TokenSource that automatically refreshes an expired token using refresh_token
tokenSource := serverConf.TokenSource(ctx, expiredTok)
refreshedTok, err := tokenSource.Token()
if err != nil {
fmt.Fprintf(os.Stderr, "TokenSource failed to refresh token: %v\n", err)
os.Exit(1)
}
if refreshedTok.AccessToken != "access-token-refreshed-789" {
fmt.Fprintf(os.Stderr, "Refreshed token access_token mismatch: got %q\n", refreshedTok.AccessToken)
os.Exit(1)
}
if !refreshedTok.Valid() {
fmt.Fprintf(os.Stderr, "Refreshed token should be valid\n")
os.Exit(1)
}
_ = tokenRequests
_ = retrieveErr
fmt.Println("All oauth2 contract assertions passed.")
}
原始种子者
匿名