refactor: 使用 go-oidc 验证 ID Token

This commit is contained in:
2026-07-14 11:11:48 +08:00
parent 053bc260c7
commit 85d72a1c8c
7 changed files with 91 additions and 69 deletions
-39
View File
@@ -152,45 +152,6 @@ func (v *OIDCVerifier) Verify(ctx context.Context, raw string) (*User, error) {
}, nil
}
func (v *OIDCVerifier) VerifyIDToken(ctx context.Context, raw, clientID, expectedNonce string) (string, error) {
clientID = strings.TrimSpace(clientID)
expectedNonce = strings.TrimSpace(expectedNonce)
if clientID == "" || expectedNonce == "" {
return "", oidcUnauthorized("ID token validation context is invalid", nil)
}
parser := jwt.NewParser(jwt.WithValidMethods([]string{"RS256", "ES256"}))
unverified, _, err := parser.ParseUnverified(raw, jwt.MapClaims{})
if err != nil || unverified == nil {
return "", oidcUnauthorized("ID token envelope is invalid", err)
}
kid, _ := unverified.Header["kid"].(string)
if kid == "" {
return "", oidcUnauthorized("ID token kid is missing", nil)
}
key, err := v.key(ctx, kid)
if err != nil {
return "", oidcUnauthorized("ID token signing key lookup failed", err)
}
token, err := jwt.Parse(raw, func(token *jwt.Token) (any, error) {
if token.Header["kid"] != kid {
return nil, ErrUnauthorized
}
return key, nil
}, jwt.WithValidMethods([]string{"RS256", "ES256"}), jwt.WithIssuer(v.config.Issuer),
jwt.WithAudience(clientID), jwt.WithExpirationRequired(), jwt.WithLeeway(30*time.Second))
if err != nil || !token.Valid {
return "", oidcUnauthorized("ID token signature or registered claims are invalid", err)
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || stringClaim(claims, "sub") == "" || stringClaim(claims, "nonce") != expectedNonce {
return "", oidcUnauthorized("ID token subject or nonce is invalid", nil)
}
if _, ok := numericDateClaim(claims["nbf"]); !ok {
return "", oidcUnauthorized("ID token nbf is missing", nil)
}
return stringClaim(claims, "sub"), nil
}
func oidcUnauthorized(reason string, cause error) error {
if cause != nil {
return fmt.Errorf("%w: %s: %v", ErrUnauthorized, reason, cause)