验证码在服务器端生成_如何在服务器端Blazor应用中实现Google身份验证和授权

申屠昌胤
2023-12-01

验证码在服务器端生成

介绍 (Introduction)

The latest preview for .NET Core 3 (preview-6) has introduced the functionality to add authentication and authorization in a server-side Blazor application. In this article, we will learn how to implement authentication and authorization using Google in a server-side Blazor application. You can refer to my previous article Understanding Server-side Blazor to get in-depth knowledge on server-side Blazor.

.NET Core 3的最新预览版(预览版6)引入了在服务器端Blazor应用程序中添加身份验证和授权的功能。 在本文中,我们将学习如何在服务器端Blazor应用程序中使用Google实施身份验证和授权。 您可以参考我以前的文章“ 了解服务器端Blazor”,以获取有关服务器端Blazor的深入知识。

先决条件 (Prerequisites)

  • Install the latest .NET Core 3.0 Preview SDK from here.

    此处安装最新的.NET Core 3.0 Preview SDK。

  • Install the latest preview of Visual Studio 2019 from here.

    此处安装Visual Studio 2019的最新预览版。

  • Install ASP.NET Core Blazor Language Services extension from here.

    此处安装ASP.NET Core Blazor语言服务扩展。

源代码 (Source Code)

Get the source code from GitHub

GitHub获取源代码

创建服务器端Blazor应用程序 (Create Server Side Blazor Application)

To create a server-side Blazor app, open Visual Studio 2019 and follow the steps mentioned below.

若要创建服务器端Blazor应用,请打开Visual Studio 2019并按照以下步骤操作。

  1. Click on “Create a new project”.

    点击“创建一个新项目”。
  2. Select “ASP.NET Core Web Application” from available project types. Click on Next.

    从可用的项目类型中选择“ ASP.NET Core Web应用程序”。 单击下一步。
  3. A new “Configure your new project” screen will open. Put the name of the project as BlazorGoogleAuth and click Create.

    一个新的“配置新项目”屏幕将打开。 将项目名称命名为BlazorGoogleAuth ,然后单击“创建”。

  4. In the next screen, select “.NET Core” and “ASP.NET Core 3.0” from dropdowns on the top left.

    在下一个屏幕中,从左上方的下拉菜单中选择“ .NET Core”和“ ASP.NET Core 3.0”。
  5. Select “Blazor (server-side)” from the list of available templates.

    从可用模板列表中选择“ Blazor(服务器端)”。
  6. Click on Change Authentication button, a “Change Authentication” dialog box will open. Select “Individual User Account” and click OK. Click on Create button to create the application.

    单击更改身份验证按钮,将打开“更改身份验证”对话框。 选择“个人用户帐户”,然后单击“确定”。 单击Create按钮创建应用程序。

These steps are shown in the GIF image below.

这些步骤显示在下面的GIF图像中。

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 Update-Database command and hit enter. This will update the database using Entity Framework Code First Migrations.

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

Open project properties by right clicking on the project in solution explorer and select properties. Select Debug from left side menu then scroll to the bottom of the page. Note the SSL enabled URL. In this case, the URL is https://localhost:44327/. We need this URL to configure the Google API Console project which we will be doing in our next section. Refer to the image below:

通过在解决方案资源管理器中右键单击项目打开项目属性,然后选择属性。 从左侧菜单中选择“调试”,然后滚动到页面底部。 注意启用了SSL的URL。 在这种情况下,URL为https://localhost:44327/ 。 我们需要此URL来配置Google API控制台项目,这将在下一部分中进行。 请参考下图:

创建一个Google API控制台项目 (Create a Google API Console project)

We need to create a Google API console project and obtain a client ID and client secret to configure the Google authentication in our application.

我们需要创建一个Google API控制台项目,并获取一个客户端ID和客户端密码,以便在我们的应用程序中配置Google身份验证。

Navigate to https://developers.google.com/identity/sign-in/web/sign-in#before_you_begin. Login with your Google account. Follow the steps mentioned below.

导航至https://developers.google.com/identity/sign-in/web/sign-in#before_you_begin 。 使用您的Google帐户登录。 请遵循以下步骤。

  1. Click on “Configure a Project” button.

    点击“配置项目”按钮。
  2. A “Configure a project for Google Sign-in” dialog box will open asking you to select or create a new project.

    将打开“为Google登录配置项目”对话框,要求您选择或创建一个新项目。
  3. Select “Create a new project” from the dropdown. Name your project “BlazorAuthDemo” and click on Next.

    从下拉列表中选择“创建新项目”。 将您的项目命名为“ BlazorAuthDemo”,然后单击“下一步”。
  4. In the “Configure your OAuth client” screen, put your product name. You can use any name of your choice. Here we will put “BlazorAuth” as the product name.

    在“配置OAuth客户端”屏幕中,输入您的产品名称。 您可以使用您选择的任何名称。 在这里,我们将“ BlazorAuth”作为产品名称。
  5. In the next screen, select “Web server” from the “Where are you calling from” dropdown.

    在下一个屏幕中,从“您从哪里打电话”下拉菜单中选择“ Web服务器”。
  6. It will then ask you to put the “Authorized redirect URIs”. Give the base URL of your application with /signin-google appended to it. For this tutorial, the URL will be https://localhost:44327/signin-google.

    然后它将要求您放入“授权的重定向URI”。 提供附加了/signin-google应用程序的基本URL。 在本教程中,URL为https://localhost:44327/signin-google

  7. Click on Create. The dialog box will now prompt you with the client ID and client secret. Make a note of ClientId and ClientSecret field. We will need these values to configure Google authentication in our web app

    单击创建。 现在,对话框将提示您输入客户端ID和客户端密码。 记下ClientIdClientSecret字段。 我们将需要这些值来在我们的网络应用中配置Google身份验证

Refer to the GIF below for a better understanding.

请参阅下面的GIF,以获得更好的理解。

  • Do not use the word “Google” in your product name. You will be prompted with an error and you will not be allowed to create the app. This means “BlazorGoogleAuth” is an invalid project name.

    不要在产品名称中使用“ Google”一词。 系统将提示您错误,并且不允许您创建应用。 这意味着“ BlazorGoogleAuth”是无效的项目名称。
  • Project names must be between 4 and 30 characters and may only contain letters, numbers, spaces, and hyphens.

    项目名称必须介于4到30个字符之间,并且只能包含字母,数字,空格和连字符。

安装Google身份验证中间件NuGet软件包 (Installing Google authentication middleware NuGet package)

To configure the ASP.NET Core middleware for Google authentication we need to install the Microsoft.AspNetCore.Authentication.Google nuget package in our application. The version of this nuget package must match the version of .NET Core 3 which we are using in our project.

要为Google身份验证配置ASP.NET Core中间件,我们需要在应用程序中安装Microsoft.AspNetCore.Authentication.Google nuget程序包。 此nuget软件包的版本必须与我们在项目中使用的.NET Core 3的版本匹配。

Open https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.Google/. Select the version of .NET Core 3 from the “Version History”. Copy the command from the “package manager” tab. Run this command in the NuGet package manager console of our application.

打开https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.Google/ 。 从“版本历史记录”中选择.NET Core 3的版本。 从“程序包管理器”选项卡复制命令。 在我们的应用程序的NuGet程序包管理器控制台中运行此命令。

For this application, we are using .NET Core 3.0.0-preview6.19307.2. Therefore, we will run the following command in the package manager console of our application.

对于此应用程序,我们使用.NET Core 3.0.0-preview6.19307.2 。 因此,我们将在应用程序的程序包管理器控制台中运行以下命令。

Install-Package Microsoft.AspNetCore.Authentication.Google -Version 3.0.0-preview6.19307.2

Refer to the image below:

请参考下图:

配置服务器端Blazor应用以使用Google身份验证 (Configure the server-side Blazor app to use Google authentication)

We need to store ClientId and ClientSecret field values in our application. We will use 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.

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

Open our web application once again and Right-click the project in the Solution Explorer. Select Manage User Secrets from the context menu. A secrets.json file will open. Put the following code in it.

再次打开我们的Web应用程序,然后在解决方案资源管理器中右键单击该项目。 从上下文菜单中选择“管理用户密码”。 一个secrets.json文件将打开。 将以下代码放入其中。

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

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

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

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

This code will read the ClientId and ClientSecret from the secrets.json file. The AddGoogle()method is an extension method and it is used to configure the Google Authentication options for our application.

此代码将从secrets.json文件读取ClientIdClientSecretAddGoogle()方法是一种扩展方法,用于为我们的应用程序配置Google身份验证选项。

向Blazor页面添加授权 (Adding authorization to Blazor pages)

Blazor has added a new built-in component called AuthorizeView, which is used to display different content based on the authentication state of the application. This component will display the child component only when the user is authorized.  The AuthorizeView component is configured in \Shared\LoginDisplay.razor file.

Blazor添加了一个名为AuthorizeView的新内置组件,该组件用于根据应用程序的身份验证状态显示不同的内容。 仅当用户获​​得授权时,此组件才会显示子组件。 在\Shared\LoginDisplay.razor文件中配置AuthorizeView组件。

To implement authorization to a specific page, we need to use the [Authorize] attribute. Blazor has introduced a new directive @attribute, which is used to include the [Authorize] attribute for a page. In this application, we will apply [Authorize] to the FetchData component. This will prohibit unauthorized access to this component. Open FetchData.razor page and add the following lines at the top of the page.

要实现对特定页面的授权,我们需要使用[Authorize]属性。 Blazor引入了新的指令@attribute ,该指令用于包括页面的[Authorize]属性。 在此应用程序中,我们将对FetchData组件应用[Authorize] 。 这将禁止未经授权访问此组件。 打开FetchData.razor页面,并在页面顶部添加以下行。

@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]

执行演示 (Execution Demo)

Launch the application. Navigate to Fetch Data component by clicking on the “Fetch data” link on the menu on the left. You will see a “Not authorized” message displayed on the screen. Click “Log In” on the menu at the top. In the next page click on the “Google” button to login with Google. Once you are logged in successfully, you will be able to access the Fetch Data component.

启动应用程序。 通过单击左侧菜单上的“获取数据”链接,导航到“获取数据”组件。 您将在屏幕上看到“未授权”消息。 点击顶部菜单上的“登录”。 在下一页中,单击“ Google”按钮以登录Google。 成功登录后,您将能够访问“获取数据”组件。

Refer to the GIF below for a better understanding.

请参阅下面的GIF,以获得更好的理解。

结论 (Conclusion)

We learned how to implement Google authentication and authorization in a server-side Blazor application. We have created and configured a Google API console project to implement Google authentication. To implement authorization for a specific component in Blazor, we have used the [Authorize] attribute. We have used Microsoft.AspNetCore.Authentication.Google nuget package to configure the middleware for Google authentication.

我们学习了如何在服务器端Blazor应用程序中实现Google身份验证和授权。 我们已经创建并配置了Google API控制台项目以实现Google身份验证。 为了实现Blazor中特定组件的授权,我们使用了[Authorize]属性。 我们已经使用Microsoft.AspNetCore.Authentication.Google nuget包来配置用于Google身份验证的中间件。

Please get the source code from GitHub and play around to get a better understanding.

请从GitHub获取源代码并进行尝试以获得更好的理解。

Get my book Blazor Quick Start Guide to learn more about Blazor.

获取我的书《 Blazor快速入门指南》,以了解有关Blazor的更多信息。

Preparing for interviews !!! Read my article on C# Coding Questions For Technical Interviews

准备面试! 阅读有关技术面试的C#编码问题的文章

也可以看看 (See Also)

Originally published at https://ankitsharmablogs.com/google-authentication-and-authorization-in-server-side-blazor-app/

最初发布在https://ankitsharmablogs.com/google-authentication-and-authorization-in-server-side-blazor-app/

翻译自: https://www.freecodecamp.org/news/how-to-implement-google-authentication-and-authorization-in-server-side-blazor-app/

验证码在服务器端生成

 类似资料: