Как пройти аутентификацию на Sharepoint онлайн для вызовов API - PullRequest
0 голосов
/ 29 апреля 2019

Я хочу пройти проверку подлинности, используя область «учетные данные клиента». Я создал основной код, чтобы получить его, используя идентификатор клиента и секрет. Я могу получить токен, но затем получаю следующий ответ:

401-Unauthorized
{"error_description":"Invalid issuer or signature."}

Я чувствую, что токен, который я получаю, неверен (возможно, я получаю токен из неверного URL). Я использую правильный URL?

public class SharePointTest {

private static String URL_TOKEN = "https://login.microsoftonline.com/<tenant id>/oauth2/v2.0/token";

private static String CLIENT_ID = "";
private static String CLIENT_SECRET="";
Private static String TOKEN="";

public String getToken(){
    try{
        String url = URL_TOKEN;
        String text = "client_id="+CLIENT_ID +
                        "&scope=https://graph.microsoft.com/.default" +
                            "&client_secret="+CLIENT_SECRET +
                                "&grant_type=client_credentials";
        System.out.println(url);
        URL u = new URL(url);
        URLConnection conn = u.openConnection();
        HttpURLConnection http = (HttpURLConnection) conn;
        http.setRequestMethod("POST");
        http.setDoOutput(true);
        http.setDoInput(true);
        http.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        http.addRequestProperty("Host", "login.microsoftonline.com");
        http.addRequestProperty("Accept", "application/xml");
        http.connect();

        OutputStream out = http.getOutputStream();
        if(!(send(out, text))){
            return null;
        }

        if(http.getResponseCode() == 200){
            InputStream in = http.getInputStream();
            TOKEN=read(in);
        }else{
            System.out.println(http.getResponseCode()+"-"+http.getResponseMessage());
            InputStream in = http.getErrorStream();
            System.out.println(read(in));
            return null;
        }

    }catch(JSONException e){
        System.out.println("SendJSON (JSONException):"+e.getMessage());
    }catch(MalformedURLException e) {
        System.out.println("SendJSON (MalformedURLException):"+e.getMessage());
    }catch(IOException e) {
        System.out.println("SendJSON (IOException):"+e.getMessage());
    }
    return null;
}

private String read (InputStream in){
    try {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];

        for (int n; (n = in.read(b)) != -1;) {
            out.append(new String(b, 0, n));
        }

        return out.toString();
    }catch(IOException e) {
        System.out.println("Read (IOException):"+e.getMessage());
    }
    return null;
}

private Boolean send(OutputStream out, String s) {
    try {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
        writer.write(s);
        writer.flush();
        writer.close();
        out.close();
        return true;
    }catch(IOException e) {
        System.out.println("Send (IOException):"+e.getMessage());
    }
    return false;
}

public static void main(String[] args){
    SharePointTest t = new SharePointTest();
    t.getToken();
}
}

Вот функция (вызов API), которая возвращает ошибку:

public String getList() {

    try {
        String SITE = "https://<tenant>.sharepoint.com";
        String token = TOKEN;
        if(token != null){
            String url = SITE+URL_LIST;
            System.out.println(url);
            URL u = new URL(url);
            URLConnection conn = u.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;
            http.setRequestMethod("GET");
            http.setDoOutput(false);
            http.setDoInput(true);
            http.addRequestProperty("Authorization", "Bearer "+token);
            http.addRequestProperty("Accept", "application/json;odata=verbose");
            http.connect();

            if(http.getResponseCode() == 200){
                InputStream in = http.getInputStream();
                System.out.println(read(in));
            }else{
                System.out.println(http.getResponseCode()+"-"+http.getResponseMessage());
                InputStream in = http.getErrorStream();
                System.out.println(read(in));
                return null;
            }
        }
        System.out.println("no token");

    }catch(JSONException e){
        System.out.println("SendJSON (JSONException):"+e.getMessage());
    }catch(MalformedURLException e) {
        System.out.println("SendJSON (MalformedURLException):"+e.getMessage());
    }catch(IOException e) {
        System.out.println("SendJSON (IOException):"+e.getMessage());
    }
    return null;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...