WSO2 Identity Server - Oauth 2.0 - Sign-off Example for Java

与世无争的帅哥 提交于 2019-11-30 21:10:41

问题


I wrote a Java based sign-off routine (token revocation) for an Oauth2 authentication flow. See below the code implementation following the cURL protocol instructions in the manual described [ here ]. The program code compiles and works without error message, but after the log-off the user accounts still remains in a connected state under the WSO2 dashboard query.

See below the Servlet class that triggers the log-off function:

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);
}   

}

Advice about what to change in the Java code to activate the sign-off function for Oauth 2.0 is welcome.

Thanks for detailed explanations about the difference between authorization and authentication in Oauth2. See below the code that is able to revoke the valid Oauth2 token:

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);
}   

}


回答1:


Above doc has been mentioned the way to revoke the access token.Access token revoking and sign-off from OAuth2 authorization server are two different process. As an example; in Facebook, you can revoke the access token which are given for different applications. But it does not mean that you are sign-off from FB or any other application which you already login.

OAuth2 is not an authentication mechanism. It is authorization framework. It does not contain standard way to sign-off from authorization sever. However, there is some custom way which you can use to sign-off (terminate the SSO session in WSO2IS) from WSO2IS which can be used. But, it must be done using the end user's browser (not using the back channel) by calling following url. Please check last part of this for more details

https://localhost:9443/commonauth?commonAuthLogout=true&type=oidc2&sessionDataKey=7fa50562-2d0f-4234-8e39-8a7271b9b273&commonAuthCallerPath=http://localhost:8080/openidconnect/oauth2client&relyingParty=OpenidConnectWebapp


来源:https://stackoverflow.com/questions/32337588/wso2-identity-server-oauth-2-0-sign-off-example-for-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!