-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoauth.go
More file actions
87 lines (73 loc) · 2.24 KB
/
Copy pathoauth.go
File metadata and controls
87 lines (73 loc) · 2.24 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
var httpClient = &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
},
},
}
// DiscoverOIDC fetches the OpenID Connect configuration from the issuer URL
func DiscoverOIDC(issuerURL string) (*OIDCConfig, error) {
if !strings.HasPrefix(issuerURL, "https://") {
return nil, fmt.Errorf("issuer URL must use HTTPS: %s", issuerURL)
}
wellKnownURL := strings.TrimRight(issuerURL, "/") + "/.well-known/openid-configuration"
resp, err := httpClient.Get(wellKnownURL)
if err != nil {
return nil, fmt.Errorf("OIDC discovery request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("OIDC discovery returned status %d", resp.StatusCode)
}
var config OIDCConfig
if err := json.NewDecoder(resp.Body).Decode(&config); err != nil {
return nil, fmt.Errorf("failed to parse OIDC discovery response: %w", err)
}
if config.TokenEndpoint == "" {
return nil, fmt.Errorf("OIDC discovery response missing token_endpoint")
}
return &config, nil
}
// RequestToken performs a client_credentials grant against the token endpoint
func RequestToken(tokenEndpoint, clientID, clientSecret, scopes string) (*TokenResponse, error) {
if !strings.HasPrefix(tokenEndpoint, "https://") {
return nil, fmt.Errorf("token endpoint must use HTTPS: %s", tokenEndpoint)
}
data := url.Values{
"grant_type": {"client_credentials"},
"client_id": {clientID},
"client_secret": {clientSecret},
}
if scopes != "" {
data.Set("scope", scopes)
}
resp, err := httpClient.PostForm(tokenEndpoint, data)
if err != nil {
return nil, fmt.Errorf("token request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read token response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("token endpoint returned status %d: %s", resp.StatusCode, string(body))
}
var token TokenResponse
if err := json.Unmarshal(body, &token); err != nil {
return nil, fmt.Errorf("failed to parse token response: %w", err)
}
return &token, nil
}