@@ -2,6 +2,7 @@ import { z } from "zod";
22import { RequestHandler } from "express" ;
33import { OAuthRegisteredClientsStore } from "../clients.js" ;
44import { OAuthClientInformationFull } from "../../../shared/auth.js" ;
5+ import { InvalidRequestError , InvalidClientError } from "../errors.js" ;
56
67export type ClientAuthenticationMiddlewareOptions = {
78 /**
@@ -26,38 +27,34 @@ declare module "express-serve-static-core" {
2627
2728export function authenticateClient ( { clientsStore } : ClientAuthenticationMiddlewareOptions ) : RequestHandler {
2829 return async ( req , res , next ) => {
29- let client_id , client_secret ;
3030 try {
31- const result = ClientAuthenticatedRequestSchema . parse ( req . body ) ;
32- client_id = result . client_id ;
33- client_secret = result . client_secret ;
34- } catch ( error ) {
35- res . status ( 400 ) . json ( {
36- error : "invalid_request" ,
37- error_description : String ( error ) ,
38- } ) ;
39- return ;
40- }
31+ let client_id , client_secret ;
32+ try {
33+ const result = ClientAuthenticatedRequestSchema . parse ( req . body ) ;
34+ client_id = result . client_id ;
35+ client_secret = result . client_secret ;
36+ } catch ( error ) {
37+ throw new InvalidRequestError ( String ( error ) ) ;
38+ }
4139
42- const client = await clientsStore . getClient ( client_id ) ;
43- if ( ! client ) {
44- // TODO: Return 401 with WWW-Authenticate if Authorization header was used
45- res . status ( 400 ) . json ( {
46- error : "invalid_client" ,
47- error_description : "Invalid client_id" ,
48- } ) ;
49- return ;
50- }
40+ const client = await clientsStore . getClient ( client_id ) ;
41+ if ( ! client ) {
42+ throw new InvalidClientError ( "Invalid client_id" ) ;
43+ }
5144
52- if ( client . client_secret !== client_secret ) {
53- res . status ( 400 ) . json ( {
54- error : "invalid_client" ,
55- error_description : "Invalid client_secret" ,
56- } ) ;
57- return ;
58- }
45+ if ( client . client_secret !== client_secret ) {
46+ throw new InvalidClientError ( "Invalid client_secret" ) ;
47+ }
5948
60- req . client = client ;
61- next ( ) ;
49+ req . client = client ;
50+ next ( ) ;
51+ } catch ( error ) {
52+ if ( error instanceof InvalidRequestError || error instanceof InvalidClientError ) {
53+ res . status ( 400 ) . json ( error . toResponseObject ( ) ) ;
54+ } else {
55+ console . error ( "Unexpected error authenticating client:" , error ) ;
56+ res . status ( 500 ) . end ( "Internal Server Error" ) ;
57+ }
58+ }
6259 }
6360}
0 commit comments