Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add google authentication to **Existing** .net core 2 web api project

TL;DR - how to add authentication to an existing default core 2 web api project that was started without auth.

Details - I've got an existing .net core 2 web api project with no authentication configured and I'm using entity framework core.

It was opened like -

PIC 1 - No Auth Selected

No Auth Selected

I'd like to add Google authentication to my existing project as if it were opened with

PIC 2 - Individual user accounts selected

Individual User Accounts Selected

but I can't find any resource regarding adding those capabilities + scaffolding and migrations - all I can find are links regarding upgrading from core v1 to 2.

  • Migrating Authentication and Identity to ASP.NET Core 2.0
  • Configuring Google authentication in ASP.NET Core

any ideas?

thanks!

like image 514
JanivZ Avatar asked Oct 12 '17 00:10

JanivZ


People also ask

How do I add authentication to .NET core?

Authentication schemes are specified by registering authentication services in Startup. ConfigureServices : By calling a scheme-specific extension method after a call to AddAuthentication (such as AddJwtBearer or AddCookie, for example). These extension methods use AuthenticationBuilder.

How do I add authentication to Web API?

In IIS Manager, go to Features View, select Authentication, and enable Basic authentication. In your Web API project, add the [Authorize] attribute for any controller actions that need authentication. A client authenticates itself by setting the Authorization header in the request.


1 Answers

Add packages

Microsoft.AspNetCore.Identity
Microsoft.AspNetCore.Identity.EntityFrameworkCore
Microsoft.AspNetCore.Authentication.Google

Then in Startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity<IdentityUser, IdentityRole>();
    services.AddAuthentication(
            v => {
                v.DefaultAuthenticateScheme = GoogleDefaults.AuthenticationScheme;
                v.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
            }).AddGoogle(googleOptions =>
            {
                googleOptions.ClientId = "CLIENT ID";
                googleOptions.ClientSecret = "CLIENT SECRET";
            });
    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication()
       .UseMvc();
}

A minimal working example here: https://github.com/mjrmua/Asp.net-Core-2.0-google-authentication-example

like image 144
Murray Avatar answered Oct 20 '22 11:10

Murray