AspNetCore WebAPI - Google Authentication
More and more projects have sections secured by Google, Twitter or Microsoft identities.
For example, for Google, you must create an ID and specify the return URL.
Then you must activate the Google Authentication service and secure your methods via [Authorize]
.
The first call of a secure method automatically redirects you to the Google page.
Create a Google ID
The first step is to configure Google API to create a project ID, to be used in our application:
- Go to Integrating Google Sign-In into your web app and configure a project.
- Select the OAuth authentication, using a Web server.
- Add your local URL, in the field Authorized redirect URIs:
https://localhost:5001/signin-google
(the port 5001 corresponds to the default configuration of Visual Studio: see below). - Copy the ClientID and the Client Secret generated.
More detail in the Microsoft documentation.
Once the configuration is complete, you can view or modify it via Google Console.
Enable WebAPIs security
In your ASP.NET Core WebAPI project, add the services Identity, Authentication and Google as follows.
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<IdentityUser, IdentityRole>();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = GoogleDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddGoogle(options =>
{
options.ClientId = "[MyGoogleClientId]";
options.ClientSecret = "[MyGoogleSecretKey]";
});
services.AddMvc();
}
Then enable authentication via UseAuthentication()
.
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
app.UseAuthentication();
app.UseMvc();
}
Finally, add the attribute [Authorize()]
to the APIs you want to secure. And start your website to call the secure API.
[HttpGet("{id}")]
[Authorize]
public ActionResult<string> Get(int id)
{
return this.User.Identity.Name;
}
Once Google has approved the authentication, you can manage your own security (roles, lifespan,…) using JWT tokens, for example.