web-api
  1. web-api-google-authentication

Google Authentication - (Web API Social Authentication)

Google Authentication is a popular method for allowing users to sign in to your web application using their Google credentials. In Web API, implementing Google Authentication is simple with the use of OAuth middleware. This page explains how to implement Google Authentication in a Web API application.

Syntax

To enable Google Authentication in a Web API application, you will need to install the appropriate NuGet packages, configure the authentication middleware, and add the [Authorize] attribute to controller actions or methods. Here is an example of how to enable Google Authentication in a Web API application:

services.AddAuthentication(options =>
{
  options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
  options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
  options.TokenValidationParameters = new TokenValidationParameters
  {
    ValidateIssuer = true,
    ValidateAudience = true,
    ValidateLifetime = true,
    ValidateIssuerSigningKey = true,
    ValidIssuer = Configuration["Jwt:Issuer"],
    ValidAudience = Configuration["Jwt:Audience"],
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
  };
})
.AddGoogle(options =>
{
  options.ClientId = Configuration["Google:ClientId"];
  options.ClientSecret = Configuration["Google:ClientSecret"];
});

Example

Here is an example of how to implement Google Authentication in a Web API application:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace MyNamespace
{
  [Authorize]
  [ApiController]
  [Route("[controller]")]
  public class MyController : ControllerBase
  {
    [HttpGet]
    public IActionResult Get()
    {
      var user = HttpContext.User.Identity.Name;
      return Ok($"Hello, {user}!");
    }
  }
}

Output

When a user clicks the "Sign in with Google" button on your web application, they will be redirected to the Google login page. After they sign in with their Google credentials, they will be redirected back to your web application and their Google user identity will be stored in a server-side cookie. When the user makes a request to a controller action or method decorated with the [Authorize] attribute, the authentication middleware will check for the cookie and authorize the user if the Google credentials are valid. The action or method will then

Published on: