Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable external authentication in an ASP.NET Core Razor Pages project?

I have an ASP.NET Core project in Visual Studio 2017 Community on Windows 10. I am using Razor Pages as the programming model. I would like to enable external OAuth 2.0 authentication using Google or Facebook as the authentication providers so that users can sign in using their Google or Facebook accounts.

How do I enable Google or Facebook authentication in this type of project?

like image 935
Samir Avatar asked Feb 17 '18 23:02

Samir


Video Answer


1 Answers

It should be made clear that ASP.NET Core is not ASP.NET and that Razor Pages is not the traditional MVC model. If you want to know more about the difference between ASP.NET Core Razor Pages and ASP.NET Core MVC, please see this Q & A.

Overview

  • Google Authentication
    • Creating a Visual Studio project
    • Adding initial migration
    • Enabling SSL/TLS
    • Creating a Google Cloud Platform project
    • Creating OAuth credentials
    • Enabling Google+ API
    • Adding API credentials
    • Enabling Google authentication using OWIN
  • Facebook Authentication
    • Creating a Visual Studio project
    • Adding initial migration
    • Enabling SSL/TLS
    • Creating a Facebook App project
    • Enabling Facebook Login API
    • Creating OAuth credentials
    • Adding API credentials
    • Enabling Facebook authentication using OWIN

Google Authentication

The very first thing you will need is a Google account in order to consume the required API in your app. You will need to create a new Google Cloud Platform project if you don't have one already. You will then need to create OAuth credentials for the project. These credentials consist of an ID and a secret. These are API equivalents to a username and password. Google refers to these as Client ID and Client secret. Be sure to protect these, and do not share them with anyone.

Creating a Visual Studio project


When creating the project, you should select the ASP.NET Core Web Application template. On the dialog box that follows, you need to select Web Application and Individual User Accounts option in order to add ASP.NET Core Identity.

  1. Go to File > New > Project
  2. Select Installed > Visual C# > Web > ASP.NET Core Web Application
  3. Set a name and location, and then click OK.
  4. Select .NET Core, ASP.NET Core 2.0, Web Application.
  5. Click on Change Authentication, select Individual User Accounts and click OK.
  6. Click OK to create the project.

Visual Studio - New Project

Visual Studio - New ASP.NET App

Visual Studio - New ASP.NET App

Visual Studio - New ASP.NET App

Adding initial migration


Migrations are enabled by default for ASP.NET Core apps, but you need to add the initial migration and update the database using Package Manager Console.

  1. Go to Tools > NuGet Package Manager > Package Manager Console
  2. Execute Add-Migration Initial
  3. Execute Update-Database

Enabling SSL/TLS


OAuth 2.0 requires that you use a secure channel HTTPS protocol. So you need to enable SSL/TLS for your project. This is configured automatically for you if you use the Web Application template and you add ASP.NET Core Identity as explained above.

There are at least three ways to ensure that HTTPS is used in your app.

  • Using data annotation
  • Redirecting HTTP to HTTPS
  • Enforcing HTTPS globally

You can add the [RequireHttps] attribute to controllers, methods or Razor pages but you have to remember to add the attribute when you create new controllers, methods or Razor pages.

Another way is to redirect all HTTP requests to HTTPS. To do that, you can navigate to the Configure(IApplicationBuilder app, IHostingEnvironment env) method in the Startup.cs file in the root of the project and add the following Rewrite option in its body.

var options = new RewriteOptions()
    .AddRedirectToHttps();

app.UseRewriter(options);

A third way is to enforce HTTPS globally in your app. This requires all requests to us HTTPS, and therefore all HTTP requests are ignored. Requiring HTTPS globally is a security best practice and this approach is recommended.

  1. Open the Startup.cs file in the root of the project.
  2. Navigate to the ConfigureServices(IServiceCollection services) method and add the following filter in its body.

    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new RequireHttpsAttribute());
    });
    
  3. Add the Microsoft.AspNetCore.Mvc namespace.

Creating a Google Cloud Platform project


If you don't have a Google account you will need to create one. If you have never visited the Google Cloud Platform before you will be prompted to create your first project.

  1. Go to Google Cloud Platform Console.
  2. Click on the drop-down menu at the top of the page.
  3. Click on the plus icon to create a new project.
  4. Give the project a name and click Create.

Creating a Google project

Creating a Google project

Creating a Google project

Creating OAuth credentials


  1. Make sure to select the newly created project at the top of the Google Cloud Platform Console page.
  2. Under APIs and services menu on the left, click on the Credentials section.
  3. Click on the Create credentials drop-down and select OAuth client ID. You will be prompted to configure the consent screen first.
  4. Click on Configure consent screen.
  5. Provide at least a product name and click Save. You will now be allowed to continue the process of creating the OAuth credentials.
  6. Select Web application as the application type on the credentials page.
  7. Go to Visual Studio and select the project name in Solution Explorer.
  8. Go to View > Property Pages (or press Shift + F4).
  9. Copy the URL and make sure it includes the HTTPS protocol.
  10. Go back to the credentials page.
  11. In the Authorized JavaScript origin field, paste in the URL for your app. It should not end with a forward slash, such as https://localhost:44324 so make sure to remove any trailing forward slash.
  12. In the Authorized redirect URI, paste in the URL for your app and append "signin-google" at the end, such as https://localhost:44324/signin-google
  13. Click on Create button. The ID and the secret will be conveniently displayed in a modal window with copy buttons that you can click on to copy the strings.

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Enabling Google+ API


You need to enable the Google+ API for the Google Cloud Platform project.

  1. Under APIs and services menu on the left, click on the Library section.
  2. Search for "google+".
  3. Click on Google+ API in the results.
  4. Click on the Enable button.

enter image description here

enter image description here

enter image description here

Adding API credentials


Once you have enabled the API and you have the credentials, you need to add them to your app. There are two ways to do that in an ASP.NET Core project.

  • Adding API credentials by editing the JSON file
  • Adding credentials by using the command line

In an ASP.NET Core project the secrets are stored outside of the solution folder using the Secret Manager. It stores the secrets in a JSON file found in the AppData folder. You can easily locate this file by right-clicking on the project name in the Solution Explorer and then selecting Manage User Secrets.

enter image description here

enter image description here

Even though JSON files are just plain text files and can be manually edited, they are really meant for data exchange between applications and should be generated and consumed by applications. Therefore, the recommended approach is to use the command line to store the secrets. Unless you have made a mistake and need to edit it out manually. One common mistake is to set the secret as the ID and the ID as the secret. So be sure to paste the correct string when you copy and paste from the credentials page.

You need to open a command line window at the root of the project or the solution in order to successfully execute the following commands. The easiest way is to right-click on the project name in Solution Explorer and selecting Open Command Line and then PowerShell or CMD.

command line

Run the following two commands, replacing id and secret with your actual values.

dotnet user-secrets set Authentication:Google:ClientId id
dotnet user-secrets set Authentication:Google:ClientSecret secret

Enabling Google authentication using OWIN


ASP.NET Core projects rely on OWIN middleware for external authentication.

  1. Open the Startup.cs file.
  2. Navigate to the ConfigureServices(IServiceCollection services) method and add the following code to its body.

    services.AddAuthentication().AddGoogle(googleOptions =>
    {
        googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
        googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
    });
    
  3. Build the app and run it. You should see the option to log in using Google.

google login

google login

google login

google login

Facebook Authentication

The very first thing you will need is a Facebook account in order to consume the required API in your app. You will need to create a new Facebook App project if you don't have one already. You will then need to create OAuth credentials for the project. These credentials consist of an ID and a secret. These are API equivalents to a username and password. Facebook refers to these as App ID and App Secret. Be sure to protect these, and do not share them with anyone.

Creating a Visual Studio project


When creating the project, you should select the ASP.NET Core Web Application template. On the dialog box that follows, you need to select Web Application and Individual User Accounts option in order to add ASP.NET Core Identity.

  1. Go to File > New > Project
  2. Select Installed > Visual C# > Web > ASP.NET Core Web Application
  3. Set a name and location, and then click OK.
  4. Select .NET Core, ASP.NET Core 2.0, Web Application.
  5. Click on Change Authentication, select Individual User Accounts and click OK.
  6. Click OK to create the project.

Visual Studio - New Project

Visual Studio - New ASP.NET App

Visual Studio - New ASP.NET App

Visual Studio - New ASP.NET App

Adding initial migration


Migrations are enabled by default for ASP.NET Core apps, but you need to add the initial migration and update the database using Package Manager Console.

  1. Go to Tools > NuGet Package Manager > Package Manager Console
  2. Execute Add-Migration Initial
  3. Execute Update-Database

Enabling SSL/TLS


OAuth 2.0 requires that you use a secure channel HTTPS protocol. So you need to enable SSL/TLS for your project. This is configured automatically for you if you use the Web Application template and you add ASP.NET Core Identity as explained above.

There are at least three ways to ensure that HTTPS is used in your app.

  • Using data annotation
  • Redirecting HTTP to HTTPS
  • Enforcing HTTPS globally

You can add the [RequireHttps] attribute to controllers, methods or Razor pages but you have to remember to add the attribute when you create new controllers, methods or Razor pages.

Another way is to redirect all HTTP requests to HTTPS. To do that, you can navigate to the Configure(IApplicationBuilder app, IHostingEnvironment env) method in the Startup.cs file in the root of the project and add the following Rewrite option in its body.

var options = new RewriteOptions()
    .AddRedirectToHttps();

app.UseRewriter(options);

A third way is to enforce HTTPS globally in your app. This requires all requests to us HTTPS, and therefore all HTTP requests are ignored. Requiring HTTPS globally is a security best practice and this approach is recommended.

  1. Open the Startup.cs file in the root of the project.
  2. Navigate to the ConfigureServices(IServiceCollection services) method and add the following filter in its body.

    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new RequireHttpsAttribute());
    });
    
  3. Add the Microsoft.AspNetCore.Mvc namespace.

Creating a Facebook App project


enter image description here

enter image description here

enter image description here

Enabling Facebook Login API


enter image description here

enter image description here

enter image description here

Creating OAuth credentials


enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Adding API credentials


enter image description here

Enabling Facebook authentication using OWIN


services.AddAuthentication().AddFacebook(facebookOptions =>
{
    facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
    facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});

enter image description here

enter image description here

enter image description here

enter image description here

like image 155
Samir Avatar answered Oct 17 '22 01:10

Samir