WSO2 Identity Server - Oauth 2.0 - Abmeldebeispiel für Java

Ich habe eine Java-basierte Abmeldungsroutine (Token-Widerruf) für einen Oauth2-Authentifizierungsablauf geschrieben. Siehe unten die Code-Implementierung gemäß den Anweisungen des cURL-Protokolls im beschriebenen Handbuch Hie]. Der Programmcode wird kompiliert und funktioniert ohne Fehlermeldung, aber nach dem Abmelden bleiben die Benutzerkonten unter der WSO2-Dashboard-Abfrage weiterhin verbunden.

Siehe unter der Servlet-Klasse, die die Abmeldefunktion auslöst:

class SignoffServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {

                try{
       String accessToken = (String) req.getSession().getAttribute("access_token"); 
       System.out.println("Start Logoff processing for revoke of the token: " + accessToken);
           URL url = new URL (Oauth2Server + "/oauth2/revoke?token="+accessToken); 
       HttpURLConnection connection = (HttpURLConnection) url.openConnection();
       // new encode with Apache codec (for Java8 use native lib) 
       String userCredentials = clientId + ":" + clientSecret;
       String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
       connection.setRequestProperty ("Authorization", basicAuth);
       connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");    
       connection.addRequestProperty("token", accessToken); 
       connection.addRequestProperty("token_type_hint", "access_token");
       //connection.setRequestProperty("token", accessToken); 
       // connection.setRequestProperty("token_type_hint", "access_token");
                   connection.setRequestMethod("POST");
                   connection.setDoOutput(true);
                   InputStream content = (InputStream)connection.getInputStream();
                   BufferedReader in   = 
                     new BufferedReader (new InputStreamReader (content));
                     String line;
                     while ((line = in.readLine()) != null) {
                         System.out.println(line);
                         System.out.println("Logoff finished sucessfully");
                         }
                    } catch(Exception e) {
                      System.out.println("Logoff failed, error cause: " + e.toString());
                      e.printStackTrace();
                    }
    System.out.println("Logoff finished sucessfully");
    // return the json of the user's basic info
    String html_header = "<html><body>"; 
    String myjson = "<br>Logoff completed sucessfully"; 
    myjson += "<br><br><b><a href='./index.html'>Back to login page</a></b><br>";
    String html_footer = "</body></html>";  
    String mypage = html_header + myjson + html_footer; 
    resp.setContentType("text/html");
    resp.getWriter().println(myjson);
}   

}

Willkommen sind Hinweise zur Änderung des Java-Codes, um die Abmeldefunktion für Oauth 2.0 zu aktivieren.

Danke für detaillierte Erklärungen zum Unterschied zwischen Autorisierung und Authentifizierung in Oauth2. Siehe unten den Code, der das gültige Oauth2-Token widerrufen kann:

class SignoffServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {

    String outputl = "";        
                try{
       String accessToken = (String) req.getSession().getAttribute("access_token"); 
           // testing .. inhibu acivate this line:  // revoke accessToken = "abc";             
       System.out.println("Start Logoff processing for revoke of the token: " + accessToken);
           // URL url = new URL (Oauth2Server + "/oauth2/revoke?token="+accessToken); 
           // URL url = new URL (Oauth2Server + "/oauth2endpoints/revoke");
       URL url = new URL (Oauth2Server + "/oauth2/revoke");
       HttpURLConnection connection = (HttpURLConnection) url.openConnection();
       connection.setRequestMethod("POST");
       connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
       // new encode with Apache codec (for Java8 use native lib) 
       String userCredentials = clientId + ":" + clientSecret;
       String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
       basicAuth = basicAuth.replace("\\r", "");
       basicAuth = basicAuth.replace("\\n", "");
                   connection.setRequestProperty ("Authorization", basicAuth);
       connection.setUseCaches(false);
       connection.setDoInput(true);
       connection.setDoOutput(true);
       // send data     
           // String str =  "{\"token\": \"" + accessToken + "\",\"token_type_hint\":\"access_token\"}";
       // example of JSON string  "{\"x\": \"val1\",\"y\":\"val2\"}";
       //byte[] outputInBytes = str.getBytes("UTF-8");
       //OutputStream os = connection.getOutputStream();
       //os.write( outputInBytes );    
       // os.close();
       //send request 
       DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); 
       wr.writeBytes("token=" + accessToken); 
       wr.flush(); 
       wr.close(); 
        // end of new method 
                   InputStream content = (InputStream)connection.getInputStream();
                   BufferedReader in   = 
                     new BufferedReader (new InputStreamReader (content));
                     String line;
                     while ((line = in.readLine()) != null) {
                         // System.out.println(line); // for debug only 
             outputl += line; 
                         }
                    } catch(Exception e) {
                      System.out.println("Logoff failed, error cause: " + e.toString());
                      e.printStackTrace();
                    }
    System.out.println("Logoff finished successfully");
    // return the json of the user's basic info
    // customized Apache HTTP GET with header - Claude, 27 August 2015 reading user information 
    // ===============================================================================================
                String tokeninfo = ""; 
    String infourl = Oauth2Server + "/oauth2/userinfo?schema=openid";
                StringBuilder infobody = new StringBuilder();
                DefaultHttpClient infohttpclient = new DefaultHttpClient(); // create new httpClient 
                HttpGet infohttpGet = new HttpGet(infourl); // create new httpGet object
                // get some info about the user with the access token
    String currentToken = (String) req.getSession().getAttribute("access_token");
                String bearer = "Bearer " + currentToken.toString(); 
        infohttpGet.setHeader("Authorization", bearer);
    try {
           HttpResponse response = infohttpclient.execute(infohttpGet); // execute httpGet
           StatusLine statusLine = response.getStatusLine();
                   int statusCode = statusLine.getStatusCode();
                   if (statusCode == HttpStatus.SC_OK) {
                       System.out.println(statusLine);
                       infobody.append(statusLine + "\n");
                       HttpEntity e = response.getEntity();
                       String entity = EntityUtils.toString(e);
                       infobody.append(entity);
                       } else {
                              infobody.append(statusLine + "\n");
                              // System.out.println(statusLine);
                              }
                    } catch (ClientProtocolException e) {
                      e.printStackTrace();
                    } catch (IOException e) {
                      e.printStackTrace();
                    } finally {
                      tokeninfo = infobody.toString();  
                      infohttpGet.releaseConnection(); // stop connection
                    }
    // User info lookup is done fetching current log status of the token 
    if (tokeninfo.startsWith("HTTP/1.1 400 Bad Request")) { 
        tokeninfo = "Token " + currentToken + " was revoked";               
        };  
    String html_header = "<html><body>"; 
    String myjson = "<br>Logoff completed successfully"; 
    myjson += "<br>Current Userinfo and Token Status";
    myjson += "<br>" + tokeninfo + "<br>"; 
    myjson += "<br><br><b><a href='./index.html'>Back to login page</a></b><br>";
    String html_footer = "</body></html>";  
    String mypage = html_header + myjson + html_footer; 
    resp.setContentType("text/html");
    resp.getWriter().println(myjson);
    // to print signoff screen for debug purpose
    // resp.getWriter().println(outputl);
}   

}

Antworten auf die Frage(2)

Ihre Antwort auf die Frage