Suragch
Suragch

Reputation: 512676

How to get the request header in a Dart Aqueduct server

I want to get a token from the Authorization header of the request.

import 'dart:async';
import 'package:aqueduct/aqueduct.dart';


class SecretController extends ResourceController {

  @Operation.get()
  Future<Response> signin() async {

    request.headers // ??? not available

  }
}

How do I access that header in Aqueduct?

Upvotes: 2

Views: 416

Answers (1)

Joe Conway
Joe Conway

Reputation: 1586

A request is a wrapper around a raw HttpRequest object from the Dart standard library, so one way is to access it like this:

request.raw.headers["authorization"]

You can also bind the value of a header to a method parameter; this is nice when you want to parse the string header value into another type and/or validate the header. (You can do some really convenient stuff with binding.)

@Operation.get()
Future<Response> signIn(
  @Bind.header("authorization") String authorization) async {
  ...
}

Finally, specific to the Authorization header, you can use Authorizer middleware. This validates the authorization header and creates an Authorization object with the details of authorized resource owner ('the user') that you can access from your method.

router.route("/secret")
  .link(() => Authorizer.bearer(authServer))
  .link(() => SecretController());

...

@Operation.get()
Future<Response> signIn() async {
  final userIDForRequest = request.authorization.ownerID;
}

Upvotes: 3

Related Questions