I'm using dart-lang/rpc
with the shelf_rpc
package.
Some of my Resources require authentication. I decided to go with JWT and want to use the JwtSessionHandler
from shelf_auth
.
My simplified setup looks like this:
final ApiServer _apiServer = new ApiServer();
main() async {
var loginMiddleware = authenticate([new UsernamePasswordAuthenticator(lookupByUsernamePassword)],
sessionHandler: new JwtSessionHandler('my app', 'shhh secret', usernameLookup), allowHttp: true);
_apiServer.addApi(new Api());
// Create a Shelf handler for your RPC API.
var apiHandler = shelf_rpc.createRpcHandler(_apiServer);
var apiRouter = shelf_route.router()
..add('/api', null, apiHandler, exactMatch: false);
var handler = const shelf.Pipeline()
.addMiddleware(loginMiddleware)
.addMiddleware(shelf.logRequests())
.addHandler(apiRouter.handler);
var server = await shelf_io.serve(handler, '0.0.0.0', 8087);
}
/// Stub implementation
lookupByUsernamePassword(String username, String password) async =>
new Some(new Principal(username));
/// Stub implementation
usernameLookup(String username) async =>
new Some(new Principal(username));
How can I only add the loginMiddleware
to requests that start with /account
(for example)? Or even better: is it possible to define the loginMiddleware
on the RPC Resource itself (instead of defining a path prefix which can potentially change and annul the authentication)?
You would just create a handler that only does something when that path starts with account. This should work.