Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google OpenId Connect migration: getting the openid_id in ASP.NET app

I've gone through plenty of Google documentation and SO Q/A's but with no luck. I wonder if anyone has yet succesfully used the OpenId to OpenId Connect migration as advised by Google.

This is what we used to do:

IAuthenticationResponse response = _openid.GetResponse();
if (response != null) {
   //omitted for brevity       
} else {
   IAuthenticationRequest req = _openid.CreateRequest("https://www.google.com/accounts/o8/id");
   req.AddExtension(new ClaimsRequest
                    {
                        Country = DemandLevel.Request,
                        Email = DemandLevel.Request,
                        Gender = DemandLevel.Require,
                        PostalCode = DemandLevel.Require,
                        TimeZone = DemandLevel.Require
                    });
   req.RedirectToProvider();
}

That was done using a version of DotNetOpenAuth that dates back a few years. Because Google has deprecated OpenId authentication we are trying to move over to OpenID Connect. The key question here is: can I somehow get my hands on the OpenId identifier (in the form of https://www.google.com/accounts/o8/id?id=xyz) using the latest version of DotNetOpenAuth library or by any other means?

I have tried the latest DotNetOpenAuth and I can get it to work but it gives me a new Id (this was expected). I have also tried the Javascript way by using this URL (line breaks for readibility):

https://accounts.google.com/o/oauth2/auth?
    scope=openid%20profile%20email
    &openid.realm=http://localhost/palkkac/
    &client_id=//here is the client id I created in google developer console
    &redirect_uri=http://localhost/palkkac/someaspxpagehere
    &response_type=id_token%20token

I checked (using Fiddler) the realm value that we currently send using the old DotNetOpenAuth code and it is http://localhost/palkkac/. I've put the same realm in the url above. The redirect url starts with the realm value but it is not entirely the same.

When I redirect to a simple page that parses the id_token and decrypts it (using the https://www.googleapis.com/oauth2/v1/tokeninfo?id_token=zyx endpoint) I get this:

audience    "client id is here"
email   "[email protected]"
expires_in  3597
issued_at   //some numbers here
issued_to   "client id is here"
issuer  "accounts.google.com"
user_id     "here is a sequence of numbers, my id in the OpenID Connect format that is"
verified_email  true

So there is no sign of the openid_id field that you would expect to find here, though the whole structure of the message seems different from the Google docs, there is no field titled sub, for example. I wonder if I'm actually using the wrong endpoint, parameters or something?

What I have been reading is the migration guide: https://developers.google.com/accounts/docs/OpenID. I skipped step 2 because it seemed like an optional step. In step 3 the field openid_id is discussed and I would like to get that to work as a proof-of-concept first.

We registered the app on Google in order to create the client id etc. There are now also numerous allowed redirect url's as well as javascript origins listed in the Google dev console. Let me know if those might mess up the system and I'll post them here for review.

Side note: we are supposed to be moving our app behind a strictly firewalled environment where we would need to open ports in order to do this on the server side. Therefore, a client-side Javascript solution to access Google combined with HTTPS and redirecting the result to the server would be prefered (unless there are other issues that speak against this).

There are other resources on SO regarding this same issue, although all of these seem to use different libraries on the server side to do the job and nobody seems to have made any attempts at using Javascript:

  • Here (https://stackoverflow.com/questions/22842475/migrating-google-openid-to-openid-connect-openid-id-does-not-match) I think the problem was resolved by setting the realm to be the same as in the old OpenId2.0 flow. This does not seem to work in my case.
  • over here the openid_id field is also missing, but the problem here is more about how to request the id_token from Google using libraries other than DotNetOpenAuth.
  • and in here there seem to be similar problems getting Google to return the openid_id field.
like image 205
mikkark Avatar asked Oct 31 '22 14:10

mikkark


1 Answers

You can use the GoogleAuthentication owin middleware.

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
{
    SignInAsAuthenticationType = signAs,
    AuthenticationType = "Google",
    ClientId = "xxx.apps.googleusercontent.com",
    ClientSecret = "xx",
    CallbackPath = PathString.FromUriComponent("/oauth2callback"),
    Provider = new GoogleOAuth2AuthenticationProvider
    {
        OnApplyRedirect = context =>
        {
            context.Response.Redirect(context.RedirectUri + "&openid.realm=https://mydomain.com/"); // DotNetOpenAuth by default add a trailing slash, it must be exactly the same as before
        }
    },
    BackchannelHttpHandler = new MyWebRequestHandler()
}

Then, add a new class called MyWebRequestHandler:

public class MyWebRequestHandler : WebRequestHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var httpResponse = await base.SendAsync(request, cancellationToken);
            if (request.RequestUri == new Uri("https://www.googleapis.com/plus/v1/people/me")) return httpResponse;

            var configuration = await OpenIdConnectConfigurationRetriever.GetAsync("https://accounts.google.com/.well-known/openid-configuration", cancellationToken); // read the configuration to get the signing tokens (todo should be cached or hard coded)

            // google is unclear as the openid_id is not in the access_token but in the id_token
            // as the middleware dot not expose the id_token we need to parse it again
            var jwt = httpResponse.Content.ReadAsStringAsync().Result;
            JObject response = JObject.Parse(jwt);
            string idToken = response.Value<string>((object)"id_token"); 

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

            try
            {
                SecurityToken token;
                var claims = tokenHandler.ValidateToken(idToken, new TokenValidationParameters()
                {
                    ValidAudience = "xxx.apps.googleusercontent.com",
                    ValidIssuer = "accounts.google.com",
                    IssuerSigningTokens = configuration.SigningTokens
                }, out token);

                var claim = claims.FindFirst("openid_id");
                // claim.Value will contain the old openid identifier
                if (claim != null) Debug.WriteLine(claim.Value);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            return httpResponse;
        }
    }

If like me you found this not really straightforward, please help by upvoting this issue https://katanaproject.codeplex.com/workitem/359

like image 111
cortex Avatar answered Nov 09 '22 09:11

cortex