Google OAuth2 Service Account Access Token

Saturday, May 3, 2014

I'm trying to generate an access token using Google OAuth2 on the server. My code looking something like this:

var claimbuilder = new Stub.Jwt.ClaimsBuilder();
claimbuilder.Add("iss", "");
claimbuilder.Add("scope", "");
claimbuilder.Add("aud", "");

string head = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";

var jwt = String.Format("{0}.{1}", head, claimbuilder.ClaimSetBase64);

//var sigbytes = Stub.Jwt.Utility.getBytes(jwt);
byte[] sigbytes = null;

using (FileStream reader = new FileStream(@".....a0dd7-privatekey.p12", FileMode.Open, FileAccess.Read))
sigbytes = new byte[(int)reader.Length];
reader.Read(sigbytes, 0, (int)reader.Length);

var token = new Stub.Jwt.JsonWebToken();
var jwtresult = token.Generate(head, claimbuilder.ClaimSet, sigbytes);


OAuth.Response resp = new OAuth.Response();
OAuth.Request auth = new OAuth.Request("");
auth.AddPostVar("grant_type", HttpUtility.UrlEncode("authorization_code")); // "authorization_code");
auth.AddPostVar("code", jwt);
auth.AddPostVar("client_id", ".....ypTmu1BBVSo");
auth.AddPostVar("client_secret", "notasecret");


I'm getting a 401 Unauthorized error, specifically:

Web Exception Message: The remote server returned an error: (401) Unauthorized.
Web Exception HelpLink:
"error" : "invalid_client"

So what am I doing wrong? I'm close, but stuck!