Skip to content

Commit

Permalink
Enhance token introspection with detailed validation
Browse files Browse the repository at this point in the history
Added and refined tests for the introspection method to cover scenarios for active and inactive tokens, improving test coverage and reliability. Updated the introspection logic to ensure more precise extraction and validation of token information, addressing potential issues with JWT decoding and token expiration handling. The changes offer a more robust introspection process by aligning token payload parsing with expected structures.
  • Loading branch information
eliasjpr committed Oct 6, 2024
1 parent c35c1a0 commit ba64688
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 12 deletions.
29 changes: 29 additions & 0 deletions spec/authly_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,35 @@ describe Authly do
end
end

describe ".introspect" do
it "returns active token" do
a_token = Authly::AccessToken.new(client_id, scope)
expected_token = Authly.jwt_decode(a_token.access_token).first
token = Authly.introspect(a_token.access_token)

token.should eq({
active: true,
scope: scope,
cid: client_id,
exp: a_token.expires_in,
sub: expected_token["sub"],
})
end

it "returns inactive token" do
token = Authly.introspect("invalid_token")

token.should eq({active: false})
end

it "returns inactive token" do
a_token = Authly::AccessToken.new(client_id, scope)
token = Authly.introspect(a_token.to_s + "invalid")

token.should eq({active: false})
end
end

describe ".code" do
it "returns an temporary code" do
code = Authly.code("code", client_id, redirect_uri, scope)
Expand Down
21 changes: 9 additions & 12 deletions src/authly.cr
Original file line number Diff line number Diff line change
Expand Up @@ -41,25 +41,22 @@ module Authly

def self.introspect(token : String)
# Decode the JWT, verify the signature and expiration
payload, header = JWT.decode(token, SECRET, algorithm: "HS256")
payload, _header = jwt_decode(token)

# Check if the token is expired (exp claim is typically in seconds since epoch)
exp = payload["exp"].to_i
if Time.now.to_unix > exp
return { active: false, exp: exp }
if Time.local.to_unix > payload["exp"].to_s.to_i
return {active: false, exp: payload["exp"]}
end

# Return the token metadata
# Return authly access token
{
active: true,
scope: payload["scope"],
client_id: payload["client_id"],
username: payload["sub"], # 'sub' is commonly used for the user identifier in JWTs
exp: exp
scope: payload["scope"],
cid: payload["cid"],
exp: payload["exp"],
sub: payload["sub"],
}
rescue JWT::DecodeError
return {
active: false
}
{active: false}
end
end

0 comments on commit ba64688

Please sign in to comment.