跳到正文
DEV Community· Raylabs·· 3 小時前AI 評分49

OAuth 中繼資料探索與 JWT 驗證

Validating OAuth Metadata and JWTs

AI 導讀

OAuth 中繼資料探索不能代替 JWT 信任驗證;服務須在執行時嚴格核對 issuer、audience 及允許的簽署演算法。RFC 8414 和 RFC 9728 分別定義授權伺服器及受保護資源的中繼資料探索,兩者均不會驗證傳入的 token。有效簽署不代表 token 的 audience 符合接收服務,受眾不符時必須拒絕。

正文

Engineers frequently confuse fetching configuration endpoints with verifying cryptographic credentials, assuming that locating a server means its tokens are automatically safe to accept. When an application accepts a digitally signed JSON Web Token without validating its runtime claims against the actual protocol environment, it opens the system up to cross-context impersonation and unauthorized data access.

Quick solution:

Implement strict runtime checks for issuer, audience, and algorithm alongside metadata discovery, as shown in this minimal Node.js verification snippet using explicit claim validation.

const jwt = require('jsonwebtoken');

function verifyToken(token, expectedIssuer, expectedAudience, jwksUri) {
  // Prerequisite: Never rely solely on discovery metadata for trust
  const options = {
    issuer: expectedIssuer,
    audience: expectedAudience,
    algorithms: ['RS256']
  };

  try {
    const decoded = jwt.verify(token, getKey, options);
    return { valid: true, claims: decoded };
  } catch (err) {
    return { valid: false, error: err.message };
  }
}

What do RFC 9728 and RFC 8414 each discover?

Configuration discovery separates client configuration from hardcoded URLs. As outlined in RFC 8414, authorization servers publish metadata documents containing endpoints, supported scopes, and public signing key locations. This allows clients to dynamically locate token endpoints without manual configuration updates when infrastructure shifts.

Complementing authorization server metadata, RFC 9728 defines protected resource metadata. It enables protected resources to advertise their required authorization servers, scopes, and supported bearer token methods. While this mechanism tells a client where to authenticate and which authorization server governs the resource, it does not inspect inbound tokens, evaluate cryptographic signatures, or confirm that a presented token matches the expected operational context.

Why can a valid signature still belong to the wrong audience?

A cryptographic signature proves only that a trusted private key generated the token, not that the token was minted for the service currently inspecting it. If an authorization server issues a valid JWT for Service A, an attacker can capture that token and present it to Service B if both services trust the same issuer.

{
  "iss": "https://auth.example.com",
  "aud": "https://service-a.example.com",
  "sub": "user-123",
  "exp": 1800000000
}

When Service B receives this payload, a naive implementation might inspect only the cryptographic signature, see that it matches the public key from the authorization server, and grant access. Because the audience claim (aud) points to Service A, Service B must reject the token. Enforcing strict audience checks prevents multi-tenant token replay attacks across microservices.

How are issuer mismatch and token-type confusion rejected?

Authentication boundaries require explicit rejection rules to handle malformed claims, unexpected issuers, and mismatched token types. Following RFC 8725 guidance on JSON Web Token best current practices, validators must explicitly enforce expected header parameters and payload constraints. For instance, token-type confusion occurs when an application accepts an ID token or an opaque assertion where an access token is required.

When designing machine commerce protocols or agent architectures, managing trust boundaries requires robust protocol segregation as detailed in discussions on agent authentication and machine commerce protocols, where clear credential validation rules prevent unintended privilege escalation.

Validation Check When to Use It Trade-off or Failure Mode Recommendation
Issuer Check (iss) Every incoming token Rejects tokens from unknown or untrusted auth servers Always match against a strict allowlist of authorized issuers.
Audience Check (aud) Microservice authorization Rejects valid tokens minted for different application tiers Bind every endpoint to its exact expected audience string.
Algorithm Check Signature verification Rejects 'none' or asymmetric-to-symmetric key confusion Hardcode allowed algorithms (e.g., RS256); never trust the alg header blindly.

Execution and Verification Checklist

  • [ ] Verify that a token with a valid signature but an unexpected audience string is rejected with an audience mismatch error.
  • [ ] Confirm that an unexpected issuer string causes immediate rejection even if the signing key is recognized.
  • [ ] Ensure that unapproved algorithms, such as 'none' or HMAC variants where RSA is expected, fail signature validation.
  • [ ] Test that metadata endpoints from RFC 9728 and RFC 8414 are used exclusively for endpoint discovery rather than runtime claim evaluation.

來源:DEV Community · dev.to