Giter Site home page Giter Site logo

appsup-dart / openid_client Goto Github PK

View Code? Open in Web Editor NEW
90.0 90.0 113.0 432 KB

Library for working with OpenID Connect and implementing clients.

License: BSD 3-Clause "New" or "Revised" License

Dart 61.57% HTML 2.12% CSS 0.18% Kotlin 0.20% Ruby 2.12% Swift 1.00% Objective-C 0.03% CMake 14.76% C++ 16.82% C 1.12% Dockerfile 0.08%
oauth2 openid-connect

openid_client's People

Contributors

betterb0y avatar insertjokehere avatar passsy avatar rbellens avatar twklessor avatar wstrange avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

openid_client's Issues

How to get refresh token?

Is there anyway I can get refresh token, I am using web client and AuthorizationPKCE grant type.
I don't see any interface to get refresh token. Any help?

App stays in pause state

Hello,

I have implemented a  PCKE  flow by redirecting the user to identity provider and everything works fine. The problem I have is that if the user click back button of his phone in the webview instead of adding his credentials and log in, he returns to app but the app remains in pause state. I tried to find if the  url launcher gets any parameter as a back button callback but I was not able to find something. Do I miss something?

query prompt=login not working

var uri = new Uri(scheme: "http", host: "10.0.2.2", port: 5000, query: "prompt=login" );

when i do prompt=login it does not take me to login page but automatically logs in the user.

How to delete auto login

In flutter, the system automatically logs in if there is a 'state' available i'm assuming. Problem being is that the token may not be valid and i keep getting unauthorized over and over. How can i remove this auto login or clear the state / token?

ERR_CLEARTEXT_NOT_PERMITTED Android

Using the default redirect url on port 4000 per the example on android results with the above error message.

It would be much better if this library used the device's authentication system to get notifications back of the authentication. And on web just redirected and picked it up from the url.

Otherwise It appears that at least on Android https is required.

Redirection to Keycloak not working using openid package for flutter app

Currently building a flutter app that uses keycloak to authenticate users. The user is supposed to click on the login button that will take him to the web interface built using keycloak , after the authentication the user will be brought back to the app (home page ) after getting the token. Since I have no idea how this is supposed to work I followed this example Example Link

This is my function :

 authenticate() async {
    var uri = Uri.parse('http://10.0.2.2:8080/auth/realms/clients');
    var clientId = 'helium';
    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,);

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

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




Am calling it inside a button:


   RoundedButton(
              text: "Login",
                press: (){


                authenticate();
                }

                //Navigator.push(
                  //context,
                 //MaterialPageRoute(
                  // builder: (context) {
                     //return MainMenu();
                    //},
                 // ),
               //);


                 ,
            ),







this is the stack trace :


E/flutter ( 5769): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Instance of 'HttpRequestException'
E/flutter ( 5769): #0      _processResponse (package:openid_client/src/http_util.dart:37:5)
E/flutter ( 5769): #1      get (package:openid_client/src/http_util.dart:18:10)
E/flutter ( 5769): <asynchronous suspension>
E/flutter ( 5769): #2      Issuer.discover (package:openid_client/src/openid.dart:124:16)
E/flutter ( 5769): <asynchronous suspension>
E/flutter ( 5769): #3      Body.authenticate (package:helium_app/screens/login/components/body.dart:35:18)
E/flutter ( 5769): <asynchronous suspension>




Am I missing something ? if anyone knows how to make this work , plz don't hesitate to help and guide me through this , also I would love to know how to generate a link to my home page to redirect the user to it instead of the redirection URI am using in the function 'http://localhost:4200'

thank u in advance

Not able to retrieve the Access token and Refresh token after successful redirection from keyCloak to the App (Flutter Web)

Description :

Redirection to Keycloak is working properly but even after successful authentication from Keycloak not able to retrieve the Access token and Refresh token.

Expected Results :

After Successful redirection from Keycloak, it should store the access token and refresh token in local storage or cache
eg:- It should at least store the access token or response in window.localStorage['openid_client:auth']

Actual Result : Currently only the state is stored in the local storage in window.localStorage['openid_client:state']
and the window.localStorage['openid_client:auth'] is empty, not able to retrieve the access token or the refresh token from the local storage of the browser

How to authenticate with keycloak through authorization code flow?

I'm trying to authenticate my flutter app to keycloak

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?

Not able to redirect to the application after successful login

Hello,

I created the sample application as per your provided readme document, it's working properly for the mobile but facing some issues for the web

After running the project with the below command
flutter run -d chrome --web-port 60000
it navigates to the keycloak login screen and after login it redirects to one white screen with url contains the information
for the token state etc. and does not navigate back to the app.

As per noticed issue i'm facing this issue only when running through the above command or normal flutter project run.
When i build the project and then host it in the IIS (Internet Service Manager ) in windows system, it seems to work fine i.e. it redirects to app after successful login.

Steps to reproduce:

  1. Create new flutter project
  2. import packages as per the readme example setup the whole example for web
  3. After running normally with command it redirects to the login screen but after successful login it stuck on white screen with token and some other details in the URL section

Versions:

Flutter 2.0.1 • channel beta • https://github.com/flutter/flutter.git
Framework • revision c5a4b4029c (7 months ago) • 2021-03-04 09:47:48 -0800
Engine • revision 40441def69
Tools • Dart 2.12.0

Any workaround or solution for this issue, As each time building app and after that hosting is not a feasible solution as sometimes we need to debug the project

Thank you.

Dynamic OpenID Providers MUST support the code, id_token, and the token id_token Response Type values.

According to this openID document https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse, "Dynamic OpenID Providers MUST support the code, id_token, and the token id_token Response Type values.". I tried using openID_client to connect with login.gov. login.gov's discovery metadata has "response_types_supported": ["code"], openid_client will fail at this function:

Flow.implicit(Client client, {String state})
: this._(
FlowType.implicit,
['token id_token', 'id_token token', 'id_token', 'token']
.firstWhere((v) =>
client.issuer.metadata.responseTypesSupported.contains(v)),
client,
state: state);

Can we add 'Code' in the list?

Support registration client

Hello

I was wondering if there is any possiblity to have a client registration like present on this link from the keycloak doc ?

Is that possible in anyway or is it maybe already available ?

Logout issues

Hi.

I'm not able to figure out how to sign out using this library. Revoke is not working for me and after sending generateLogoutUrl() using http.get request I'm able to call my API as it never happened.

How can I clear tokens manually?
What am I doing wrong?

Flutter Support

Please support Flutter.

Steps to reproduce error:
I put "openid_client: ^0.1.3" in the file pubspec.yaml dependencies. But it depends on "unscripted" and it depends on 'dart:mirrors', which is incompatible with flutter.

Not able to get refresh token for the web

Description:

i'm trying to get the access token using the below function as per the readme docs
var tr = await credential.getTokenResponse()

when i fetch the token as per the above method then getting the token, but when i fetch the token with below syntax i.e send the dorceRefresh argument to true then getting below error
Called Function:
var tr = await credential.getTokenResponse(true)

Error:
Invalid Argument : null

Can you suggest any workaround for this, as per our requirement we need to get the latest token by forceRefresh option.
also can you suggest correct way for sending that forceRefresh option, As per the package code checked there that forceRefresh argument is provided in the square braces [ ] so that's why while calling that function its not suggesting that option for sending argument.
Future<TokenResponse> getTokenResponse([bool forceRefresh = false])

Method not found

Hi @rbellens
Hello everyone
I'm using your library to perform authentication ... but I'm having a problem

Error: Method not found: 'JsonSerializable'

Please, can you help me?

Launching lib/main.dart on iPhone X in debug mode...
Running pod install...
Starting Xcode build...
Xcode build done.
[VERBOSE-2:shell.cc(181)] Dart Error: error: import of dart:mirrors with --enable-mirrors=false
[VERBOSE-2:engine.cc(158)] Could not prepare to run the isolate.
[VERBOSE-2:engine.cc(117)] Engine not prepare and launch isolate.
[VERBOSE-2:FlutterViewController.mm(411)] Could not launch engine with configuration.
Syncing files to device iPhone X...
compiler message: lib/oidc/model/metadata.dart:5:2: Error: Method not found: 'JsonSerializable'.
compiler message: @JsonSerializable()
compiler message:  ^
compiler message: lib/oidc/model/jwk.dart:3:2: Error: Method not found: 'JsonSerializable'.
compiler message: @JsonSerializable()
compiler message:  ^
compiler message: lib/oidc/model/jwk.dart:8:4: Error: Method not found: 'JsonKey'.
compiler message:   @JsonKey('kty')
compiler message:    ^
compiler message: lib/oidc/model/jwk.dart:8:11: Error: Too many positional arguments: 0 allowed, but 1 found.
compiler message: Try removing the extra positional arguments.
compiler message:   @JsonKey('kty')
compiler message:           ^^^^^^^
compiler message: lib/oidc/model/jwk.dart:32:4: Error: Method not found: 'JsonKey'.
compiler message:   @JsonKey('key_ops')
compiler message:    ^
compiler message: lib/oidc/model/jwk.dart:32:11: Error: Too many positional arguments: 0 allowed, but 1 found.
compiler message: Try removing the extra positional arguments.
compiler message:   @JsonKey('key_ops')
compiler message:           ^^^^^^^^^^^
compiler message: lib/oidc/model/jwk.dart:37:4: Error: Method not found: 'JsonKey'.
compiler message:   @JsonKey('alg')
compiler message:    ^
compiler message: lib/oidc/model/jwk.dart:37:11: Error: Too many positional arguments: 0 allowed, but 1 found.
compiler message: Try removing the extra positional arguments.
compiler message:   @JsonKey('alg')
compiler message:           ^^^^^^^
compiler message: lib/oidc/model/jwk.dart:44:4: Error: Method not found: 'JsonKey'.
compiler message:   @JsonKey('kid')
compiler message:    ^
compiler message: lib/oidc/model/jwk.dart:44:11: Error: Too many positional arguments: 0 allowed, but 1 found.
compiler message: Try removing the extra positional arguments.
compiler message:   @JsonKey('kid')
compiler message:           ^^^^^^^
compiler message: lib/oidc/model/jwk.dart:48:4: Error: Method not found: 'JsonKey'.
compiler message:   @JsonKey('x5u')
compiler message:    ^
compiler message: lib/oidc/model/jwk.dart:48:11: Error: Too many positional arguments: 0 allowed, but 1 found.
compiler message: Try removing the extra positional arguments.
compiler message:   @JsonKey('x5u')
compiler message:           ^^^^^^^
compiler message: lib/oidc/model/jwk.dart:52:4: Error: Method not found: 'JsonKey'.
compiler message:   @JsonKey('x5c')
compiler message:    ^
compiler message: lib/oidc/model/jwk.dart:52:11: Error: Too many positional arguments: 0 allowed, but 1 found.
compiler message: Try removing the extra positional arguments.
compiler message:   @JsonKey('x5c')
compiler message:           ^^^^^^^
compiler message: lib/oidc/model/jwk.dart:57:4: Error: Method not found: 'JsonKey'.
compiler message:   @JsonKey('x5t')
compiler message:    ^
compiler message: lib/oidc/model/jwk.dart:57:11: Error: Too many positional arguments: 0 allowed, but 1 found.
compiler message: Try removing the extra positional arguments.
compiler message:   @JsonKey('x5t')
compiler message:           ^^^^^^^
compiler message: lib/oidc/model/jwk.dart:62:4: Error: Method not found: 'JsonKey'.
compiler message:   @JsonKey('x5t#S256')
compiler message:    ^
compiler message: lib/oidc/model/jwk.dart:62:11: Error: Too many positional arguments: 0 allowed, but 1 found.
compiler message: Try removing the extra positional arguments.
compiler message:   @JsonKey('x5t#S256')
compiler message:           ^^^^^^^^^^^^
compiler message: lib/oidc/model/jwk.dart:86:2: Error: Method not found: 'JsonSerializable'.
compiler message: @JsonSerializable()
compiler message:  ^
....

Allow specifying the flow using Authenticator

Hi Rik,

When using the Authenticator class and providing a redirectUri, the Authorization Code grant type will be chosen by default. In my case, a different redirectUri is needed, together with the Authorization Code with PKCE grant type.

As shown in PR #41 , it has already been attempted to expose the flow constructor for customization, however I do not see this present in the main branch.

My proposal is to add an optional Flow in the Authenticator constructor, which will default to the current implementation when not given. This way, current implementations of the library will continue to be supported, while enabling both redirectUri and Authorization Code with PKCE grant types to be used simultaneously when necessary.

I have implemented the proposed change and will open and link a PR for you to review and merge.

Edit: The corresponding PR is #56.

Please let me know if there are any questions and whether the proposed change is acceptable.

Looking forward to hearing from you and with kind regards,

Andreas

Add support for grant_type password

Keycloak provides OpenID Connect logins with username and password.

The endpoint is POST https://<keycloak-domain:port>/auth/realms/<realm_name>/protocol/openid-connect/token
With the x-www-form-urlencoded body:
username=xyz&password=abc&grant_type=password&client_id=our_client_id

This works If I send the request directly to the server, but I cannot for the life of me figure out how to do it with this library. All I could find by looking at the source is that you support grant_type authorization_code and urn:ietf:params:oauth:grant-type:jwt-bearer but not password.

PKCE flow of OpenID Connect

Hi,

Is there an example on using this library with the PKCE flow of PKCE flow of OpenID Connect?

I see there was a fix, but am looking for an example please

Expired access token in openid_client:auth causes getUserInfo to fail

I have a working authentication setup for web, i.e. I open the app, I get redirected, insert my credentials, get redirected again and get a valid result from getUserInfo.
However when I reopen the app after the originally issued access token has expired, the process fails. The auth server (keycloak in this case) returns:

www-authenticate: Bearer realm="MyRealm", error="invalid_token", error_description="Token verification failed"

Analyzing the request that gets sent to the server, I found that the access_token being sent is the one that was originally issued. I tried called getTokenResponse before calling getUserInfo, but with no luck.

Digging a bit deeper I discovered that credentials are being read from local storage (openid_client:auth). However openid_client:auth is only updated when calling authorize, which, following your examples, I do not if I already have credentials.

The only way I found that this works1 is if I call getTokenResponse(true), forcing a token refresh. However, my assumption was that expired access tokens should cause a refresh automatically?
Any feedback would be highly appreciated.

1: It does not actually work due to another bug I have encountered, but I'm still investigating. It's most likely due to my setup, but will open a separate issue if otherwise

Refresh Token automatically after it expires to keep the user session active

Hello everyone , am using the openeiclient package in my flutter app to redirect my users to Keycloak so they ken log in . My method works perfectly fine and am able to retrieve the JWT token , I want to be able to refresh the token am getting whenever it expires so I can keep my user session active and I have no idea how to do it .This is the function am using to redirect me to Keycloak :

authenticate() async {
      // keyclock url : key-clock-url : example : http://localhost:8080
      // my realm : name of your real.m
      var uri = Uri.parse('http://169.254.105.22:8080/auth/realms/Clients');
      // your client id
      var clientId = 'helium';
      var scopes = List<String>.of(['openid', 'profile']);
      var port = 8080;
      var issuer = await Issuer.discover(uri);
      var client = new Client(issuer, clientId);
      print(issuer.metadata);
      urlLauncher(String url) async {
        if (await canLaunch(url)) {
          await launch(url, forceWebView: true);
        } else {
          throw 'Could not launch $url';
        }
      }
      authenticator = new Authenticator(
        client,
        scopes: scopes,
        port: port,
        urlLancher: urlLauncher,
      );
      var c = await authenticator.authorize();
      closeWebView();
      var token = await c.getTokenResponse();
      var userInformation = await c.getUserInfo();
      setState(() {
        userAccessToken = token.accessToken;
        userRefreshToken = token.refreshToken;
        print (userRefreshToken);
        userName = userInformation.preferredUsername;
      });
      //print(token);
      //return token;
      parseJwt(userAccessToken);


    }

If you know how I can check if my token has expired then automatically ask for a new token (which include new accessToken and a new refreshToken ) please guide me through this for I've been stuck for a while .Thank u in advance

Throw exception with error name if error_description is not provided

currently, only error_description is used to get the error message returned from token endpoint
there are cases where server just return error without error_description, so:

  • json["error_description"] should be used if exists
  • json["error"] should be used if error_description not exists

image

Issue , integrating flutter web app with ForgeRock

I used web version of the example, no matter what I do I end up with the error :

{
  "error": "unauthorized_client",
  "error_description": "The authenticated client is not authorized to use this authorization grant type."
}

"Do I need to create metadata ?
I registered client ID and issuer URL in forgeRock, do I need to do anything else ? Does web version work authorization code flow"

I am using this code // import the browser version
import 'package:openid_client/openid_client_browser.dart';

authenticate(Uri uri, String clientId, List<String> scopes) async {   
    
    // create the client
    var issuer = await Issuer.discover(uri);
    var client = new Client(issuer, clientId);
    
    // create an authenticator
    var authenticator = new Authenticator(client, scopes: scopes);
    
    // get the credential
    var c = await authenticator.credential;
    
    if (c==null) {
      // starts the authentication
      authenticator.authorize(); // this will redirect the browser
    } else {
      // return the user info
      return await c.getUserInfo();
    }
}

Web app returns empty credentials and userInfo

With the example for a Flutter app on Android, I am redirected to the login entry without any problems and have access to my userInfo data after entering my user data. However, if I replace the authenticate() function with the code provided in the readme for the web version, I am redirected correctly, but I always get null for authenticator.credential. After coming back from the login screen to the webapp, there is a url displayed shortly that contains the access_token, the state, and the id_token. But within a second, this url is replaced by my default local host address without any parameters appended. The webapp gets also reloaded. I don't see what is missing for the web version, as it works for Android as expected. I would appreciate your help.

During debuggin, I have noticed that the function _credentialFromUri(Flow flow) only sees the basic local host address.

For reproducing the problem, here is a minimal working example. I use auth0 for login and allowed redirecting to the local host, which is used for Android and the web version. The plus button starts the redirection:

import 'package:flutter/material.dart';
// import the browser version
import 'package:openid_client/openid_client_browser.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() async {
    var userInfo = await authenticate(
        Uri.parse('https://TEST.eu.auth0.com'),
        'CLIENT_ID',
        ['openid', 'profile', 'offline_access']);
    print('userInfo: $userInfo');
    _counter++;
  }

  authenticate(Uri uri, String clientId, List<String> scopes) async {
    // create the client
    var issuer = await Issuer.discover(uri);
    var client = new Client(issuer, clientId);

    // create an authenticator
    var authenticator = new Authenticator(client, scopes: scopes);

    // get the credential
    var c = await authenticator.credential;

    if (c == null) {
      // starts the authentication
      authenticator.authorize(); // this will redirect the browser
    } else {
      // return the user info
      return await c.getUserInfo();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('test'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Flutter doctor :

[✓] Flutter (Channel stable, 2.0.5, on Linux, locale de_DE.UTF-8)
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/linux#android-setup for more details.
[✓] Chrome - develop for the web
[✓] Android Studio
[✓] Connected device (1 available)

getUserInfo type cast error

Dart version: 2.12.2

After authenticating and attempting to obtain the user info using the getUserInfo() method the following error occurs:

E/flutter ( 6893): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type 'Future<dynamic>' is not a subtype of type 'FutureOr<Map<String, dynamic>>' in type cast
E/flutter ( 6893): #0      Credential.getUserInfo (package:openid_client/src/openid.dart:195:26)

If I modify the line
return UserInfo.fromJson(await (_get(uri) as FutureOr<Map<String, dynamic>>));
to
return UserInfo.fromJson(await (_get(uri)));

The error goes away and everything works as expected, not sure that this would be the best approach though.

Ideas on a fix? Happy to PR it after discussion.

example flutter web

Hi,
is there anyone who can provide a working example for flutter web?
That would be great!
Thanks
Stefan

Null-Safety

hello and thanks for all your efforts.

Will this package be updated to support null safety? if yes then could you give us an ETA?

Using a custom redirectUri instead of "http://localhost:$port" is not working

In this issue, this comment concludes the same: #4 (comment)

I spent so much time debugging this, and finally had to change my custom redirectUri from my openid Identity Server to match http://localhost:$port. Anything other than that didn't work. The browser would just display "Can't open this url. Unknown..." and the app would hang there.

I tried debugging but can't make out why this happens with a custom redirectUri only.

Issuer.discover(uri) return XMLHttpRequest error in response - Flutter on web

Issuer.discover(uri) return the error in response saying "XMLHttpRequest error". I am using this package for Flutter on web for chrome browser. I can't proceed further. It seems it is getting on http.get request. Can you let me know how to resolve this error. I can see the configuration file in response when I run URL directly on chrome.

Is this package works for Flutter on web?

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

I have installed the needed CA to the android phone yet still getting the above error. Could it be what is causing me to get a blank white screen?

Also, assuming the white screen is a failed attempt to collect my credentials. I already have the credentials, could I possibly pass those in?

I/cr_X509Util(24485): Failed to validate the certificate chain, error: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
E/chromium(24485): [ERROR:ssl_client_socket_impl.cc(960)] handshake failed; returned -1, SSL error code 1, net_error -202

Unsupported operation when using the library with flutter web

I am using this library with flutter web and get the following error:

Error: Unsupported operation: InternetAddress.ANY_IP_V4
    at Object.throw_ [as throw] (http://localhost:51179/dart_sdk.js:5032:11)
    at Function.get ANY_IP_V4 [as ANY_IP_V4] (http://localhost:51179/dart_sdk.js:55307:17)
    at Function.get anyIPv4 [as anyIPv4] (http://localhost:51179/dart_sdk.js:55304:33)
    at Function._startServer (http://localhost:51179/packages/openid_client/openid_client_io.dart.lib.js:108:81)
    at openid_client_io.Authenticator.new.authorize (http://localhost:51179/packages/openid_client/openid_client_io.dart.lib.js:85:46)
    at authorize.next (<anonymous>)
    at runBody (http://localhost:51179/dart_sdk.js:37229:34)
    at Object._async [as async] (http://localhost:51179/dart_sdk.js:37260:7)
    at openid_client_io.Authenticator.new.authorize (http://localhost:51179/packages/openid_client/openid_client_io.dart.lib.js:81:20)
    at login_view._LoginViewState.new.loginAction (http://localhost:51179/packages/dashboard/views/login/login_view.dart.lib.js:1633:38)

My setup is:

flutter doctor -v
[√] Flutter (Channel stable, 2.0.3, on Microsoft Windows [Version 10.0.19042.870], locale de-CH)
    • Flutter version 2.0.3 at C:\src\flutter
    • Framework revision 4d7946a68d (11 days ago), 2021-03-18 17:24:33 -0700
    • Engine revision 3459eb2436
    • Dart version 2.12.2
    • Pub download mirror https://pub.dev

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.0-rc2)
    • Android SDK at C:\Users\SebastianBuechler\AppData\Local\Android\sdk
    • Platform android-30, build-tools 30.0.0-rc2
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

[√] Android Studio (version 4.1.0)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)

[√] VS Code (version 1.54.3)
    • VS Code at C:\Users\SebastianBuechler\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.20.0

[√] Connected device (3 available)
    • Android SDK built for x86 64 (mobile) • emulator-5554 • android-x64    • Android 10 (API 29) (emulator)
    • Chrome (web)                          • chrome        • web-javascript • Google Chrome 89.0.4389.90
    • Edge (web)                            • edge          • web-javascript • Microsoft Edge 89.0.774.57

• No issues found!

And I am using the example for flutter on the library page.

Any idea why this does not work with flutter web?

Keycloak Issue using Google Provider (403 error and browser not closing)

Hi all

Just found an issue using Keycloak, when user try to authenticate using the Google Provider (on keycloak UI authentication page)
First issue : 403 disallowed user agent
FIX : => i was forced to comment this line forceWebView: true,

Now next issue is that opening a native browser (and not in-app browser), the browser can't be closed after authentication
The redirect_uri keep showing (with a blank page)
I can not found out how to fix this
Of course the await closeWebView(); can't help when not in an in-app webview.

Any clue or same use case maybe ?

Maybe a way to fix the 403 error using url_lancher without disallowing the in-app webview ?

Thanks

Flutter web authentication issue with Keycloak

Maybe I am doing something incorrectly but I try to use the browser authentication inside a flutter web application.

I get authenticated by, at least I think I am, because I get an id token. but do not get a expires_at/expires_in or refresh token.
What I understand from different sites is that you should not get a refresh token so that is ok?

Now when I try to get the user data like the code below I get an error: "Invalid argument: null".
I think that is because I haven't set the accessToken but I did not receive it.

My code:

import 'package:openid_client/openid_client_browser.dart' as openIdBrowser;
static const List<String> _scopes = ['openid', 'profile', 'email', 'roles'];
....

var authenticator = new openIdBrowser.Authenticator(this._client, scopes: _scopes);
 _credential = await authenticator.credential;

if (_credential==null) {
      // starts the authentication
      authenticator.authorize(); // this will redirect the browser
}
print("Userinfo: ${await _credential.getUserInfo()}");

Is an id token what is needed or am I doing something wrong?

I am also using the library for the app version and that seems to work fine.

Tijs

401 Unauthorized

Hi everyone. I use the openid_client library in flutter mobile app with keycloak server. But access token returned after login is invalid.Please someone can help me. Thanks

My flutter login code:
` login() async {

var uri = Uri.parse(env["KEYCLOAKURL"].toString());
 var clientId = env["KEYCLOAKCLIENTID"].toString();
 var scopes = List<String>.of(['openid', 'profile', 'offline_access']);
 var issuer = await Issuer.discover(uri);
 var client = new Client(issuer, clientId);
 urlLauncher(String url) async {
   if (await canLaunch(url)) {
          await launch(url);
          } else {
               throw 'Could not launch $url';
             }
   }
var authenticator = new Authenticator(client,
    scopes: scopes, port: 8080, urlLancher: urlLauncher);

var c = await authenticator.authorize();

TokenResponse tokenResponse = await c.getTokenResponse();
await this.storage.write(key: "REFRESH", value: tokenResponse.refreshToken);
await this.storage.write(key: "TOKEN", value: tokenResponse.accessToken);

closeWebView();

}`
Keycloak configuration:

Capture

Using openID for keycloak error

Hello,

I have been trying through de command line to add clients like that :
openid_client clients configure https://my_realm_keycloak client_id

error throw :
type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>'

I tried this as well :
openid_client clients configure --secret my_scret_keycloak https://my_realm_keycloak client_id

same error throw :
type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>'

Do you have any ideas ? thanks in advance :)

building for web fails with an error

I just implemented OpenID into my app and now I get this error when launching on the web:

Launching lib\main.dart on Chrome in debug mode...
lib\main.dart:1
/D:/Programmieren/SDKs/flutter/.pub-cache/hosted/pub.dartlang.org/pointycastle-3.1.3/lib/key_derivators/argon2.dart:42:27: Error: The integer literal 0xFFFFFFFFFFFFFFFF can't be represented exactly in JavaScript.
Try changing the literal to something that can be represented in Javascript. In Javascript 0x10000000000000000 is the nearest value that can be represented exactly.
  static const int M32L = 0xFFFFFFFFFFFFFFFF;
                          ^^^^^^^^^^^^^^^^^^
/D:/Programmieren/SDKs/flutter/.pub-cache/hosted/pub.dartlang.org/pointycastle-3.1.3/lib/src/utils.dart:313:9: Error: The integer literal 0xFFFFFFFFFFFFFFFF can't be represented exactly in JavaScript.
Try changing the literal to something that can be represented in Javascript. In Javascript 0x10000000000000000 is the nearest value that can be represented exactly.
      ((0xFFFFFFFFFFFFFFFF) ^ ((1 << (64 - count)) - 1));
        ^^^^^^^^^^^^^^^^^^
/D:/Programmieren/SDKs/flutter/.pub-cache/hosted/pub.dartlang.org/pointycastle-3.1.3/lib/src/platform_check/platform_check.dart:6:35: Error: Method not found: 'getPlatform'.
  static Platform get instance => getPlatform();
                                  ^^^^^^^^^^^
Failed to compile application.
Exited (sigterm)

I tried rebuilding with only "openid_client_browser" imported in my files, but it still failed wich means that the package is unusable for web deployment

Facebook example

Hi,

It would be nice if you added a real example to work with facebook, along with it's scope options and all.

Thanks for the library.

PKCE flow cannot be completed in AngularDart web application due incorrect 'code_verifier' value

Hello,

I am working on AngularDart Web SPA and want to implement PKCE authentication...

I meet an issue with Flow.authorizationCodeWithPKCE.
Constructor of the class initializes values (see code lib/src/openid.dart#L342-L349)

    ...
    var verifier = _randomString(50);
    ...
    _proofKeyForCodeExchange = {
      'code_verifier': verifier,
      'code_challenge': challenge
    };
    ...

So each new Flow object has own verifier/challenge values.

In my authentication scenario:

  • My application creates first Flow object and make redirect to Authentication Server (IndentityServer4 in my case). Redirect looks like https://id.server/connect/authorize?response_type=code&scope=openid+openid+profile+Dashboard.Read+Dashboard.Write&client_id=angular_spa&redirect_uri=http%3A%2F%2F127.0.0.1%3A8080%2F%23%2Fchildren&state=9KFkMK4NhbCUgQpP0wNst9e5nVmFbCIeOdSNVGGgFkpfBDZeKE&code_challenge_method=S256&code_challenge=OeY8ejw4ONcZty_lQBLpWbhFyAUfyEe8uRWS5o7wPq4. This link has code_challenge from first Flow object.
  • Authentication Server ask login/password and make necessary auth action. Finally Authentication Server redirect browser back to my app. Redirect looks like http://127.0.0.1:8080/#/children?code=7B69313E40979013687FC8442829B0849E287CD351B2F35E83207290270403B3&scope=openid%20profile%20Dashboard.Read%20Dashboard.Write&state=9KFkMK4NhbCUgQpP0wNst9e5nVmFbCIeOdSNVGGgFkpfBDZeKE&session_state=b1qZ6KgawcJw5G6IDewn9UlnccZgVWhvlO68oBfC7ww.6EF65CE28705809AB26C552A3F07DBFF
  • My applications is loading into browser. The application creates second Flow object, validates query arguments and call flow.callback(q.cast()). Authentication Server sends failure response: "Transformed code verifier does not match code challenge" and this is correct due we sent incorrect code_verifier from second Flow object.
  1. Is this expected behaviour? How use Flow to avoid the issue?
  2. Provide your vision to solve the problem and I will make implementation as PR

Thanks

Screen Shot 2021-01-07 at 20 16 24

API Access

Hi,

I was able to use openid_client library in Flutter to successfully login and get user information with getUserInfo, but I'm not sure how to proceed and access secure endpoints on my server. All endpoints expect valid access_token as a part of the Authorization header. Can I access this endpoints using openid_client directly, or do I have to somehow get access_token from the library? Additionally would openid_client take care of refreshing the access_token for me?

Thanks,
Milos

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.