-
Notifications
You must be signed in to change notification settings - Fork 3
/
introspect.go
104 lines (84 loc) · 2.13 KB
/
introspect.go
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package clients
import (
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
"authelia.com/provider/oauth2/internal/consts"
)
type IntrospectForm struct {
Token string
Scopes []string
}
type IntrospectResponse struct {
Active bool `json:"active"`
ClientID string `json:"client_id,omitempty"`
Scope string `json:"scope,omitempty"`
Audience []string `json:"aud,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
Subject string `json:"sub,omitempty"`
Username string `json:"username,omitempty"`
}
type Introspect struct {
endpointURL string
client *http.Client
}
func (c *Introspect) IntrospectToken(
ctx context.Context,
form IntrospectForm,
header map[string]string,
) (*IntrospectResponse, error) {
data := url.Values{}
data.Set(consts.FormParameterToken, form.Token)
data.Set(consts.FormParameterScope, strings.Join(form.Scopes, " "))
request, err := c.getRequest(ctx, data, header)
if err != nil {
return nil, err
}
response, err := c.client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
if c := response.StatusCode; c < 200 || c > 299 {
return nil, &RequestError{
Response: response,
Body: body,
}
}
result := &IntrospectResponse{}
if err := json.Unmarshal(body, result); err != nil {
return nil, err
}
return result, nil
}
func (c *Introspect) getRequest(
ctx context.Context,
data url.Values,
header map[string]string,
) (*http.Request, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpointURL, strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
request.Header.Set(consts.HeaderContentType, consts.ContentTypeApplicationURLEncodedForm)
for header, value := range header {
request.Header.Set(header, value)
}
return request, nil
}
func NewIntrospectClient(endpointURL string) *Introspect {
return &Introspect{
endpointURL: endpointURL,
client: &http.Client{},
}
}