This tool demonstrates how to get a Google OAuth2 access token using three-legged OAuth2 in an ASP.NET application.This is also known as the "authorization code grant flow". This is when your ASP.NET app acts on the behalf of a third-party user, your app must obtain the user's permission before it can make requests that access and update that third-party's confidential resources. A User access token carries a third-party's authorization to access specific resources, and this type of token is obtained through the authorization code grant flow.
@{ Layout = "~/_LayoutPage1.cshtml"; } @functions { // Exchange the authorization code for an access token returned in jsonToken. private static bool ExchangeCodeForToken(string uri, string body, Chilkat.JsonObject jsonToken) { var request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "POST"; request.Accept = "application/json"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = body.Length; using (Stream requestStream = request.GetRequestStream()) { StreamWriter writer = new StreamWriter(requestStream); writer.Write(body); writer.Close(); } var response = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { var reader = new StreamReader(responseStream); string jsonStr = reader.ReadToEnd(); reader.Close(); jsonToken.Load(jsonStr); } return jsonToken.HasMember("access_token"); } } @{ string access_token = ""; string state = ""; string redirect_uri = "https://tools.chilkat.io/google_oauth2.cshtml"; string clientId = "5332332985-rd1jebnjhob8r1hcvpim5fatmbe1ek7b.apps.googleusercontent.com"; string clientSecret = "<secret>CLIENT_SECRET</secret>"; Chilkat.JsonObject jsonAccessToken = new Chilkat.JsonObject(); // Check to see if this is our redirect containing the access token. if (!string.IsNullOrEmpty(Request.Params["state"])) { state = Request["state"]; // Make sure this is the redirect for our session. if (!state.Equals(Session["oauth2_state"])) { access_token = "invalid_state"; } else if (!string.IsNullOrEmpty(Request.Params["code"])) { string authorizationCode = Request["code"]; string bodyTemplate = "client_id={0}&client_secret={1}&code={2}&grant_type=authorization_code&redirect_uri={3}&access_type=offline"; var formUrlEncodedBody = string.Format(bodyTemplate, WebUtility.UrlEncode(clientId), WebUtility.UrlEncode(clientSecret.Replace("<secret>","").Replace("</secret>","")), WebUtility.UrlEncode(authorizationCode), WebUtility.UrlEncode(redirect_uri)); if (ExchangeCodeForToken("https://www.googleapis.com/oauth2/v4/token",formUrlEncodedBody,jsonAccessToken)) { access_token = jsonAccessToken.StringOf("access_token"); } else { access_token = "exchange_code_for_token_failed"; } } } } @{ Chilkat.HttpRequest req = new Chilkat.HttpRequest(); req.AddParam("client_id", clientId); req.AddParam("redirect_uri", redirect_uri); req.AddParam("include_granted_scopes", "true"); req.AddParam("access_type", "offline"); req.AddParam("prompt", "consent"); req.AddParam("response_type", "code"); // SPACE separated list of scopes. req.AddParam("scope", "https://www.googleapis.com/auth/drive.metadata.readonly"); string stateData = "12345678"; // Replace this with random data.. req.AddParam("state", stateData); Session["oauth2_state"] = stateData; string auth_url = "https://accounts.google.com/o/oauth2/v2/auth?" + req.GetUrlEncodedParams(); } <div class="container"> <h2>Obtain Google OAuth2 Access Token</h2> <p> This tool demonstrates how to get a Google OAuth2 access token using three-legged OAuth2 in an ASP.NET application.This is also known as the "authorization code grant flow". This is when your ASP.NET app acts on the behalf of a third-party user, your app must obtain the user's permission before it can make requests that access and update that third-party's confidential resources. A User access token carries a third-party's authorization to access specific resources, and this type of token is obtained through the authorization code grant flow. </p> <div class="panel panel-default"> <div class="panel-body"> <a href = "@auth_url" class="btn btn-primary" role="button">Begin OAuth2</a> <div><small>Note: Google will display an Unverified App warning.This is because the app is unverified, but it is an app that does nothing.After the warning, click on "Advanced", then click on "go to chilkat.io".</small></div> </div> </div> <div class="panel panel-default"> @{ if (!string.IsNullOrEmpty(access_token)) { @:<p><b>Google access token:</b> @access_token</p> } if (!string.IsNullOrEmpty(state)) { @:<p>state: @state</p> } } </div> <div class="panel panel-default"> <h2>The C# Source Code for this Page</h2> <pre> @{ Chilkat.FileAccess fac = new Chilkat.FileAccess(); string path = Server.MapPath("~/google_oauth2.cshtml"); string src = fac.ReadEntireTextFile(path, "utf-8"); Chilkat.StringBuilder sbTemp = new Chilkat.StringBuilder(); sbTemp.Append(src); sbTemp.ReplaceAllBetween("<secret>", "</secret>", "CLIENT_SECRET", false); src = sbTemp.GetAsString(); @: @src } </pre> </div> </div>