Get a user's profile using AspNet.Security.OpenIdConnect.Server

773 views Asked by At

recently I've spent some time digging into AspNet.Security.OpenIdConnect.Server. I use MVC sample as a code base for my client/server apps.

The thing I need to implement now is obtaining a user's profile info from an external provider (Google) and saving the info into the server's database.

What is the right place for getting and saving a profile's info and a proper way to implement it?

1

There are 1 answers

0
Kévin Chalet On BEST ANSWER

Note: since ASOS (AspNet.Security.OpenIdConnect.Server) only handles the OAuth2/OpenID Connect server part, it's actually not involved in the authentication part, and thus doesn't directly deal with the external providers you configure.

To achieve what you want, the best approach is to configure the Google middleware to extract more information from the user object returned in the user profile response and to persist them in the authentication cookie so you can later retrieve them in your application code.

app.UseGoogleAuthentication(options => {
    options.ClientId = "client_id";
    options.ClientSecret = "client_secret";

    options.Events = new OAuthEvents {
        OnCreatingTicket = context => {
            // Extract the "language" property from the JSON payload returned by
            // the user profile endpoint and add a new "urn:language" claim.
            var language = context.User.Value<string>("language");
            context.Identity.AddClaim(new Claim("urn:language", language));

            return Task.FromResult(0);
        }
    };
});

You can retrieve the urn:language claim from the User instance

If the response doesn't include the data you need, nothing prevents you from using context.Backchannel to make another HTTP call to retrieve more data from a different Google endpoint.