Refactored, reorganized, fixed issues, and implemented functionality

This commit is contained in:
David Allen 2024-02-24 00:26:51 -07:00
parent 3edc5e1191
commit 5428085fdf
No known key found for this signature in database
GPG key ID: 1D2A29322FBB6FCB
9 changed files with 524 additions and 190 deletions

View file

@ -1,8 +1,13 @@
package oidc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"github.com/lestrrat-go/jwx/jwk"
)
@ -15,7 +20,7 @@ type IdentityProvider struct {
}
type Endpoints struct {
Authorize string `json:"authorize_endpoint" yaml:"authorize"`
Authorization string `json:"authorization_endpoint" yaml:"authorization"`
Token string `json:"token_endpoint" yaml:"token"`
Revocation string `json:"revocation_endpoint" yaml:"revocation"`
Introspection string `json:"introspection_endpoint" yaml:"introspection"`
@ -36,7 +41,7 @@ type Supported struct {
func NewIdentityProvider() *IdentityProvider {
p := &IdentityProvider{Issuer: "127.0.0.1"}
p.Endpoints = Endpoints{
Authorize: p.Issuer + "/oauth/authorize",
Authorization: p.Issuer + "/oauth/authorize",
Token: p.Issuer + "/oauth/token",
Revocation: p.Issuer + "/oauth/revocation",
Introspection: p.Issuer + "/oauth/introspect",
@ -69,12 +74,70 @@ func NewIdentityProvider() *IdentityProvider {
return p
}
func (p *IdentityProvider) FetchServerConfig(url string) {
func (p *IdentityProvider) ParseServerConfig(data []byte) error {
// parse JSON into IdentityProvider fields
var ep Endpoints
var s Supported
var e error
epErr := json.Unmarshal(data, &ep)
if epErr != nil {
e = fmt.Errorf("%v", epErr)
}
sErr := json.Unmarshal(data, &s)
if sErr != nil {
e = fmt.Errorf("%v %v", e, sErr)
}
err := json.Unmarshal(data, p)
if err != nil {
e = fmt.Errorf("%v %v", e, err)
}
p.Endpoints = ep
p.Supported = s
return e
}
func (p *IdentityProvider) LoadServerConfig(path string) error {
// load server config from local file i
data, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("failed to read server config: %v", err)
}
err = p.ParseServerConfig(data)
if err != nil {
return fmt.Errorf("failed to parse server config: %v", err)
}
return nil
}
func (p *IdentityProvider) FetchServerConfig(url string) error {
// make a request to a server's openid-configuration
req, err := http.NewRequest("GET", url, bytes.NewBuffer([]byte{}))
if err != nil {
return fmt.Errorf("failed to create a new request: %v", err)
}
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to do request: %v", err)
}
body, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %v", err)
}
err = p.ParseServerConfig(body)
if err != nil {
return fmt.Errorf("failed to parse server config: %v", err)
}
return nil
}
func (p *IdentityProvider) FetchJwk(url string) error {
//
if url == "" {
url = p.Endpoints.Jwks
}
// fetch JWKS from identity provider
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
set, err := jwk.Fetch(ctx, url)