-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
sdk: add consent helper - closes #397 #398
Merged
Changes from 3 commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -43,8 +43,6 @@ func ToError(err error) *Error { | |
} | ||
} | ||
|
||
|
||
|
||
return &Error{ | ||
OriginalError: err, | ||
Name: "internal-error", | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
package sdk | ||
|
||
import ( | ||
"crypto/rsa" | ||
"fmt" | ||
"github.com/dgrijalva/jwt-go" | ||
ejwt "github.com/ory-am/fosite/token/jwt" | ||
"github.com/ory-am/hydra/jwk" | ||
"github.com/ory-am/hydra/oauth2" | ||
"github.com/pkg/errors" | ||
"time" | ||
) | ||
|
||
// Consent is a helper for singing and verifying consent challenges. For an exemplary reference implementation, check | ||
// https://github.com/ory/hydra-consent-app-go | ||
type Consent struct { | ||
KeyManager jwk.Manager | ||
} | ||
|
||
// ResponseRequest is being used by the consent response singing helper. | ||
type ResponseRequest struct { | ||
// Challenge is the original consent challenge. | ||
Challenge string | ||
|
||
// Subject will be the sub claim of the access token. Usually this is a resource owner (user). | ||
Subject string | ||
|
||
// Scopes are the scopes the resource owner granted to the application requesting the access token. | ||
Scopes []string | ||
|
||
// AccessTokenExtra is arbitrary data that will be available when performing token introspection or warden requests. | ||
AccessTokenExtra interface{} | ||
|
||
// IDTokenExtra is arbitrary data that will included as a claim in the ID Token, if requested. | ||
IDTokenExtra interface{} | ||
} | ||
|
||
// ChallengeClaims are the decoded claims of a consent challenge. | ||
type ChallengeClaims struct { | ||
// RequestedScopes are the scopes the application requested. Each scope should be explicitly granted by | ||
// the user. | ||
RequestedScopes []string `json:"scp"` | ||
|
||
// The ID of the application that initiated the OAuth2 flow. | ||
Audience string `json:"aud"` | ||
|
||
// RedirectURL is the url where the consent app will send the user after the consent flow has been completed. | ||
RedirectURL string `json:"redir"` | ||
|
||
// ExpiresAt is a unix timestamp of the expiry time. | ||
ExpiresAt float64 `json:"exp"` | ||
|
||
// ID is the tokens' ID which will be automatically echoed in the consent response. | ||
ID string `json:"jti"` | ||
} | ||
|
||
// Valid tests if the challenge's claims are valid. | ||
func (c *ChallengeClaims) Valid() error { | ||
if time.Now().After(ejwt.ToTime(c.ExpiresAt)) { | ||
return errors.Errorf("Consent challenge expired") | ||
} | ||
return nil | ||
} | ||
|
||
// VerifyChallenge verifies a consent challenge and either returns the challenge's claims if it is valid, or an | ||
// error if it is not. | ||
func (c *Consent) VerifyChallenge(challenge string) (*ChallengeClaims, error) { | ||
var claims ChallengeClaims | ||
t, err := jwt.ParseWithClaims(challenge, &claims, func(t *jwt.Token) (interface{}, error) { | ||
if _, ok := t.Method.(*jwt.SigningMethodRSA); !ok { | ||
return nil, errors.Errorf("Unexpected signing method: %v", t.Header["alg"]) | ||
} | ||
|
||
pk, err := c.KeyManager.GetKey(oauth2.ConsentChallengeKey, "public") | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
rsaKey, ok := jwk.First(pk.Keys).Key.(*rsa.PublicKey) | ||
if !ok { | ||
return nil, errors.New("Could not convert to RSA Private Key") | ||
} | ||
return rsaKey, nil | ||
}) | ||
if err != nil { | ||
return nil, errors.Wrap(err, "The consent chalnge is not a valid JSON Web Token") | ||
} | ||
|
||
if !t.Valid { | ||
return nil, errors.Errorf("Consent challenge is invalid") | ||
} else if err := claims.Valid(); err != nil { | ||
return nil, errors.Wrap(err, "The consent challenge claims could not be verified") | ||
} | ||
|
||
return &claims, err | ||
} | ||
|
||
// GenerateResponse generates a consent response and returns the consent response token, or an error if it is invalid. | ||
func (c *Consent) GenerateResponse(r *ResponseRequest) (string, error) { | ||
challenge, err := c.VerifyChallenge(r.Challenge) | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
token := jwt.New(jwt.SigningMethodRS256) | ||
token.Claims = jwt.MapClaims{ | ||
"jti": challenge.ID, | ||
"scp": r.Scopes, | ||
"aud": challenge.Audience, | ||
"exp": challenge.ExpiresAt, | ||
"sub": r.Subject, | ||
"at_ext": r.AccessTokenExtra, | ||
"id_ext": r.IDTokenExtra, | ||
} | ||
|
||
ks, err := c.KeyManager.GetKey(oauth2.ConsentEndpointKey, "private") | ||
if err != nil { | ||
return "", errors.WithStack(err) | ||
} | ||
|
||
rsaKey, ok := jwk.First(ks.Keys).Key.(*rsa.PrivateKey) | ||
if !ok { | ||
return "", errors.New("Could not convert to RSA Private Key") | ||
} | ||
|
||
var signature, encoded string | ||
if encoded, err = token.SigningString(); err != nil { | ||
return "", errors.WithStack(err) | ||
} else if signature, err = token.Method.Sign(encoded, rsaKey); err != nil { | ||
return "", errors.WithStack(err) | ||
} | ||
|
||
return fmt.Sprintf("%s.%s", encoded, signature), nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
package sdk | ||
|
||
import ( | ||
"encoding/base64" | ||
"encoding/json" | ||
"github.com/gorilla/sessions" | ||
"github.com/ory-am/fosite" | ||
"github.com/ory-am/hydra/jwk" | ||
"github.com/ory-am/hydra/oauth2" | ||
"github.com/square/go-jose" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
"strings" | ||
"testing" | ||
"time" | ||
) | ||
|
||
func genKey() *jose.JsonWebKeySet { | ||
g := &jwk.RS256Generator{} | ||
k, _ := g.Generate("") | ||
return k | ||
} | ||
|
||
func TestConsentHelper(t *testing.T) { | ||
km := &jwk.MemoryManager{Keys: map[string]*jose.JsonWebKeySet{}} | ||
km.AddKeySet(oauth2.ConsentChallengeKey, genKey()) | ||
km.AddKeySet(oauth2.ConsentEndpointKey, genKey()) | ||
|
||
_, err := km.GetKey(oauth2.ConsentChallengeKey, "private") | ||
require.Nil(t, err) | ||
c := Consent{KeyManager: km} | ||
s := oauth2.DefaultConsentStrategy{ | ||
KeyManager: km, | ||
DefaultChallengeLifespan: time.Hour, | ||
} | ||
|
||
ar := fosite.NewAuthorizeRequest() | ||
ar.Client = &fosite.DefaultClient{ID: "foobarclient"} | ||
challenge, err := s.IssueChallenge(ar, "/lightyear", &sessions.Session{Values: map[interface{}]interface{}{}}) | ||
require.Nil(t, err) | ||
|
||
claims, err := c.VerifyChallenge(challenge) | ||
require.Nil(t, err) | ||
assert.Equal(t, claims.Audience, "foobarclient") | ||
assert.Equal(t, claims.RedirectURL, "/lightyear") | ||
assert.NotEmpty(t, claims.ID) | ||
|
||
resp, err := c.GenerateResponse(&ResponseRequest{ | ||
Challenge: challenge, | ||
Subject: "buzz", | ||
Scopes: []string{"offline", "openid"}, | ||
}) | ||
require.Nil(t, err) | ||
|
||
var dec map[string]interface{} | ||
result, err := base64.RawURLEncoding.DecodeString(strings.Split(resp, ".")[1]) | ||
require.Nil(t, err) | ||
|
||
require.Nil(t, json.Unmarshal(result, &dec)) | ||
assert.Equal(t, dec["jti"], claims.ID) | ||
t.Logf("%v", dec["jti"]) | ||
assert.Equal(t, dec["scp"].([]interface{}), []interface{}{"offline", "openid"}) | ||
assert.Equal(t, dec["sub"], "buzz") | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of returning the consent response token here, we could probably return the URL instead. The former requires us to do something like this:
while the latter would allow for an easier flow:
To deny consent, the idea is to have:
Currently this would be possible with: