/
auth.go
105 lines (87 loc) · 2.48 KB
/
auth.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
105
package digdir
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/go-jose/go-jose/v4/jwt"
"github.com/google/uuid"
nais_io_v1 "github.com/nais/liberator/pkg/apis/nais.io/v1"
"github.com/nais/digdirator/pkg/crypto"
)
const (
grantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
applicationFormUrlEncoded = "application/x-www-form-urlencoded"
)
type TokenResponse struct {
AccessToken string `json:"access_token"`
}
type customClaims struct {
jwt.Claims
Scope string `json:"scope"`
}
func (c Client) getAuthToken(ctx context.Context) (*TokenResponse, error) {
token, err := crypto.GenerateJwt(c.Signer, c.claims())
if err != nil {
return nil, fmt.Errorf("generating JWT: %w", err)
}
endpoint := c.Config.DigDir.Maskinporten.Metadata.TokenEndpoint
req, err := authRequest(ctx, endpoint, token)
if err != nil {
return nil, err
}
resp, err := c.HttpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("doing request: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading response: %w", err)
}
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("invalid status %s: %s", resp.Status, body)
}
tokenResponse := &TokenResponse{}
if err := json.Unmarshal(body, tokenResponse); err != nil {
return nil, fmt.Errorf("unmarshalling: %w", err)
}
return tokenResponse, nil
}
func (c Client) claims() customClaims {
var scopes string
switch c.instance.(type) {
case *nais_io_v1.IDPortenClient:
scopes = c.Config.DigDir.IDPorten.Scopes
case *nais_io_v1.MaskinportenClient:
scopes = c.Config.DigDir.Maskinporten.Scopes
}
return customClaims{
Claims: jwt.Claims{
Issuer: string(c.ClientId),
Audience: []string{c.Config.DigDir.Maskinporten.Metadata.Issuer},
Expiry: jwt.NewNumericDate(time.Now().Add(2 * time.Minute)),
NotBefore: jwt.NewNumericDate(time.Now()),
IssuedAt: jwt.NewNumericDate(time.Now()),
ID: uuid.New().String(),
},
Scope: scopes,
}
}
func authRequest(ctx context.Context, endpoint, token string) (*http.Request, error) {
params := url.Values{
"grant_type": []string{grantType},
"assertion": []string{token},
}
body := strings.NewReader(params.Encode())
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, body)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
req.Header.Set("Content-Type", applicationFormUrlEncoded)
return req, nil
}