Merge remote-tracking branch 'origin/token-introspection' into signingkey

# Conflicts:
#	pkg/op/mock/storage.mock.go
#	pkg/op/storage.go
This commit is contained in:
Livio Amstutz 2021-02-12 13:02:04 +01:00
commit 1049c44c3e
48 changed files with 1696 additions and 578 deletions

View file

@ -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)
}

View file

@ -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))

View file

@ -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 {

View 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
}

View file

@ -181,22 +181,22 @@ func (s *AuthStorage) GetClientByClientID(_ context.Context, id string) (op.Clie
return nil, errors.New("not found")
}
var appType op.ApplicationType
var authMethod op.AuthMethod
var authMethod oidc.AuthMethod
var accessTokenType op.AccessTokenType
var responseTypes []oidc.ResponseType
if id == "web" {
appType = op.ApplicationTypeWeb
authMethod = op.AuthMethodBasic
authMethod = oidc.AuthMethodBasic
accessTokenType = op.AccessTokenTypeBearer
responseTypes = []oidc.ResponseType{oidc.ResponseTypeCode}
} else if id == "native" {
appType = op.ApplicationTypeNative
authMethod = op.AuthMethodNone
authMethod = oidc.AuthMethodNone
accessTokenType = op.AccessTokenTypeBearer
responseTypes = []oidc.ResponseType{oidc.ResponseTypeCode}
} else {
appType = op.ApplicationTypeUserAgent
authMethod = op.AuthMethodNone
authMethod = oidc.AuthMethodNone
accessTokenType = op.AccessTokenTypeJWT
responseTypes = []oidc.ResponseType{oidc.ResponseTypeIDToken, oidc.ResponseTypeIDTokenOnly}
}
@ -207,26 +207,37 @@ func (s *AuthStorage) AuthorizeClientIDSecret(_ context.Context, id string, _ st
return nil
}
func (s *AuthStorage) GetUserinfoFromToken(ctx context.Context, _, _, _ string) (oidc.UserInfo, error) {
return s.GetUserinfoFromScopes(ctx, "", "", []string{})
func (s *AuthStorage) SetUserinfoFromToken(ctx context.Context, userinfo oidc.UserInfoSetter, _, _, _ string) error {
return s.SetUserinfoFromScopes(ctx, userinfo, "", "", []string{})
}
func (s *AuthStorage) GetUserinfoFromScopes(_ context.Context, _, _ string, _ []string) (oidc.UserInfo, error) {
userinfo := oidc.NewUserInfo()
func (s *AuthStorage) SetUserinfoFromScopes(ctx context.Context, userinfo oidc.UserInfoSetter, _, _ string, _ []string) error {
userinfo.SetSubject(a.GetSubject())
userinfo.SetAddress(oidc.NewUserInfoAddress("Test 789\nPostfach 2", "", "", "", "", ""))
userinfo.SetEmail("test", true)
userinfo.SetPhone("0791234567", true)
userinfo.SetName("Test")
userinfo.AppendClaims("private_claim", "test")
return userinfo, nil
return nil
}
func (s *AuthStorage) GetPrivateClaimsFromScopes(_ context.Context, _, _ string, _ []string) (map[string]interface{}, error) {
return map[string]interface{}{"private_claim": "test"}, nil
}
func (s *AuthStorage) SetIntrospectionFromToken(ctx context.Context, introspect oidc.IntrospectionResponse, tokenID, subject, clientID string) error {
if err := s.SetUserinfoFromScopes(ctx, introspect, "", "", []string{}); err != nil {
return err
}
introspect.SetClientID(a.ClientID)
return nil
}
func (s *AuthStorage) ValidateJWTProfileScopes(ctx context.Context, userID string, scope oidc.Scopes) (oidc.Scopes, error) {
return scope, nil
}
type ConfClient struct {
applicationType op.ApplicationType
authMethod op.AuthMethod
authMethod oidc.AuthMethod
responseTypes []oidc.ResponseType
ID string
accessTokenType op.AccessTokenType
@ -259,7 +270,7 @@ func (c *ConfClient) ApplicationType() op.ApplicationType {
return c.applicationType
}
func (c *ConfClient) AuthMethod() op.AuthMethod {
func (c *ConfClient) AuthMethod() oidc.AuthMethod {
return c.authMethod
}