尝试从Azure AD

时间:2017-12-22 09:52:10

标签: java azure https azure-active-directory

我正在为我的Web应用程序实现azure并尝试通过openId connect tutorial获取访问令牌

https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code

当我请求获取访问令牌时,我总是得到错误的请求400

请求获取访问令牌:

  

POST / {tenant} / oauth2 / token HTTP / 1.1

     

主持人:https://login.microsoftonline.com

     

内容类型:application / x-www-form-urlencoded

     

grant_type = authorization_code

     

&安培; CLIENT_ID = 2d4d11a2-f814-46a7-890a-274a72a7309e

     

&安培;代码= AwABAAAAvPM1KaPl .......

     

&安培; REDIRECT_URI = HTTPS%3A%2F%2Flocalhost%2Fmyapp%2F

     

&安培;资源= HTTPS%3A%2F%2Fservice.contoso.com%2F

     

&安培; client_secret = P @ ssw0rd

这是我的代码:

public static String post( String endpoint,
        Map<String, String> params) {//YD
    StringBuffer paramString = new StringBuffer("");
    //if(!Utilities.checkInternetConnection(context)){
    //  return XMLHandler.getXMLForErrorCode(context, JSONHandler.ERROR_CODE_INTERNET_CONNECTION);
    //}
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    StringBuffer tempBuffer = new StringBuffer("");
    String paramval;
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        if (param != null) {
            if (paramString.length() > 0) {
                paramString.append("&");
            }
            System.out.println( "post key : " + param.getKey());
            String value;
            try {
                paramval = param.getValue();
                if(paramval!=null)
                    value = URLEncoder.encode(paramval, "UTF-8");
                else
                    value = "";
            } catch (UnsupportedEncodingException e) {
                value = "";
                e.printStackTrace();
            }


                paramString.append(param.getKey()).append("=")
                        .append(value);
        }
    }
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(endpoint);
        String data = "";

        try {
            // Add your data
            // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs))
            //httppost.addHeader("Host", host);
            httppost.addHeader("Content-Type",
                    "application/x-www-form-urlencoded");

            if (!paramString.equals("")) {
                if (tempBuffer.length() > 0) {
                    data = data + tempBuffer.toString();
                }
                data = data + paramString.toString();

                if (data.endsWith("&")) {
                    data = data.substring(0, data.length() - 1);
                } 

                httppost.setEntity(new ByteArrayEntity(data.getBytes()));
            }

            System.out.println( "post Stringbuffer  : " + data);

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            int statuscode = response.getStatusLine().getStatusCode();
            System.out.println("Response code : " + statuscode);
            if (statuscode != 200) {
                return null;
            }
            HttpEntity entity = response.getEntity();
            InputStream in = null;
            if (entity != null) {
                in = entity.getContent();
            }

            if (in != null) {
                StringBuilder builder = new StringBuilder();
                String line;
                try {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(in, "UTF-8"));
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                } finally {
                    in.close();
                }

                String response2 = builder.toString();

                System.out.println("response :" + response2);
                retrycount = 0;

                return response2;
            }
        }
        catch(UnknownHostException e){
            e.printStackTrace();
            return null;
        }
        catch (EOFException eof) {
            if (retrycount < max_retry) {
                eof.printStackTrace();
                post( endpoint, params);
                retrycount = 1;
            }
        } catch (Throwable th) {
            throw new IOException("Error in posting :" + th.getMessage());
        }
        retrycount = 0;
        return null;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

请帮我解决这个问题

先谢谢

2 个答案:

答案 0 :(得分:0)

您是否确保传递给/ token的重定向uri与您传递给/授权的重定向相同

我相信,如果您可以使用Postman工具测试当前客户端ID,密码和范围的OAuth验证代码流,以排除错误配置,将会有所帮助。

答案 1 :(得分:0)

请参阅以下代码以请求AuthorizationCode

public static void getAuthorizationCode() throws IOException {

        String encoding = "UTF-8";
        String params = "client_id=" + clientId 
                + "&response_type=" + reponseType
                + "&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F"
                + "&response_mode=query"
                + "&resource=https%3A%2F%2Fgraph.windows.net"
                + "&state=12345";
        String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/authorize";
        byte[] data = params.getBytes(encoding);
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        conn.setConnectTimeout(5 * 1000);
        OutputStream outStream = conn.getOutputStream();
        outStream.write(data);
        outStream.flush();
        outStream.close();
        System.out.println(conn.getResponseCode());
        System.out.println(conn.getResponseMessage());

        BufferedReader br = null;
        if (conn.getResponseCode() != 200) {
            br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
        } else {
            br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        }
        System.out.println("Response body : " + br.readLine());
    }

然后您可以使用您获得的access token获取AuthorizationCode并使用以下代码获取刷新代码。

public static void getToken(String refreshToken) throws IOException {

        String encoding = "UTF-8";
        String params = "client_id=" + clientId + "&refresh_token=" + refreshToken
                + "&grant_type=refresh_token&resource=https%3A%2F%2Fgraph.windows.net";
        String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
        byte[] data = params.getBytes(encoding);
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        conn.setConnectTimeout(5 * 1000);
        OutputStream outStream = conn.getOutputStream();
        outStream.write(data);
        outStream.flush();
        outStream.close();
        System.out.println(conn.getResponseCode());
        System.out.println(conn.getResponseMessage());

        BufferedReader br = null;
        if (conn.getResponseCode() != 200) {
            br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
        } else {
            br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        }
        System.out.println("Response body : " + br.readLine());
    }

希望它对你有所帮助。