OAuth Client (2.2+ only)

OAuth Client is the client side implementation of the OAuth protocol. We support both OAuth1 and OAuth2.


To use the OAuth2 authoriziation, you first need to set up your app key/app secrets, authorization/token endpoints and provide your redirect uri.
#include "cpprest/http_listener.h"
#include "cpprest/http_client.h"

using namespace web::http;
using namespace web::http::client;
using namespace web::http::oauth2::experimental;

utility::string_t redirect_uri(U("http://localhost:5001"));
oauth2_config m_oauth2_config(U("000000004C11C831"), /* Your live App key*/
            U("r4zFBhg1qP5AvMZBLyFlMFdhAT1mkg1m"), /* Your live App secret*/
            U("https://login.live.com/oauth20_authorize.srf"), /* Authorization endpoint*/
            U("https://login.live.com/oauth20_token.srf"), /* Token endpoint */
            redirect_uri); /* Redirect URI */

If the server requires you to provide the access scope, you can use the set_scope(utility::string_t scope) function.
m_oauth2_config.set_scope(U("wl.basic wl.skydrive"));

Now, you need to use function build_authorization_uri(bool generate_state) to get the authorization uri.
In this function, if you set generate_state parameter as true, a new random state string is generated.
auto auth_uri = m_oauth2_config.build_authorization_uri(false);  /* Get the authorization uri */

In this example, the uri is https://login.live.com/oauth20_authorize.srf?response_type=code&client_id=000000004C11C831&redirect_uri=http://localhost:5001&state=&scope=wl.basic%20wl.skydrive

Open the web browser, type in this uri and login to authorize the access. Please view our sample to get more details how to automatically open the web browser.

To successfully receive the access token, you need to set up a http_listener to listen on the redirect_uri you provided and capture the access token by using token_from_redirected_uri().

http_listener m_listener(redirect_uri);

m_listener.support([&](http_request request) -> void
     m_oauth2_config.token_from_redirected_uri(request.request_uri()).then([&]() -> void
          auto token = m_oauth2_config.token().access_token(); // Get the access token
     request.reply(status_codes::OK, U("Ok."));

After you successfully get the access token, you can pass this m_oauth2_config to the http_client_config::set_oauth2(), construct http_client with this http_client_config then all the http requests by this client are OAuth2 authenticated.
http_client_config http_config;
http_client m_live_client (U("https://apis.live.net/v5.0/"), http_config);
m_live_client.request(methods::GET, U("me/skydrive/my_photos")).wait();

Last edited Aug 26, 2014 at 7:38 PM by zhelu, version 8