Unable to get authorization token (VK API)

I'm learning how to work with the VK API. I use HttpClient (Apache). Faced with the difficulty of authorization - I can't programmatically get a token.

Registered a Standalone application, generated a request for the server:

String url = "https://oauth.vk.com/authorize?client_id=IDHERE&display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=friends,groups,offline&response_type=token&v=5.44";

When using queries GET/POST, in the response, I get the code of the page with scripts. If I enter the same line in the browser window with my hands, I get a transition to the page specified in the request, and in the URL I have the token that I need so much, vida:

https://oauth.vk.com/blank.html#access_token=tokenHere1&expires_in=0&user_id=idHere

The code that sends the GET request:

URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", USER_AGENT);
    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to Url : " + url);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        response.append(inputLine);
    }
    in.close();

I tried both GET - and POST-requests, caught cookies - to no avail.
Tell me, how can I get a token from the server response, or from the browser URL?

Author: Артём Ионаш, 2016-02-06

2 answers

With authorization Standalone the VKontakte application is being redirected to the address "oauth.vk.com/blank.html" and the token is contained in the address bar. You can pull it out programmatically only in a web component over which you have control-for example, in the Electron application. This is not possible by standard means due to the security policy of browsers – the document is located in the vk domain, and any of your scripts do not have access to it.

If you all if you want to try to log in to the VK completely programmatically and give permission to the application, you can try using yes at least curl and correctly process the resulting HTML. The &display=mobile parameter in the initial authorization link can help reduce the number of scripts.

 2
Author: Sergiks, 2016-02-06 13:17:45

There is a solution. Apache httpCient-does not allow you to perform authorization operations on VKontakte, like a normal browser.

But the problem is solved through the Selenium Web Driver-headless browser based on PhantomJS. All operations are performed as in a normal browser, but through javascript with access to html elements. After forwarding, extract your token from the response URL.

 0
Author: Zon, 2016-10-31 15:12:48