Google Authentication in .Net Core Web API

In this article, we will learn how to authenticate API from direct access. We can secure our app with google authentication.

Create google OAuth credentials

We will do some necessary and simple steps in your Google account in order to get the OAuth key and enable the login function for your app.

we need to ClientId and Client Secret in our application for Google authentication. Open the below link and login with your google account credential.

Once you logged in create a new project if you don’t have.

Now you can give appropriate name of project, and click on create button.

Next go to Library tab from the left menu. Now you search for Google+ API and click on that. And then click the ENABLE button to enable this service.

Next go to the Credential tab and click on Create Credential button it will show dropdown list then select OAuth Client ID option.

Now you have to configure Authorised redirect URIs. This URI at which our application is hosted and this path signin-google. Then click on create button.

Now, you get Client ID & Client Secret. Now let’s  started the code.

Here we  authenticate getStudent API to direct access you need to google sign in to use this API.

First Add required Packages by clicking Manage Nuget Packages for solution of tool menu. The list is below:

Add migration and create table. Create  Student.cs class

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;


namespace APIWithGooglelink.Student
{
    public class Students
    {

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string StudentName { get; set; }
        public string Address { get; set; }
        public string Gender { get; set; }
        public int Class { get; set; }
        public string Grade { get; set; }

    }
}

Now create Dbcontext class StudentDbContext.cs.

using Microsoft.EntityFrameworkCore;
using System;


namespace APIWithGooglelink.Student
{
    public class StudentsDbContext : DbContext
    {
        public StudentsDbContext(DbContextOptions options) : base(options)
        {
        }
        public DbSet<Students> Students { get; set; }
    }
}

Now open the package manager console & type add-migration initial

after that run the command: update-database

IStudentRepository.cs

using APIWithGooglelink.Student;
using System;
using System.Collections.Generic;

namespace APIWithGooglelink.repository
{
    public interface IStudentrepository 
    {
        IEnumerable<Students> GetStudent();
        Students GetStudent(int id);
    }
}

StudentRepository.cs

using APIWithGooglelink.Student;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APIWithGooglelink.repository
{
    public class StudentRepository : IStudentrepository
    {
        protected StudentsDbContext Context;
        public StudentRepository(StudentsDbContext context)
        {
            Context = context;
        }
        public IEnumerable<Students> GetStudent()
        {
            return Context.Students.AsNoTracking().ToList();
        }
        public Students GetStudent(int id)
        {
            return Context.Students.AsNoTracking().FirstOrDefault(x => x.Id == id);
        }
    }
}

Startup.cs

using APIWithGooglelink.repository;
using APIWithGooglelink.Student;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace APIWithGooglelink
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

      
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            //services.AddSwaggerGen(c =>
            //{
            //    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Crud", Version = "v1" });
                
            //});
            services.AddDbContext<StudentsDbContext>(item => item.UseSqlServer(Configuration.GetConnectionString("SqlConnection")));
            services.AddScoped<IStudentrepository, StudentRepository>();

           
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
            })
            .AddCookie()
                 .AddGoogle(GoogleDefaults.AuthenticationScheme, opts =>
            {
                opts.ClientId = "Your ClientId.............";
                opts.ClientSecret = "Your ClientSecret..........";
            });
           
            services.AddCors();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //app.UseSwagger();
                //app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "APIWithGooglelink v1"));
            }
          

            app.UseCors(options =>
              options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            app.UseCookiePolicy();

            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Here in Startup.cs file register service for google authentication and provide client Id & client secret which we have generated above.

StudentController.cs

using APIWithGooglelink.repository;
using APIWithGooglelink.Student;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace APIWithGooglelink.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class HomeController : Controller
    {
        private readonly IStudentrepository _studentRepository;

        public HomeController(IStudentrepository employeeRepository)
        {
            _studentRepository = employeeRepository;
        }
        
        [HttpGet("GetStudent")]
        public IEnumerable<StudentDTO> GetStudent()
        {

            return _studentRepository.GetStudent().Select(x => new StudentDTO
            {
                Id = x.Id,
                StudentName = x.StudentName,
                Address = x.Address,
                Gender = x.Gender,
                Class = x.Class,
                Grade = x.Grade
            });
        }

        [HttpGet("GetStudent/{id}")]
        public ActionResult<StudentDTO> GetStudent(int id)
        {
            Students std = _studentRepository.GetStudent(id);
            if (std is null) return NotFound();
            return new StudentDTO
            {
                Id = std.Id,
                StudentName = std.StudentName,
                Address = std.Address,
                Gender = std.Gender,
                Class = std.Class,
                Grade = std.Grade
            };
        }
    }
}

We need to add authorize attribute either on controller for all method authentication or specific action method.

OUTPUT:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories