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

asp.core 身份验证

by Ankit Sharma

通过Ankit Sharma

在ASP.NET Core 2.0中使用Twitter进行身份验证 (Authentication Using Twitter 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 Twitter.

有时,我们希望用户使用他们现有的凭据从第三方应用程序(如Facebook,Twitter,Google等)登录。 在本文中,我们将研究使用Twitter进行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 Community Edition 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 Visual C# menu from the left panel. Then, select “ASP.NET Core Web Application” from available project types. Put the name of the project as DemoTwitterAuth and press OK.

打开Visual Studio,然后选择“文件>>新建>>项目”。 选择项目后,将打开“新建项目”对话框。 从左侧面板的Visual C#菜单中选择.NET Core。 然后,从可用的项目类型中选择“ ASP.NET Core Web应用程序”。 将项目名称命名为Dem o TwitterAuth,然后按OK。

After clicking on OK, a new dialog will open asking 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 your 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 can see a home page as shown below.

按F5运行该应用程序。 您可以看到如下所示的主页。

Note the URL from the browser address bar. In this case, the URL is http://localhost:51763/. We need this URL to configure our Twitter App, which we will be doing in the next section.

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

创建Twitter应用 (Create the Twitter App)

Before we start building our ASP.NET Core 2.0 application, we need to create and configure the Twitter app so that we can use it to authenticate our application.

在开始构建ASP.NET Core 2.0应用程序之前,我们需要创建和配置Twitter应用程序,以便我们可以使用它来验证我们的应用程序。

Navigate to https://apps.twitter.com/ and sign in using your existing Twitter account. If you do not have a Twitter account, you need to create one. You cannot proceed without a Twitter account. Once you have logged in, you will be redirected to an Application Management page similar to the one shown below.

导航到https://apps.twitter.com/并使用您现有的Twitter帐户登录。 如果您没有Twitter帐户,则需要创建一个。 没有Twitter帐户,您将无法继续。 登录后,您将被重定向到类似于下面所示的“应用程序管理”页面。

It will show all your Twitter Apps configured. Since I have already configured a Twitter App, it is being displayed. If you are creating one for the first time, it will not show anything. Click on the “Create New App” button in the top right corner. It will open a form and ask to fill out the details to create a new app.

它将显示所有已配置的Twitter Apps。 由于我已经配置了Twitter App,因此正在显示它。 如果是第一次创建,则不会显示任何内容。 点击右上角的“创建新应用”按钮。 它将打开一个表格,并要求填写详细信息以创建一个新的应用程序。

You can fill the form with the details as mentioned below.

您可以使用以下详细信息填写表格。

  • Name

    名称

    Give any name of your choice. But it should be universally unique. This means no one should have used this name earlier for creating a Twitter app. This works the same as Email id. Two people cannot have the same Email id. I am using the name “DemoTwitterAuth” for this tutorial. If you use an already existing name then you will get an error “

    给出您选择的任何名称。 但是它应该是普遍唯一的。 这意味着没有人早先使用此名称来创建Twitter应用程序。 这与电子邮件ID相同。 两个人不能具有相同的电子邮件ID。 我在本教程中使用的名称为“ DemoTwitterAuth”。 如果您使用的名称已经存在,则会出现错误“

    The client application failed validation: <your entered name> is already taken for Name.”

    客户端应用程序验证失败:<您输入的名称>已被用作名称。”

  • Description

    描述

    Give an appropriate description.

    给出适当的描述。

  • Website

    网站

    Give your public website URL. But for this demo purpose, we will use a dummy URL

    提供您的公共网站URL。 但是出于演示目的,我们将使用一个伪URL

    http://demopage.com.

    http://demopage.com。

If you use the URL format as www.demopage.com, you will get an error “The client application failed validation: Not a valid URL format.” Always use URL format as http://demopage.com

如果将URL格式用作www.demopage.com则会收到错误“ 客户端应用程序验证失败:无效的URL格式。 ”始终使用网址格式为http://demopage.com

Accept the Developer agreement by clicking the checkbox and click on the “Create your Twitter application” button. You will be redirected to your newly created Twitter app page, and you will also see a success message as shown in the image below.

通过单击复选框接受开发人员协议,然后单击“创建您的Twitter应用程序”按钮。 您将被重定向到新创建的Twitter应用程序页面,并且还将看到成功消息,如下图所示。

Navigate to the “Keys and Access Tokens” tab and make a note of the Consumer Key (API Key) and Consumer Secret (API Secret) field values. We will be using these values in the ASP.NET Core app.

导航到“密钥和访问令牌”选项卡,并记下“消费者密钥”(API密钥)和“消费者秘密”(API秘密)字段的值。 我们将在ASP.NET Core应用中使用这些值。

The fields are masked in this image for security purposes.

为了安全起见,此图像中的字段被屏蔽。

Our Twitter app has been created successfully.

我们的Twitter应用已成功创建。

配置Web应用程序以使用Twitter身份验证 (Configure the Web App to use Twitter authentication)

We need to store the Consumer Key (API Key) and Consumer Secret (API Secret) field values in our application. We will use the Secret Manager tool for this purpose.

我们需要在我们的应用程序中存储使用者密钥(API密钥)和使用者密钥(API密钥)字段值。 为此,我们将使用Secret Manager工具。

The Secret Manager tool is a project tool that can be used to store secrets such as password, API Key, and so on 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.

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:Twitter:ConsumerKey": "Your Consumer Key here",  
    "Authentication:Twitter:ConsumerSecret": "Your Consumer Secret here"  
}

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

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

services.AddAuthentication().AddTwitter(twitterOptions => {  
    twitterOptions.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];  
    twitterOptions.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];  
});

In this code section, we are reading ConsumerKey and ConsumerSecret for the authentication purpose. So finally, Startup.cs will look like this.

在此代码部分中,我们正在阅读ConsumerKey和ConsumerSecret以进行身份​​验证。 最后, 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 DemoTwitterAuth.Data;  
using DemoTwitterAuth.Models;  
using DemoTwitterAuth.Services;  
namespace DemoTwitterAuth {  
    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 < ApplicationDbContext > (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
            services.AddIdentity < ApplicationUser, IdentityRole > ().AddEntityFrameworkStores < ApplicationDbContext > ().AddDefaultTokenProviders();  
            services.AddAuthentication().AddTwitter(twitterOptions => {  
                twitterOptions.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];  
                twitterOptions.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];  
            });  
            // Add application services.  
            services.AddTransient < IEmailSender, EmailSender > ();  
            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” in the top right corner of the homepage.

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

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

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

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

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

Once you click on Authorize app, the application will take a few moments to authenticate your Twitter account. Upon successful authentication, 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.

单击“授权”应用程序后,该应用程序将花费一些时间来验证您的Twitter帐户。 身份验证成功后,您将被重定向到应用程序内的注册页面,您需要在其中填写电子邮件ID来标记您的帐户。

Give an email id and click “Register”. You will be redirected to the homepage again but this time, you can also see your registered email is in the top right corner.

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

结论 (Conclusion)

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

我们已经成功创建了一个Twitter应用程序,并将其用于验证我们的ASP.NET Core应用程序。

You can get the source code from GitHub.

您可以从GitHub获取源代码。

Please note that in the source code, the secrets.json file contains dummy values. So you’ll need to replace the values with the keys of your Twitter app before executing it.

请注意,在源代码中, secrets.json文件包含伪值。 因此,您需要在执行前用Twitter应用程序的键替换值。

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)

Originally published at ankitsharmablogs.com

最初发布在ankitsharmablogs.com

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

asp.core 身份验证

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值