@@ -24,16 +24,23 @@ struct QuoteServiceImpl: APIProtocol, OpenAPILambdaHttpApi {
2424
2525 let logger : Logger
2626
27- func register( transport: OpenAPILambdaTransport , middlewares: [ ServerMiddleware ] ) throws {
27+ func register( transport: OpenAPILambdaTransport ) throws {
28+
2829 // you have a chance here to customize the routes, for example
2930 try transport. router. get ( " /health " ) { _, _ in
3031 " OK "
3132 }
33+ logger. trace ( " Available Routes \n \( transport. router) " ) // print the router tree (for debugging purposes)
3234
35+ // to log all request and their response, add a logging middleware
3336 let loggingMiddleware = LoggingMiddleware ( logger: logger)
34- try self . registerHandlers ( on: transport, middlewares: middlewares + [ loggingMiddleware] )
3537
36- logger. trace ( " Available Routes \n \( transport. router) " ) // print the router tree (for debugging purposes)
38+ // This app includes a sample authorization middleware
39+ // It transforms the bearer token into a username.
40+ // The user can be access through a TaskLocal variable.
41+ let authenticationMiddleware = self . authenticationMiddleware ( )
42+
43+ try self . registerHandlers ( on: transport, middlewares: [ loggingMiddleware, authenticationMiddleware] )
3744 }
3845
3946 static func main( ) async throws {
@@ -93,6 +100,10 @@ struct QuoteServiceImpl: APIProtocol, OpenAPILambdaHttpApi {
93100
94101 func getQuote( _ input: Operations . getQuote . Input ) async throws -> Operations . getQuote . Output {
95102
103+ // You can log events to the AWS Lambda logs here
104+ guard let user = AuthenticationServerMiddleware . User. current else { return . unauthorized( . init( ) ) }
105+ logger. trace ( " GetQuote for \( user) - Started " )
106+
96107 let symbol = input. path. symbol
97108
98109 var date : Date = Date ( )
@@ -111,6 +122,31 @@ struct QuoteServiceImpl: APIProtocol, OpenAPILambdaHttpApi {
111122 timestamp: date
112123 )
113124
125+ logger. trace ( " GetQuote - Returning " )
126+
114127 return . ok( . init( body: . json( price) ) )
115128 }
129+
130+ func authenticationMiddleware( ) -> AuthenticationServerMiddleware {
131+ AuthenticationServerMiddleware ( authenticate: { stringValue in
132+ // Warning: this is an overly simplified authentication strategy, checking
133+ // for well-known tokens.
134+ //
135+ // In your project, here you would likely call out to a library that performs
136+ // a cryptographic validation, or similar.
137+ //
138+ // The code is for illustrative purposes only and should not be used directly.
139+ switch stringValue {
140+ case " 123 " :
141+ // A known user authenticated.
142+ return . init( name: " Seb " )
143+ case " 456 " :
144+ // A known user authenticated.
145+ return . init( name: " Nata " )
146+ default :
147+ // Unknown credentials, no authenticated user.
148+ return nil
149+ }
150+ } )
151+ }
116152}
0 commit comments