Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
5bd00a4
feat: add ability to disable client authentication in token endpoint …
Nov 26, 2020
95798e7
feat(oauth2): add handler for authorize grant via jwt bearer
Nov 30, 2020
7e04502
fix(oauth2): mark jwt as used, if kid is provided in token
Dec 1, 2020
df5b6f1
refactor(oauth2): change err msg when no public key found for auth gr…
Dec 1, 2020
fd1ae59
feat(storage): add implementation of JWTAuthGrantStorage in MemoryStore
Dec 1, 2020
1509763
feat(compose): add support for AuthorizeJwtGrantHandler in compose
Dec 1, 2020
02992f7
fix(oauth2): fix incorrect message when validating assertion prerequi…
Dec 2, 2020
0e14733
fix(oauth2): fix nil pointer if all public keys didn't match in Autho…
Dec 2, 2020
18267a6
refactor(oauth2): change order of token validation in AuthorizeJwtGra…
Dec 3, 2020
b406a62
test: added unit tests for AuthorizeJwtGrantHandler
Dec 3, 2020
0d11ebd
fix(oauth2): fill session with subject, scopes, audience correctly in…
Dec 7, 2020
ca7f8a9
test: fix test assertion
Dec 9, 2020
f1a93b0
fix(oauth2): fix audience grant in AuthorizeJwtGrantHandler
Dec 9, 2020
9cba91b
feat(oauth2): add additional check for exp claim in AuthorizeJwtGrant…
Dec 9, 2020
665b957
cases for jwt bearer authorization grand creation
seliverstov-tinkoff Dec 3, 2020
db0aafa
draft introspection cases of jwt bearer
seliverstov-tinkoff Dec 4, 2020
db506b9
add clients for jwt bearer test
seliverstov-tinkoff Dec 8, 2020
38afdae
introspect token expired test
seliverstov-tinkoff Dec 9, 2020
a9de527
add constants for tests and few test on introspect token
seliverstov-tinkoff Dec 9, 2020
af01a48
use jose for jwt generation in tests
seliverstov-tinkoff Dec 10, 2020
7dea172
rename jwt bearer tests
seliverstov-tinkoff Dec 10, 2020
92bee79
introspection auth header store in suite
seliverstov-tinkoff Dec 11, 2020
ade7901
fix TestSuccessResponseWithMultipleScopesToken test
seliverstov-tinkoff Dec 11, 2020
6cf3d51
refactor: client authentification handling
Dec 16, 2020
27babf5
fix(oauth2): fix code style, naming and jwt token validation
Jan 19, 2021
418ddc3
fix(oauth2): mark jwt as used only after all checks
Jan 19, 2021
d7b294b
chore: apply code review
aeneasr Feb 5, 2021
5fa6839
refactor: move new changes to rfc7523
aeneasr Feb 5, 2021
98fb2d0
refactor: clean up package changes and renaming
aeneasr Feb 5, 2021
f6692bd
Merge remote-tracking branch 'origin/master' into auth-grant-type-jwt…
aeneasr Feb 5, 2021
3e50595
chore: merge
aeneasr Feb 5, 2021
306a0be
ci: run golangci/lint as job
aeneasr Feb 5, 2021
d5f202e
ci: run golangci/lint as job
aeneasr Feb 5, 2021
0ecc6c2
Merge branch 'master' into auth-grant-type-jwt-bearer
aeneasr Feb 5, 2021
7bbd667
u
aeneasr Feb 5, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ version: 2.1
orbs:
changelog: ory/changelog@0.1.4
nancy: ory/nancy@0.0.13
golangci: ory/golangci@0.0.9
golangci: ory/golangci@0.0.11

jobs:
test:
Expand Down
27 changes: 21 additions & 6 deletions access_request_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ import (
// client MUST authenticate with the authorization server as described
// in Section 3.2.1.
func (f *Fosite) NewAccessRequest(ctx context.Context, r *http.Request, session Session) (AccessRequester, error) {
var err error
accessRequest := NewAccessRequest(session)

if r.Method != "POST" {
Expand All @@ -80,18 +79,34 @@ func (f *Fosite) NewAccessRequest(ctx context.Context, r *http.Request, session
return accessRequest, errorsx.WithStack(ErrInvalidRequest.WithHint("Request parameter 'grant_type' is missing"))
}

client, err := f.AuthenticateClient(ctx, r, r.PostForm)
if err != nil {
return accessRequest, err
client, clientErr := f.AuthenticateClient(ctx, r, r.PostForm)
if clientErr == nil {
accessRequest.Client = client
}
accessRequest.Client = client

var found = false
for _, loader := range f.TokenEndpointHandlers {
// Is the loader responsible for handling the request?
if !loader.CanHandleTokenEndpointRequest(accessRequest) {
continue
}

// The handler **is** responsible!

// Is the client supplied in the request? If not can this handler skip client auth?
if !loader.CanSkipClientAuth(accessRequest) && clientErr != nil {
// No client and handler can not skip client auth -> error.
return accessRequest, clientErr
}

// All good.
if err := loader.HandleTokenEndpointRequest(ctx, accessRequest); err == nil {
found = true
} else if errors.Is(err, ErrUnknownRequest) {
// do nothing
// This is a duplicate because it should already have been handled by
// `loader.CanHandleTokenEndpointRequest(accessRequest)` but let's keep it for sanity.
//
continue
} else if err != nil {
return accessRequest, err
}
Expand Down
238 changes: 238 additions & 0 deletions access_request_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ func TestNewAccessRequest(t *testing.T) {
ctrl := gomock.NewController(t)
store := internal.NewMockStorage(ctrl)
handler := internal.NewMockTokenEndpointHandler(ctrl)
handler.EXPECT().CanHandleTokenEndpointRequest(gomock.Any()).Return(true).AnyTimes()
handler.EXPECT().CanSkipClientAuth(gomock.Any()).Return(false).AnyTimes()
hasher := internal.NewMockHasher(ctrl)
defer ctrl.Finish()

Expand Down Expand Up @@ -94,6 +96,7 @@ func TestNewAccessRequest(t *testing.T) {
mock: func() {
store.EXPECT().GetClient(gomock.Any(), gomock.Eq("foo")).Return(nil, errors.New(""))
},
handlers: TokenEndpointHandlers{handler},
},
{
header: http.Header{
Expand All @@ -118,6 +121,7 @@ func TestNewAccessRequest(t *testing.T) {
mock: func() {
store.EXPECT().GetClient(gomock.Any(), gomock.Eq("foo")).Return(nil, errors.New(""))
},
handlers: TokenEndpointHandlers{handler},
},
{
header: http.Header{
Expand All @@ -134,6 +138,7 @@ func TestNewAccessRequest(t *testing.T) {
client.Secret = []byte("foo")
hasher.EXPECT().Compare(context.TODO(), gomock.Eq([]byte("foo")), gomock.Eq([]byte("bar"))).Return(errors.New(""))
},
handlers: TokenEndpointHandlers{handler},
},
{
header: http.Header{
Expand Down Expand Up @@ -221,6 +226,239 @@ func TestNewAccessRequest(t *testing.T) {
}
}

func TestNewAccessRequestWithoutClientAuth(t *testing.T) {
ctrl := gomock.NewController(t)
store := internal.NewMockStorage(ctrl)
handler := internal.NewMockTokenEndpointHandler(ctrl)
handler.EXPECT().CanHandleTokenEndpointRequest(gomock.Any()).Return(true).AnyTimes()
handler.EXPECT().CanSkipClientAuth(gomock.Any()).Return(true).AnyTimes()
hasher := internal.NewMockHasher(ctrl)
defer ctrl.Finish()

client := &DefaultClient{}
anotherClient := &DefaultClient{ID: "another"}
fosite := &Fosite{Store: store, Hasher: hasher, AudienceMatchingStrategy: DefaultAudienceMatchingStrategy}
for k, c := range []struct {
header http.Header
form url.Values
mock func()
method string
expectErr error
expect *AccessRequest
handlers TokenEndpointHandlers
}{
// No grant type -> error
{
form: url.Values{},
mock: func() {
store.EXPECT().GetClient(gomock.Any(), gomock.Any()).Times(0)
},
method: "POST",
expectErr: ErrInvalidRequest,
},
// No registered handlers -> error
{
form: url.Values{
"grant_type": {"foo"},
},
mock: func() {
store.EXPECT().GetClient(gomock.Any(), gomock.Any()).Times(0)
},
method: "POST",
expectErr: ErrInvalidRequest,
handlers: TokenEndpointHandlers{},
},
// Handler can skip client auth and ignores missing client.
{
header: http.Header{
"Authorization": {basicAuth("foo", "bar")},
},
form: url.Values{
"grant_type": {"foo"},
},
mock: func() {
// despite error from storage, we should success, because client auth is not required
store.EXPECT().GetClient(gomock.Any(), "foo").Return(nil, errors.New("no client")).Times(1)
handler.EXPECT().HandleTokenEndpointRequest(gomock.Any(), gomock.Any()).Return(nil)
},
method: "POST",
expect: &AccessRequest{
GrantTypes: Arguments{"foo"},
Request: Request{
Client: client,
},
},
handlers: TokenEndpointHandlers{handler},
},
// Should pass if no auth is set in the header and can skip!
{
form: url.Values{
"grant_type": {"foo"},
},
mock: func() {
handler.EXPECT().HandleTokenEndpointRequest(gomock.Any(), gomock.Any()).Return(nil)
},
method: "POST",
expect: &AccessRequest{
GrantTypes: Arguments{"foo"},
Request: Request{
Client: client,
},
},
handlers: TokenEndpointHandlers{handler},
},
// Should also pass if client auth is set!
{
header: http.Header{
"Authorization": {basicAuth("foo", "bar")},
},
form: url.Values{
"grant_type": {"foo"},
},
mock: func() {
store.EXPECT().GetClient(gomock.Any(), "foo").Return(anotherClient, nil).Times(1)
hasher.EXPECT().Compare(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).Times(1)
handler.EXPECT().HandleTokenEndpointRequest(gomock.Any(), gomock.Any()).Return(nil)
},
method: "POST",
expect: &AccessRequest{
GrantTypes: Arguments{"foo"},
Request: Request{
Client: anotherClient,
},
},
handlers: TokenEndpointHandlers{handler},
},
} {
t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) {
r := &http.Request{
Header: c.header,
PostForm: c.form,
Form: c.form,
Method: c.method,
}
c.mock()
ctx := NewContext()
fosite.TokenEndpointHandlers = c.handlers
ar, err := fosite.NewAccessRequest(ctx, r, new(DefaultSession))

if c.expectErr != nil {
assert.EqualError(t, err, c.expectErr.Error())
} else {
require.NoError(t, err)
AssertObjectKeysEqual(t, c.expect, ar, "GrantTypes", "Client")
assert.NotNil(t, ar.GetRequestedAt())
}
})
}
}

// In this test case one handler requires client auth and another handler not.
func TestNewAccessRequestWithMixedClientAuth(t *testing.T) {
ctrl := gomock.NewController(t)
store := internal.NewMockStorage(ctrl)

handlerWithClientAuth := internal.NewMockTokenEndpointHandler(ctrl)
handlerWithClientAuth.EXPECT().CanHandleTokenEndpointRequest(gomock.Any()).Return(true).AnyTimes()
handlerWithClientAuth.EXPECT().CanSkipClientAuth(gomock.Any()).Return(false).AnyTimes()

handlerWithoutClientAuth := internal.NewMockTokenEndpointHandler(ctrl)
handlerWithoutClientAuth.EXPECT().CanHandleTokenEndpointRequest(gomock.Any()).Return(true).AnyTimes()
handlerWithoutClientAuth.EXPECT().CanSkipClientAuth(gomock.Any()).Return(true).AnyTimes()

hasher := internal.NewMockHasher(ctrl)
defer ctrl.Finish()

client := &DefaultClient{}
fosite := &Fosite{Store: store, Hasher: hasher, AudienceMatchingStrategy: DefaultAudienceMatchingStrategy}
for k, c := range []struct {
header http.Header
form url.Values
mock func()
method string
expectErr error
expect *AccessRequest
handlers TokenEndpointHandlers
}{
{
header: http.Header{
"Authorization": {basicAuth("foo", "bar")},
},
form: url.Values{
"grant_type": {"foo"},
},
mock: func() {
store.EXPECT().GetClient(gomock.Any(), gomock.Eq("foo")).Return(client, nil)
client.Public = false
client.Secret = []byte("foo")
hasher.EXPECT().Compare(context.TODO(), gomock.Eq([]byte("foo")), gomock.Eq([]byte("bar"))).Return(errors.New("hash err"))
handlerWithoutClientAuth.EXPECT().HandleTokenEndpointRequest(gomock.Any(), gomock.Any()).Return(nil)
},
method: "POST",
expectErr: ErrInvalidClient,
handlers: TokenEndpointHandlers{handlerWithoutClientAuth, handlerWithClientAuth},
},
{
header: http.Header{
"Authorization": {basicAuth("foo", "bar")},
},
form: url.Values{
"grant_type": {"foo"},
},
mock: func() {
store.EXPECT().GetClient(gomock.Any(), gomock.Eq("foo")).Return(client, nil)
client.Public = false
client.Secret = []byte("foo")
hasher.EXPECT().Compare(context.TODO(), gomock.Eq([]byte("foo")), gomock.Eq([]byte("bar"))).Return(nil)
handlerWithoutClientAuth.EXPECT().HandleTokenEndpointRequest(gomock.Any(), gomock.Any()).Return(nil)
handlerWithClientAuth.EXPECT().HandleTokenEndpointRequest(gomock.Any(), gomock.Any()).Return(nil)
},
method: "POST",
expect: &AccessRequest{
GrantTypes: Arguments{"foo"},
Request: Request{
Client: client,
},
},
handlers: TokenEndpointHandlers{handlerWithoutClientAuth, handlerWithClientAuth},
},
{
header: http.Header{},
form: url.Values{
"grant_type": {"foo"},
},
mock: func() {
store.EXPECT().GetClient(gomock.Any(), gomock.Any()).Times(0)
handlerWithoutClientAuth.EXPECT().HandleTokenEndpointRequest(gomock.Any(), gomock.Any()).Return(nil)
},
method: "POST",
expectErr: ErrInvalidRequest,
handlers: TokenEndpointHandlers{handlerWithoutClientAuth, handlerWithClientAuth},
},
} {
t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) {
r := &http.Request{
Header: c.header,
PostForm: c.form,
Form: c.form,
Method: c.method,
}
c.mock()
ctx := NewContext()
fosite.TokenEndpointHandlers = c.handlers
ar, err := fosite.NewAccessRequest(ctx, r, new(DefaultSession))

if c.expectErr != nil {
assert.EqualError(t, err, c.expectErr.Error())
} else {
require.NoError(t, err)
AssertObjectKeysEqual(t, c.expect, ar, "GrantTypes", "Client")
assert.NotNil(t, ar.GetRequestedAt())
}
})
}
}

func basicAuth(username, password string) string {
return "Basic " + base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password)))
}
1 change: 1 addition & 0 deletions compose/compose.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ func ComposeAllEnabled(config *Config, storage interface{}, secret []byte, key *
OAuth2ClientCredentialsGrantFactory,
OAuth2RefreshTokenGrantFactory,
OAuth2ResourceOwnerPasswordCredentialsFactory,
RFC7523AssertionGrantFactory,

OpenIDConnectExplicitFactory,
OpenIDConnectImplicitFactory,
Expand Down
26 changes: 26 additions & 0 deletions compose/compose_rfc7523.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package compose

import (
"github.com/ory/fosite/handler/oauth2"
"github.com/ory/fosite/handler/rfc7523"
)

// RFC7523AssertionGrantFactory creates an OAuth2 Authorize JWT Grant (using JWTs as Authorization Grants) handler
// and registers an access token, refresh token and authorize code validator.
func RFC7523AssertionGrantFactory(config *Config, storage interface{}, strategy interface{}) interface{} {
return &rfc7523.Handler{
Storage: storage.(rfc7523.RFC7523KeyStorage),
ScopeStrategy: config.GetScopeStrategy(),
AudienceMatchingStrategy: config.GetAudienceStrategy(),
TokenURL: config.TokenURL,
SkipClientAuth: config.GrantTypeJWTBearerCanSkipClientAuth,
JWTIDOptional: config.GrantTypeJWTBearerIDOptional,
JWTIssuedDateOptional: config.GrantTypeJWTBearerIssuedDateOptional,
JWTMaxDuration: config.GetJWTMaxDuration(),
HandleHelper: &oauth2.HandleHelper{
AccessTokenStrategy: strategy.(oauth2.AccessTokenStrategy),
AccessTokenStorage: storage.(oauth2.AccessTokenStorage),
AccessTokenLifespan: config.GetAccessTokenLifespan(),
},
}
}
23 changes: 23 additions & 0 deletions compose/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,18 @@ type Config struct {
// UseLegacyErrorFormat controls whether the legacy error format (with `error_debug`, `error_hint`, ...)
// should be used or not.
UseLegacyErrorFormat bool

// GrantTypeJWTBearerCanSkipClientAuth indicates, if client authentication can be skipped, when using jwt as assertion.
GrantTypeJWTBearerCanSkipClientAuth bool

// GrantTypeJWTBearerIDOptional indicates, if jti (JWT ID) claim required or not in JWT.
GrantTypeJWTBearerIDOptional bool

// GrantTypeJWTBearerIssuedDateOptional indicates, if "iat" (issued at) claim required or not in JWT.
GrantTypeJWTBearerIssuedDateOptional bool

// GrantTypeJWTBearerMaxDuration sets the maximum time after JWT issued date, during which the JWT is considered valid.
GrantTypeJWTBearerMaxDuration time.Duration
}

// GetScopeStrategy returns the scope strategy to be used. Defaults to glob scope strategy.
Expand Down Expand Up @@ -198,3 +210,14 @@ func (c *Config) GetMinParameterEntropy() int {
return c.MinParameterEntropy
}
}

// GetJWTMaxDuration specified the maximum amount of allowed `exp` time for a JWT. It compares
// the time with the JWT's `exp` time if the JWT time is larger, will cause the JWT to be invalid.
//
// Defaults to a day.
func (c *Config) GetJWTMaxDuration() time.Duration {
if c.GrantTypeJWTBearerMaxDuration == 0 {
return time.Hour * 24
}
return c.GrantTypeJWTBearerMaxDuration
}
Loading