catalyst / moodle-auth_userkey

Log in to Moodle using one time user key based login URL. Auth plugin for organising simple SSO (single sign on) between moodle and your external web application.
https://moodle.org/plugins/auth_userkey
81 stars 53 forks source link

Example with java not work #77

Closed MAntonio95 closed 6 months ago

MAntonio95 commented 2 years ago

Hello, could you help me with the following problem I am trying to connect the plugin using Java, I have this example https://github.com/moodlehq/sample-ws-clients/blob/master/JAVA-REST/RestJsonMoodleClient.java but not wok wtih auth_userkey

public static void main(String[] args) throws ProtocolException, IOException {

    /// NEED TO BE CHANGED
    String token = "5c8f98ad33e867ff524096c8a93";
    String domainName = "http://localhost/examenesmor";

    /// REST RETURNED VALUES FORMAT
    String restformat = "json"; //Also possible in Moodle 2.2 and later: 'json'
    //Setting it to 'json' will fail all calls on earlier Moodle version
    if (restformat.equals("json")) {
        restformat = "&moodlewsrestformat=json";
    } else {
        restformat = "";
    }

    /// PARAMETERS - NEED TO BE CHANGED IF YOU CALL A DIFFERENT FUNCTION
    String functionName = "auth_userkey_request_login_url";
    String urlParameters = "user[0][username]=" + URLEncoder.encode("sistemasadmin", "UTF-8");

    /// REST CALL
    // Send request
    String serverurl = domainName + "/webservice/rest/server.php" + "?wstoken=" + token + "&wsfunction=" + functionName + restformat;
    System.out.println(serverurl);
    HttpURLConnection con = (HttpURLConnection) new URL(serverurl).openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setDoInput(true);
    con.setInstanceFollowRedirects(false);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    //Get Response
    InputStream is = con.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuilder response = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    rd.close();
    System.out.println(response.toString());
}

and I get this exception

{"exception":"invalid_parameter_exception","errorcode":"invalidparameter","message":"Valor de par\u00e1metro inv\u00e1lido detectado"}

dmitriim commented 2 years ago

Have you tried changing
String urlParameters = "user[0][username]=" + URLEncoder.encode("sistemasadmin", "UTF-8");

to

String urlParameters = "user[username]=" + URLEncoder.encode("sistemasadmin", "UTF-8");

dmitriim commented 6 months ago

No actions from a original author for about two years, Closing this one off as part of clean up.