asp.net-web-api2 OAuth 2.0 in ASP.NET Web API Configuring an OAuth Provider

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

You need to get some details from your OAuth provider of choice. We'll be looking at Google, but ASP.NET is also set up to allow out-the-box use of Twitter, Facebook and Microsoft (obviously).

You'll want to go to the Google developer console (https://console.developers.google.com/) and create a project, enable the Google+ API (for getting the user's profile info, such as their name and avatar) and create a new OAuth 2 Client ID in the “Credentials” section. The authorized JavaScript origins should be your project's root URL (e.g. https://yourapi.azurewebsites.net) and the redirect URIs need to include ASP's built-in Google callback endpoint (https://yourapi.azurewebsites.net/signin-google) as well as your callback route of choice (https://yourapi.azurewebsites.net/callback). Getting these wrong will result in Google having a hissy fit.

Back in your Visual Studio project, open App_Start > Startup.Auth.cs. Replace the commented Google section at the bottom with the code below, adding the ID and Secret from the Google Developers Console:

var googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
{
      ClientId = "YOUR ID",
      ClientSecret = "YOUR SECRET",
            Provider = new GoogleOAuth2AuthenticationProvider()
            {
                  OnAuthenticated = (context) =>
                  {
                        context.Identity.AddClaim(new Claim("urn:google:name", context.Identity.FindFirstValue(ClaimTypes.Name)));
                        context.Identity.AddClaim(new Claim("urn:google:email", context.Identity.FindFirstValue(ClaimTypes.Email)));
                        //This following line is need to retrieve the profile image
                        context.Identity.AddClaim(new Claim("urn:google:accesstoken", context.AccessToken, ClaimValueTypes.String, "Google"));
                        return System.Threading.Tasks.Task.FromResult(0);
                  }
            }
      };
app.UseGoogleAuthentication(googleAuthOptions);

These additional claims allow you to query Google for the user's profile information, such as their name and avatar URL.



Got any asp.net-web-api2 Question?