asp.core 身份验证_在ASP.NET Core 2.0中使用Google进行身份验证

asp.core 身份验证

by Ankit Sharma

通过Ankit Sharma

在ASP.NET Core 2.0中使用Google进行身份验证 (Authentication Using Google In ASP.NET Core 2.0)

介绍 (Introduction)

Sometimes, we want our users to log in using their existing credentials from third-party applications, such as Facebook, Twitter, Google, and so on. In this article, we are going to look into authentication of an ASP.NET Core app using a Google account.

有时,我们希望用户使用他们现有的来自第三方应用程序(如Facebook,Twitter,Google等)的凭据登录。 在本文中,我们将研究使用Google帐户对ASP.NET Core应用程序的身份验证。

先决条件 (Prerequisites)

  • Install .NET Core 2.0.0 or above SDK from here.

    从此处安装.NET Core 2.0.0或更高版本的SDK。

  • Install the latest version of Visual Studio 2017 from here.

    从此处安装最新版本的Visual Studio 2017。

创建MVC Web应用程序 (Create MVC Web Application)

Open Visual Studio and select File >> New >> Project. After selecting the project, a “New Project” dialog will open. Select .NET Core inside the Visual C# menu from the left panel. Then, select “ASP.NET Core Web Application” from the available project types. Put the name of the project as GoogleAuth and press OK. Refer to this image.

打开Visual Studio,然后选择“文件>>新建>>项目”。 选择项目后,将打开“新建项目”对话框。 从左侧面板的Visual C#菜单中选择.NET Core。 然后,从可用的项目类型中选择“ ASP.NET Core Web应用程序”。 把项目A S GoogleAuth,然后按确定的名称。 参考此图像。

After clicking OK, a new dialog will open asking you to select the project template. You can observe two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.0” from these dropdowns. Then, select the “Web application(Model-View-Controller)” template. Click on the Change Authentication button, and a “Change Authentication” dialog box will open. Select “Individual User Account” and click OK. Now, click OK again to create our web app.

单击确定后,将打开一个新对话框,要求您选择项目模板。 您可以在模板窗口的左上方观察两个下拉菜单。 从这些下拉列表中选择“ .NET Core”和“ ASP.NET Core 2.0”。 然后,选择“ Web应用程序(模型-视图-控制器)”模板。 单击更改身份验证按钮,将打开“更改身份验证”对话框。 选择“个人用户帐户”,然后单击“确定”。 现在,再次单击“确定”以创建我们的Web应用程序。

Before running the application, we need to apply migrations to our app.

在运行应用程序之前,我们需要将迁移应用到我们的应用程序。

Navigate to Tools >> Nuget Package Manager >> Package Manager Console.

导航到工具>> Nuget软件包管理器>>软件包管理器控制台。

It will open the Package Manager Console. Put in the Update-Database command and hit enter. This will update the database using Entity Framework Code First Migrations.

它将打开软件包管理器控制台。 放入Update-Database命令,然后按Enter。 这将使用实体框架代码优先迁移来更新数据库。

Press F5 to run the application. You will see a homepage, as shown below.

按F5运行该应用程序。 您将看到一个主页,如下所示。

Note the URL from the browser’s address bar. In this case, the URL is http://localhost:51792/. We need this URL to configure our Google app, which we will be doing in the next section.

记下浏览器地址栏中的URL。 在这种情况下,URL为http:// localhost:51792 /。 我们需要此URL来配置我们的Google应用,这将在下一部分中进行。

创建Google应用 (Create the Google app)

We need to create a new Google app on the Google API console. Navigate to https://console.developers.google.com/projectselector/apis/library and log in using your Google account. If you do not have a Google account, you need to create one. You cannot proceed without a Google account. Once you have logged in, you will be redirected to the API Manager Library page, similar to the one shown below.

我们需要在Google API控制台上创建一个新的Google应用。 导航到https://console.developers.google.com/projectselector/apis/library并使用您的Google帐户登录。 如果您没有Google帐户,则需要创建一个。 没有Google帐户,您将无法继续。 登录后,您将被重定向到“ API管理器库”页面,与以下所示类似。

Click on the Create button to move to the “New Project” page where you need to create a new project. The “Project name” field will be populated automatically with a default name provided by Google. If you want, you can override that with your own custom name. For this tutorial, we will be using the default name. Accept the terms of service and then click on the Create button.

单击创建按钮以移动到“新项目”页面,您需要在其中创建一个新项目。 将使用Google提供的默认名称自动填充“项目名称”字段。 如果需要,可以使用自己的自定义名称覆盖它。 在本教程中,我们将使用默认名称。 接受服务条款,然后单击创建 按钮

Your project will be created successfully and you will be redirected to the API Library page similar to the one shown below.

您的项目将成功创建,并且您将被重定向到类似于下面所示的“ API库”页面。

Search for the Google+ API in the search bar and select the Google+ API from the search results. Refer to the below image.

在搜索栏中搜索Google+ API,然后从搜索结果中选择Google+ API。 请参考下图。

After selecting the Google+ API option, you will be redirected to a page as shown below, where you need to click on the Enable button.

选择Google+ API选项后,您将被重定向到如下所示的页面,您需要在该页面上单击“ 启用”按钮。

After this, the Google+ API will be enabled and you will be redirected to the API home page. Click on Create credentials button on the right side of the page to configure the secrets for your API.

此后,将启用Google+ API,您将被重定向到API主页。 点击创建凭证 页面右侧的按钮配置API的机密。

You will see an “Add credentials to your project” form.

您将看到“向项目添加凭据”表单。

This form has three sections.

该表格分为三个部分。

Fill in the details of the sections as described below.

如下所述填写各节的详细信息。

第1节-找出所需的凭证 (Section 1 — Find out what kind of credentials you need)
  • Which API are you using? — Google+ API

    您正在使用哪个API? — Google+ API
  • Where will you be calling the API from? — Web server (for example, Node.js, Tomcat)

    您将从哪里调用API? — Web服务器(例如,Node.js,Tomcat)
  • What data will you be accessing? — User data

    您将访问哪些数据? - 用户数据

And click on the What credentials do I need button. You will be redirected to section 2

然后单击“ 我需要什么凭证”按钮。 您将被重定向到第2节

第2部分-创建OAuth 2.0客户端ID (Section 2 — Create an OAuth 2.0 client ID)
  • Name — The default value provided by Google.

    名称-Google提供的默认值。
  • Authorized JavaScript origins — Leave it blank.

    授权JavaScript来源-保留空白。
  • Authorized redirect URIs — Give the base URL of your application with /signin-google appended to it. For this tutorial, the URL will be http://localhost:51792/signin-google. After entering the URL, press TAB to add the value.

    授权的重定向URI-提供您的应用程序的基本URL,并在其上附加/ signin-google 。 对于本教程,URL为http:// localhost:51792 / signin-google。 输入URL后,按TAB键添加值。

After this, click on the Create client ID button. You will be redirected to section 3.

之后,单击“ 创建客户端ID”按钮。 您将被重定向到第3节。

  • Email address — Select your email address from the dropdown. This value is masked in the above image for privacy.

    电子邮件地址-从下拉列表中选择您的电子邮件地址。 为了保护隐私,上图中屏蔽了该值。
  • Product name shown to users — Enter any product name. Here we are using “AuthDemo” as the Product name.

    向用户显示的产品名称-输入任何产品名称。 在这里,我们使用“ AuthDemo”作为产品名称。

Note: Do not use the word “Google” in your product name. You will be prompted with an error and you won’t be allowed to create the app. This means “GoogleAuthDemo” is an invalid name.

注意 :请勿在产品名称中使用“ Google”一词。 系统将提示您错误,并且不允许您创建应用。 这意味着“ GoogleAuthDemo”是无效名称。

Click on continue.

点击继续。

Your credentials have been created successfully. Click Download to download a JSON file to your local machine with all your application secrets, and then click Done to complete the process.

您的凭据已成功创建。 单击“ 下载” ,将包含所有应用程序密码的JSON文件下载到本地计算机,然后单击“完成”以完成该过程。

Open the just downloaded client_id.json file and make a note of the ClientId and ClientSecret fields. We will need these values to configure Google authentication in our web app.

打开刚刚下载的client_id.json文件,并记下ClientIdClientSecret字段。 我们将需要这些值来在我们的Web应用程序中配置Google身份验证。

配置您的Web应用以使用Google身份验证 (Configure your Web App to use Google authentication)

We need to store the ClientId and ClientSecret field values in our application. We will use the Secret Manager tool for this purpose. The Secret Manager tool is a project tool that can be used to store secrets such as password, API Key, etc. for a .NET Core project during the development process. With the Secret Manager tool, we can associate app secrets with a specific project and can share them across multiple projects.

我们需要在我们的应用程序中存储ClientId和ClientSecret字段值。 为此,我们将使用Secret Manager工具。 Secret Manager工具是一个项目工具,可在开发过程中用于存储.NET Core项目的秘密,例如密码,API密钥等。 使用Secret Manager工具,我们可以将应用程序秘密与特定项目关联,并可以在多个项目之间共享它们。

Open your web application once again and Right-click the project in Solution Explorer. Select Manage User Secrets from the context menu.

再次打开Web应用程序,然后在解决方案资源管理器中右键单击该项目。 从上下文菜单中选择“ 管理用户密码 ”。

A secrets.json file will open. Put the following code in it:

一个secrets.json文件将打开。 将以下代码放入其中:

{  
  "Authentication:Google:ClientId": "Your Google ClientId here",  
  "Authentication:Google:ClientSecret": "Your Google ClientSecret here"  
}

Now open the Startup.cs file and put the following code into the ConfigureServices method:

现在打开Startup.cs文件,并将以下代码放入ConfigureServices方法中:

services.AddAuthentication().AddGoogle(googleOptions =>  
{  
    googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];  
    googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];  
});

In this code section, we are reading ClientId and ClientSecret for authentication purposes. So finally, Startup.cs will look like this:

在此代码部分中,我们将读取ClientId和ClientSecret以进行身份​​验证。 最后, Startup.cs 看起来像这样:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using Microsoft.AspNetCore.Builder;  
using Microsoft.AspNetCore.Identity;  
using Microsoft.EntityFrameworkCore;  
using Microsoft.AspNetCore.Hosting;  
using Microsoft.Extensions.Configuration;  
using Microsoft.Extensions.DependencyInjection;  
using GoogleAuth.Data;  
using GoogleAuth.Models;  
using GoogleAuth.Services;  
  
namespace GoogleAuth  
{  
    public class Startup  
    {  
        public Startup(IConfiguration configuration)  
        {  
            Configuration = configuration;  
        }  
  
        public IConfiguration Configuration { get; }  
  
        // This method gets called by the runtime. Use this method to add services to the container.  
        public void ConfigureServices(IServiceCollection services)  
        {  
            services.AddDbContext(options =>  
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
  
            services.AddIdentity()  
                .AddEntityFrameworkStores()  
                .AddDefaultTokenProviders();  
  
            services.AddAuthentication().AddGoogle(googleOptions =>  
            {  
                googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];  
                googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];  
            });  
  
            // Add application services.  
            services.AddTransient();  
  
            services.AddMvc();  
        }  
  
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
        {  
            if (env.IsDevelopment())  
            {  
                app.UseBrowserLink();  
                app.UseDeveloperExceptionPage();  
                app.UseDatabaseErrorPage();  
            }  
            else  
            {  
                app.UseExceptionHandler("/Home/Error");  
            }  
  
            app.UseStaticFiles();  
  
            app.UseAuthentication();  
  
            app.UseMvc(routes =>  
            {  
                routes.MapRoute(  
                    name: "default",  
                    template: "{controller=Home}/{action=Index}/{id?}");  
            });  
        }  
    }  
}

And with this, our application is ready.

至此,我们的应用程序已准备就绪。

执行演示 (Execution Demo)

Launch the application and click Login on the top right corner of the home page.

启动应用程序,然后单击主页右上角的“登录”。

You will be redirected to http://localhost:51792/Account/Login page, where you can see the option to login using Google on the right side of the page.

您将被重定向到http:// localhost:51792 / Account / Login页面,您可以在页面右侧看到使用Google登录的选项。

Clicking on the Google button will take you to the Google login page. There, you will be asked to fill in your Google credentials and authorize the Google app to use your Google account.

单击Google按钮将带您进入Google登录页面。 在那里,系统将要求您填写Google凭据并授权Google应用使用您的Google帐户。

After successful authentication from Google, you will be redirected to a registration page inside your application where you need to fill in an email id to tag with your account. The Gmail id that you have used to login will already be populated in the Email id field. If you want to use another mail id, you can change it here.

经过Google的成功身份验证后,您将被重定向到应用程序内的注册页面,您需要在其中填写电子邮件ID来标记您的帐户。 您用于登录的Gmail ID将已经在“电子邮件ID”字段中填充。 如果要使用其他邮件ID,可以在此处进行更改。

Click register, you will be redirected to the home page again. But this time you can also see that your registered email is on the top right corner.

单击注册,您将再次重定向到主页。 但是这次您还可以看到您的注册电子邮件在右上角。

结论 (Conclusion)

We have successfully created and configured a Google+ app and used it to authenticate our ASP.NET Core application.

我们已经成功创建并配置了Google+应用程序,并已使用它对我们的ASP.NET Core应用程序进行身份验证。

You can get the source code from GitHub.

您可以从GitHub获取源代码。

Please note that the secrets.json file contains dummy values. You’ll need to replace the values with the keys of your Google app before executing it.

请注意, secrets.json文件包含伪值。 在执行之前,您需要使用Google应用的键替换值。

You can also find this article at C# Corner.

您也可以在C#Corner上找到此文章。

You can check my other articles on ASP .NET Core here

您可以在此处查看有关ASP .NET Core的其他文章

也可以看看 (See Also)

  • Authentication Using LinkedIn In ASP.NET Core 2.0

    在ASP.NET Core 2.0中使用LinkedIn进行身份验证

  • Authentication Using Twitter In ASP.NET Core 2.0

    在ASP.NET Core 2.0中使用Twitter进行身份验证

  • Authentication Using Facebook In ASP.NET Core 2.0

    在ASP.NET Core 2.0中使用Facebook进行身份验证

  • Cookie Authentication With ASP.NET Core 2.0

    使用ASP.NET Core 2.0进行Cookie身份验证

  • ASP.NET Core — Two Factor Authentication Using Google Authenticator

    ASP.NET Core —使用Google Authenticator进行两因素身份验证

Originally published at ankitsharmablogs.com

最初发布在ankitsharmablogs.com

翻译自: https://www.freecodecamp.org/news/authentication-using-google-in-asp-net-core-2-0-5ec32c803e23/

asp.core 身份验证

你可能感兴趣的:(java,web,vue,开发工具,github,ViewUI)