Skip to content

Commit

Permalink
MatchAlg helper
Browse files Browse the repository at this point in the history
  • Loading branch information
dvsekhvalnov committed Dec 5, 2023
1 parent cf0a53b commit 0f6c7c3
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
11 changes: 11 additions & 0 deletions jose.go
Original file line number Diff line number Diff line change
Expand Up @@ -458,3 +458,14 @@ func retrieveActualKey(headers map[string]interface{}, payload string, key inter

return key, nil
}

func MatchAlg(expected string, key interface{}) func(headers map[string]interface{}, payload string) interface{} {
return func(headers map[string]interface{}, payload string) interface{} {
alg := headers["alg"].(string)
if expected == alg {
return key
}

return errors.New("Expected alg to be '" + expected + "' but got '" + alg + "'")
}
}
27 changes: 27 additions & 0 deletions jose_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2600,6 +2600,33 @@ func (s *TestSuite) TestDeregisterJwc(c *C) {
c.Assert(test, Equals, "")
}

func (s *TestSuite) TestDecode_TwoPhased_MatchAlg(c *C) {
//given
token := "eyJhbGciOiJFUzI1NiIsImN0eSI6InRleHRcL3BsYWluIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.EVnmDMlz-oi05AQzts-R3aqWvaBlwVZddWkmaaHyMx5Phb2NSLgyI0kccpgjjAyo1S5KCB3LIMPfmxCX_obMKA"

//when
test, _, err := Decode(token, MatchAlg("ES256", Ecc256Public()))

//then
c.Assert(err, IsNil)
c.Assert(test, Equals, `{"hello": "world"}`)
}

func (s *TestSuite) TestDecode_TwoPhased_MatchAlg_Invalid(c *C) {
//given
token := "eyJhbGciOiJFUzI1NiIsImN0eSI6InRleHRcL3BsYWluIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.EVnmDMlz-oi05AQzts-R3aqWvaBlwVZddWkmaaHyMx5Phb2NSLgyI0kccpgjjAyo1S5KCB3LIMPfmxCX_obMKA"

//when
test, headers, err := Decode(token, MatchAlg("RS256", Ecc256Public()))

fmt.Printf("\nalg doesn't match err=%v\n", err)

//then
c.Assert(headers, IsNil)
c.Assert(err, NotNil)
c.Assert(test, Equals, "")
}

// test utils
func PubKey() *rsa.PublicKey {
key, _ := Rsa.ReadPublic([]byte(pubKey))
Expand Down

0 comments on commit 0f6c7c3

Please sign in to comment.