1

In order to authenticate with Imgur on a mobile app, I decided to spawn an http server on port 8585 in order to complete the oauth flow. The request is read and a response is written, but I cannot access the queryparameters from the url.

I already tried using uri.queryparameters["access_token"], but null is returned.

the server is spawned as follows:

Future<Stream<String>> _server() async {
  final StreamController<String> onCode = new StreamController();
  HttpServer server =
  await HttpServer.bind(InternetAddress.loopbackIPv4, 8585);
  server.listen((HttpRequest request) async {
    print(request.uri.hashCode);
    final String accessToken = request.uri.queryParameters["access_token"];


    request.response
      ..statusCode = 200
      ..headers.set("Content-Type", ContentType.html.mimeType)
      ..write("<html><h1>You can now close this window</h1></html>");
    await request.response.close();
    await server.close(force: true);
    onCode.add(accessToken);
    await onCode.close();
  });
  return onCode.stream;
}

the url the server gets is of the sort: http://localhost:8585/callback#access_token=your_token_here&expires_in=315360000&token_type=bearer&refresh_token=_your_refresh_token_here

Can anyone help me? I've been stuck on this for two whole days!

MGassend
  • 83
  • 2
  • 9
  • if you ever get stuck on a problem just use the easiest way that you can think of to solve it. in this situation, you could just have used `string.indexOf('access_token')` and `string.substring` to get the token. – Ali Qanbari Oct 16 '19 at 17:29
  • @aligator the problem is that I can't get the full path; every method I can think of to get the uri path ends at "callback". – MGassend Oct 16 '19 at 17:32

1 Answers1

2

It returns null because query parameters start with ? at the beginning but in this link, there is a # before the query parameters and replacing it with a ? does solve the problem.

solution 1:

 var uri =Uri.parse('http://localhost:8585/callback#access_token=your_token_here&expires_in=315360000&token_type=bearer&refresh_token=_your_refresh_token_here');
 var newUri = Uri(query: uri.toString().substring(uri.toString().indexOf('#')+1));
 print(newUri.queryParameters['access_token']) // your_token_here;

solution 2:

  var uri =Uri.parse('http://localhost:8585/callback#access_token=your_token_here&expires_in=315360000&token_type=bearer&refresh_token=_your_refresh_token_here');
  var newUri = Uri.parse(uri.toString().replaceFirst('#', '?'));
  print(newUri.queryParameters['access_token']) // your_token_here;
Ali Qanbari
  • 2,923
  • 1
  • 12
  • 28
  • Thanks for the reply! The problem is that I get an HttpRequest and I am not able to get the full uri string. If I print request.uri.toString() I only get "/callback" without the query behind it. Any idea on how I could get the full path? – MGassend Oct 16 '19 at 18:16