Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authenticate flutter app with keycloak and openid_client

I'm trying to authenticate my flutter app to keycloak through openid_client

following the repo example, I've wrote an authentication function like this

authenticate() async {

  // parameters here just for the sake of the question
  var uri = Uri.parse('https://keycloak-url/auth/realms/myrealm');
  var clientId = 'my_client_id';
  var scopes = List<String>.of(['openid', 'profile']);
  var port = 4200;
  var redirectUri = Uri.parse('http://localhost:4200');

  var issuer = await Issuer.discover(uri);
  var client = new Client(issuer, clientId);

  urlLauncher(String url) async {
    if (await canLaunch(url)) {
      await launch(url, forceWebView: true);
    } else {
      throw 'Could not launch $url';
    }
  }

  var authenticator = new Authenticator(client,
      scopes: scopes,
      port: port,
      urlLancher: urlLauncher,
      redirectUri: redirectUri);

  var c = await authenticator.authorize();
  closeWebView();

  var token= await c.getTokenResponse();
  print(token);
  return token;
}

when I call the function, a webview popup appears and I can login through keycloak, but when the popup closes I get this error at the c.getTokenResponse():

Exception has occurred. NoSuchMethodError (NoSuchMethodError: The getter 'length' was called on null. Receiver: null Tried calling: length)

inspecting the Credential c, I can see that the TokenResponse has only "state", "session_state" and "code" fields

what am I missing?

like image 366
Doc Avatar asked Mar 23 '20 13:03

Doc


People also ask

What is Keycloak Auth?

The Keycloak authentication module is a pre-configured OAuth 2.0 auth module that lets users log in to Hub and any connected service with their Keycloak credentials.

Is Keycloak Open ID connect?

Keycloak supports both OpenID Connect (an extension to OAuth 2.0) and SAML 2.0. When securing clients and services the first thing you need to decide is which of the two you are going to use. If you want you can also choose to secure some with OpenID Connect and others with SAML.


1 Answers

I've been answered on github (link), so I'll copy the solution here:


On mobile devices you should use the PKCE flow. This is automatically selected when you omit the redirect uri in the Authenticator constructor.

So, it should be:

var authenticator = new Authenticator(client,
      scopes: scopes,
      port: port,
      urlLancher: urlLauncher,);

Make sure you add the uri http://localhost:4200/ (including the trailing slash) to Valid Redirect URIs in keycloak.

image

Make sure you add the uri http://localhost:4200/ (including the trailing slash) to Valid Redirect URIs in keycloak.

like image 154
Doc Avatar answered Oct 09 '22 08:10

Doc