feat: token introspection (#83)
* introspect * introspect and client assertion * introspect and client assertion * scopes * token introspection * introspect * refactoring * fixes * clenaup * Update example/internal/mock/storage.go Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com> * clenaup Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com>
This commit is contained in:
parent
fa92a20615
commit
1518c843de
46 changed files with 1672 additions and 570 deletions
|
@ -1,90 +1,103 @@
|
|||
package main
|
||||
|
||||
// import (
|
||||
// "encoding/json"
|
||||
// "fmt"
|
||||
// "log"
|
||||
// "net/http"
|
||||
// "os"
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
// "github.com/caos/oidc/pkg/oidc"
|
||||
// "github.com/caos/oidc/pkg/oidc/rp"
|
||||
// "github.com/caos/utils/logging"
|
||||
// )
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
// const (
|
||||
// publicURL string = "/public"
|
||||
// protectedURL string = "/protected"
|
||||
// protectedExchangeURL string = "/protected/exchange"
|
||||
// )
|
||||
"github.com/caos/oidc/pkg/client/rs"
|
||||
"github.com/caos/oidc/pkg/oidc"
|
||||
)
|
||||
|
||||
const (
|
||||
publicURL string = "/public"
|
||||
protectedURL string = "/protected"
|
||||
protectedClaimURL string = "/protected/{claim}/{value}"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// clientID := os.Getenv("CLIENT_ID")
|
||||
// clientSecret := os.Getenv("CLIENT_SECRET")
|
||||
// issuer := os.Getenv("ISSUER")
|
||||
// port := os.Getenv("PORT")
|
||||
keyPath := os.Getenv("KEY")
|
||||
port := os.Getenv("PORT")
|
||||
issuer := os.Getenv("ISSUER")
|
||||
|
||||
// // ctx := context.Background()
|
||||
provider, err := rs.NewResourceServerFromKeyFile(issuer, keyPath)
|
||||
if err != nil {
|
||||
logrus.Fatalf("error creating provider %s", err.Error())
|
||||
}
|
||||
|
||||
// providerConfig := &oidc.ProviderConfig{
|
||||
// ClientID: clientID,
|
||||
// ClientSecret: clientSecret,
|
||||
// Issuer: issuer,
|
||||
// }
|
||||
// provider, err := rp.NewDefaultProvider(providerConfig)
|
||||
// logging.Log("APP-nx6PeF").OnError(err).Panic("error creating provider")
|
||||
router := mux.NewRouter()
|
||||
|
||||
// http.HandleFunc(publicURL, func(w http.ResponseWriter, r *http.Request) {
|
||||
// w.Write([]byte("OK"))
|
||||
// })
|
||||
//public url accessible without any authorization
|
||||
//will print `OK` and current timestamp
|
||||
router.HandleFunc(publicURL, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("OK " + time.Now().String()))
|
||||
})
|
||||
|
||||
// http.HandleFunc(protectedURL, func(w http.ResponseWriter, r *http.Request) {
|
||||
// ok, token := checkToken(w, r)
|
||||
// if !ok {
|
||||
// return
|
||||
// }
|
||||
// resp, err := provider.Introspect(r.Context(), token)
|
||||
// if err != nil {
|
||||
// http.Error(w, err.Error(), http.StatusForbidden)
|
||||
// return
|
||||
// }
|
||||
// data, err := json.Marshal(resp)
|
||||
// if err != nil {
|
||||
// http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
// return
|
||||
// }
|
||||
// w.Write(data)
|
||||
// })
|
||||
//protected url which needs an active token
|
||||
//will print the result of the introspection endpoint on success
|
||||
router.HandleFunc(protectedURL, func(w http.ResponseWriter, r *http.Request) {
|
||||
ok, token := checkToken(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
resp, err := rs.Introspect(r.Context(), provider, token)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
data, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
})
|
||||
|
||||
// http.HandleFunc(protectedExchangeURL, func(w http.ResponseWriter, r *http.Request) {
|
||||
// ok, token := checkToken(w, r)
|
||||
// if !ok {
|
||||
// return
|
||||
// }
|
||||
// tokens, err := provider.DelegationTokenExchange(r.Context(), token, oidc.WithResource([]string{"Test"}))
|
||||
// if err != nil {
|
||||
// http.Error(w, "failed to exchange token: "+err.Error(), http.StatusUnauthorized)
|
||||
// return
|
||||
// }
|
||||
//protected url which needs an active token and checks if the response of the introspect endpoint
|
||||
//contains a requested claim with the required (string) value
|
||||
//e.g. /protected/username/livio@caos.ch
|
||||
router.HandleFunc(protectedClaimURL, func(w http.ResponseWriter, r *http.Request) {
|
||||
ok, token := checkToken(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
resp, err := rs.Introspect(r.Context(), provider, token)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
params := mux.Vars(r)
|
||||
requestedClaim := params["claim"]
|
||||
requestedValue := params["value"]
|
||||
value, ok := resp.GetClaim(requestedClaim).(string)
|
||||
if !ok || value == "" || value != requestedValue {
|
||||
http.Error(w, "claim does not match", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
w.Write([]byte("authorized with value " + value))
|
||||
})
|
||||
|
||||
// data, err := json.Marshal(tokens)
|
||||
// if err != nil {
|
||||
// http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
// return
|
||||
// }
|
||||
// w.Write(data)
|
||||
// })
|
||||
|
||||
// lis := fmt.Sprintf("127.0.0.1:%s", port)
|
||||
// log.Printf("listening on http://%s/", lis)
|
||||
// log.Fatal(http.ListenAndServe(lis, nil))
|
||||
// }
|
||||
|
||||
// func checkToken(w http.ResponseWriter, r *http.Request) (bool, string) {
|
||||
// token := r.Header.Get("authorization")
|
||||
// if token == "" {
|
||||
// http.Error(w, "Auth header missing", http.StatusUnauthorized)
|
||||
// return false, ""
|
||||
// }
|
||||
// return true, token
|
||||
lis := fmt.Sprintf("127.0.0.1:%s", port)
|
||||
log.Printf("listening on http://%s/", lis)
|
||||
log.Fatal(http.ListenAndServe(lis, router))
|
||||
}
|
||||
|
||||
func checkToken(w http.ResponseWriter, r *http.Request) (bool, string) {
|
||||
auth := r.Header.Get("authorization")
|
||||
if auth == "" {
|
||||
http.Error(w, "auth header missing", http.StatusUnauthorized)
|
||||
return false, ""
|
||||
}
|
||||
if !strings.HasPrefix(auth, oidc.PrefixBearer) {
|
||||
http.Error(w, "invalid header", http.StatusUnauthorized)
|
||||
return false, ""
|
||||
}
|
||||
return true, strings.TrimPrefix(auth, oidc.PrefixBearer)
|
||||
}
|
||||
|
|
|
@ -1,11 +1,8 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
@ -14,8 +11,8 @@ import (
|
|||
"github.com/google/uuid"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/caos/oidc/pkg/client/rp"
|
||||
"github.com/caos/oidc/pkg/oidc"
|
||||
"github.com/caos/oidc/pkg/rp"
|
||||
"github.com/caos/oidc/pkg/utils"
|
||||
)
|
||||
|
||||
|
@ -27,18 +24,26 @@ var (
|
|||
func main() {
|
||||
clientID := os.Getenv("CLIENT_ID")
|
||||
clientSecret := os.Getenv("CLIENT_SECRET")
|
||||
keyPath := os.Getenv("KEY_PATH")
|
||||
issuer := os.Getenv("ISSUER")
|
||||
port := os.Getenv("PORT")
|
||||
scopes := strings.Split(os.Getenv("SCOPES"), " ")
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
redirectURI := fmt.Sprintf("http://localhost:%v%v", port, callbackPath)
|
||||
cookieHandler := utils.NewCookieHandler(key, key, utils.WithUnsecure())
|
||||
provider, err := rp.NewRelayingPartyOIDC(issuer, clientID, clientSecret, redirectURI, scopes,
|
||||
rp.WithPKCE(cookieHandler),
|
||||
rp.WithVerifierOpts(rp.WithIssuedAtOffset(5*time.Second)),
|
||||
)
|
||||
|
||||
options := []rp.Option{
|
||||
rp.WithCookieHandler(cookieHandler),
|
||||
rp.WithVerifierOpts(rp.WithIssuedAtOffset(5 * time.Second)),
|
||||
}
|
||||
if clientSecret == "" {
|
||||
options = append(options, rp.WithPKCE(cookieHandler))
|
||||
}
|
||||
if keyPath != "" {
|
||||
options = append(options, rp.WithClientKey(keyPath))
|
||||
}
|
||||
|
||||
provider, err := rp.NewRelyingPartyOIDC(issuer, clientID, clientSecret, redirectURI, scopes, options...)
|
||||
if err != nil {
|
||||
logrus.Fatalf("error creating provider %s", err.Error())
|
||||
}
|
||||
|
@ -71,80 +76,6 @@ func main() {
|
|||
//with the returned tokens from the token endpoint
|
||||
http.Handle(callbackPath, rp.CodeExchangeHandler(marshal, provider))
|
||||
|
||||
http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
|
||||
tokens, err := rp.ClientCredentials(ctx, provider, "scope")
|
||||
if err != nil {
|
||||
http.Error(w, "failed to exchange token: "+err.Error(), http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := json.Marshal(tokens)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
})
|
||||
|
||||
http.HandleFunc("/jwt-profile", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == "GET" {
|
||||
tpl := `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Login</title>
|
||||
</head>
|
||||
<body>
|
||||
<form method="POST" action="/jwt-profile" enctype="multipart/form-data">
|
||||
<label for="key">Select a key file:</label>
|
||||
<input type="file" accept=".json" id="key" name="key">
|
||||
<button type="submit">Get Token</button>
|
||||
</form>
|
||||
</body>
|
||||
</html>`
|
||||
t, err := template.New("login").Parse(tpl)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
err = t.Execute(w, nil)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
} else {
|
||||
err := r.ParseMultipartForm(4 << 10)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
file, handler, err := r.FormFile("key")
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
key, err := ioutil.ReadAll(file)
|
||||
fmt.Println(handler.Header)
|
||||
assertion, err := oidc.NewJWTProfileAssertionFromFileData(key, []string{issuer})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
token, err := rp.JWTProfileAssertionExchange(ctx, assertion, scopes, provider)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
data, err := json.Marshal(token)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}
|
||||
})
|
||||
lis := fmt.Sprintf("127.0.0.1:%s", port)
|
||||
logrus.Infof("listening on http://%s/", lis)
|
||||
logrus.Fatal(http.ListenAndServe("127.0.0.1:"+port, nil))
|
||||
|
|
|
@ -10,8 +10,8 @@ import (
|
|||
"golang.org/x/oauth2"
|
||||
githubOAuth "golang.org/x/oauth2/github"
|
||||
|
||||
"github.com/caos/oidc/pkg/rp"
|
||||
"github.com/caos/oidc/pkg/rp/cli"
|
||||
"github.com/caos/oidc/pkg/client/rp"
|
||||
"github.com/caos/oidc/pkg/client/rp/cli"
|
||||
"github.com/caos/oidc/pkg/utils"
|
||||
)
|
||||
|
||||
|
@ -35,7 +35,7 @@ func main() {
|
|||
|
||||
ctx := context.Background()
|
||||
cookieHandler := utils.NewCookieHandler(key, key, utils.WithUnsecure())
|
||||
relayingParty, err := rp.NewRelayingPartyOAuth(rpConfig, rp.WithCookieHandler(cookieHandler))
|
||||
relyingParty, err := rp.NewRelyingPartyOAuth(rpConfig, rp.WithCookieHandler(cookieHandler))
|
||||
if err != nil {
|
||||
fmt.Printf("error creating relaying party: %v", err)
|
||||
return
|
||||
|
@ -43,9 +43,9 @@ func main() {
|
|||
state := func() string {
|
||||
return uuid.New().String()
|
||||
}
|
||||
token := cli.CodeFlow(relayingParty, callbackPath, port, state)
|
||||
token := cli.CodeFlow(relyingParty, callbackPath, port, state)
|
||||
|
||||
client := github.NewClient(relayingParty.OAuthConfig().Client(ctx, token.Token))
|
||||
client := github.NewClient(relyingParty.OAuthConfig().Client(ctx, token.Token))
|
||||
|
||||
_, _, err = client.Users.Get(ctx, "")
|
||||
if err != nil {
|
||||
|
|
180
example/client/service/service.go
Normal file
180
example/client/service/service.go
Normal file
|
@ -0,0 +1,180 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"github.com/caos/oidc/pkg/client/profile"
|
||||
)
|
||||
|
||||
var (
|
||||
client *http.Client = http.DefaultClient
|
||||
)
|
||||
|
||||
func main() {
|
||||
keyPath := os.Getenv("KEY_PATH")
|
||||
issuer := os.Getenv("ISSUER")
|
||||
port := os.Getenv("PORT")
|
||||
scopes := strings.Split(os.Getenv("SCOPES"), " ")
|
||||
|
||||
if keyPath != "" {
|
||||
ts, err := profile.NewJWTProfileTokenSourceFromKeyFile(issuer, keyPath, scopes)
|
||||
if err != nil {
|
||||
logrus.Fatalf("error creating token source %s", err.Error())
|
||||
}
|
||||
client = oauth2.NewClient(context.Background(), ts)
|
||||
}
|
||||
|
||||
http.HandleFunc("/jwt-profile", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == "GET" {
|
||||
tpl := `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Login</title>
|
||||
</head>
|
||||
<body>
|
||||
<form method="POST" action="/jwt-profile" enctype="multipart/form-data">
|
||||
<label for="key">Select a key file:</label>
|
||||
<input type="file" accept=".json" id="key" name="key">
|
||||
<button type="submit">Get Token</button>
|
||||
</form>
|
||||
</body>
|
||||
</html>`
|
||||
t, err := template.New("login").Parse(tpl)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
err = t.Execute(w, nil)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
} else {
|
||||
err := r.ParseMultipartForm(4 << 10)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
file, _, err := r.FormFile("key")
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
key, err := ioutil.ReadAll(file)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
ts, err := profile.NewJWTProfileTokenSourceFromKeyFileData(issuer, key, scopes)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
client = oauth2.NewClient(context.Background(), ts)
|
||||
token, err := ts.Token()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
data, err := json.Marshal(token)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}
|
||||
})
|
||||
|
||||
http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
|
||||
tpl := `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Test</title>
|
||||
</head>
|
||||
<body>
|
||||
<form method="POST" action="/test">
|
||||
<label for="url">URL for test:</label>
|
||||
<input type="text" id="url" name="url" width="200px">
|
||||
<button type="submit">Test Token</button>
|
||||
</form>
|
||||
{{if .URL}}
|
||||
<p>
|
||||
Result for {{.URL}}: {{.Response}}
|
||||
</p>
|
||||
{{end}}
|
||||
</body>
|
||||
</html>`
|
||||
err := r.ParseForm()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
testURL := r.Form.Get("url")
|
||||
var data struct {
|
||||
URL string
|
||||
Response interface{}
|
||||
}
|
||||
if testURL != "" {
|
||||
data.URL = testURL
|
||||
data.Response, err = callExampleEndpoint(client, testURL)
|
||||
if err != nil {
|
||||
data.Response = err
|
||||
}
|
||||
}
|
||||
t, err := template.New("login").Parse(tpl)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
err = t.Execute(w, data)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
})
|
||||
lis := fmt.Sprintf("127.0.0.1:%s", port)
|
||||
logrus.Infof("listening on http://%s/", lis)
|
||||
logrus.Fatal(http.ListenAndServe("127.0.0.1:"+port, nil))
|
||||
}
|
||||
|
||||
func callExampleEndpoint(client *http.Client, testURL string) (interface{}, error) {
|
||||
req, err := http.NewRequest("GET", testURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("http status not ok: %s %s", resp.Status, body)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(resp.Header.Get("content-type"), "text/plain") {
|
||||
return string(body), nil
|
||||
}
|
||||
return body, err
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue