Search code examples
javascriptgoogle-app-enginegwtjsnifido-u2f

U2F JavaScript for Client Side in GWT (JSNI)


I'm trying to get response from U2F Token in GWT project using this source code:

public class Test implements EntryPoint {

    @Override
    public void onModuleLoad() {
         Window.alert("Alert 3:"+u2FTest());
    }

    public static native String u2FTest()/*-{
    var respond = {rep: "Clear"};
    var RegistrationData = {"challenge":"dG7vN-E440ZnJaKQ7Ynq8AemLHziJfKrBpIBi5OET_0",
                            "appId":"https://localhost:8443",
                            "version":"U2F_V2"};
 $wnd.u2f.register([RegistrationData], [],
  function(data) {if(data.errorCode) {
        alert("U2F failed with error: " + data.errorCode);
        return;
    }

    respond.rep=JSON.stringify(data);
    alert("Alert 1: "+respond.rep); 
});
 alert("Alert 2: "+respond.rep);
 return respond.rep;
}-*/;

}

for some reasons I get The Alerts like so:

  1. (Alert 2) first with "Clear" result
  2. (Alert 3) with "Clear"
  3. (Alert 1) with Token response

Normally I've to get (Alert 1) with Token response then 2,3. So how can I stop execution until I'll get the token response Thank you,


Solution

  • Embrace asynchronicity!

    public static native void u2FTest(com.google.gwt.core.client.Callback<String, Integer> callback) /*-{
      // …
      $wnd.u2f.register(regReqs, signReqs, $entry(function(response) {
        if (response.errorCode) {
          [email protected]::onFailure(*)(@java.lang.Integer::valueOf(I)(response.errorCode));
        } else {
          [email protected]::onSuccess(*)(JSON.stringify(response));
        }
      }));
    }*-/;
    

    (don't forget to wrap callbacks in $entry() so that exceptions are routed to the GWT.UnhandledExceptionHandler, if there's one)