前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >asp.net core 系列之用户认证(1)-给项目添加 Identity

asp.net core 系列之用户认证(1)-给项目添加 Identity

作者头像
Vincent-yuan
发布2019-09-10 18:18:31
1.1K0
发布2019-09-10 18:18:31
举报
文章被收录于专栏:Vincent-yuanVincent-yuan

对于没有包含认证(authentication),的项目,你可以使用基架(scaffolder)把 Identity的程序集包加入到项目中,并且选择性的添加Identity的代码进行生成。

虽然基架已经生成了很多必须的代码,但是你仍然需要更新你的项目来完善这个过程。

这篇文章主要就是解释完善Identity基架进行更新的一些步骤

当Identity基架添加以后,一个ScaffoldingReadme.txt 文件就被创建了,这里面会包含一些完善Identity基架的说明。如下

ScaffoldingReadme.txt

代码语言:javascript
复制

Support for ASP.NET Core Identity was added to your project 支持把ASP.NET Core Identity添加到你的项目里
- The code for adding Identity to your project was generated under Areas/Identity. 添加Identity生成的代码在Areas/Identity下面

关于Identity 相关的服务配置在Areas/Identity/IdentityHostingStartup.cs 中可以被找到
Configuration of the Identity related services can be found in the Areas/Identity/IdentityHostingStartup.cs file.

UI需要支持静态文件,可以在Configure方法中调用 app.UseStaticFiles()
The generated UI requires support for static files. To add static files to your app:
1. Call app.UseStaticFiles() from your Configure method

要使用ASP.NET Core Identity,你还需要允许认证(authentication),可以在Configure方法中调用 app.UseAuthentication(),在调用静态文件之后做此设置
To use ASP.NET Core Identity you also need to enable authentication. To authentication to your app:
1. Call app.UseAuthentication() from your Configure method (after static files)

UI 要求MVC,可以通过在 Configure 方法中调用app.UseMvc(),在认证之后调用,
另外还需要在 ConfigureServices 中增加调用 services.AddMvc()
The generated UI requires MVC. To add MVC to your app:
1. Call services.AddMvc() from your ConfigureServices method
2. Call app.UseMvc() from your Configure method (after authentication)

Apps that use ASP.NET Core Identity should also use HTTPS. To enable HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.

这篇文章会提供更详细的说明

  • 把Identity基架添加到一个空项目
  • 把Identity基架添加到一个 不存在 认证(authentication)的 Razor项目(即项目中原来不存在认证的项目)
  • 把Identity基架添加到一个 存在 认证(authentication)的 Razor项目(即项目中原来存在认证的项目)
  • 把Identity基架添加到一个 不存在 认证(authentication)的 MVC项目(即项目中原来不存在认证的项目)
  • 把Identity基架添加到一个 存在 认证(authentication)的 MVC项目(即项目中原来存在认证的项目)
  • 创建一个完全的Identity UI (认证界面) 资源

把Identity基架添加到一个空项目

1.首先,准备一个空项目

  • 文件->新建->项目
  • ASP.NET Core web应用,项目名EmptyForIdentity,确定
  • 选择空项目

操作如图:

2.添加Identity基架

  • 在项目上右键,添加->新搭建基架的项目
  • 标识->添加

然后,选择文件;

在这步,如果有布局页,可以选择现有的布局页;

这里没有没有布局页,也不需要指定一个新的布局页,就空着就可以了,它会自动生成一个新的布局页;

然后选择你需要的功能页面,这里选择的是登录功能页面,登录功能页面,注册功能页面;

再选择数据上下文,这里,如果存在的话,一样可以选择已经存在的;但是,在这个空项目中,是没有数据上下文的,所以这里直接点击加号,

新增一个即可。

点击添加

3.在StartUp文件类中,增加如下代码:

代码语言:javascript
复制
public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
       //新增的代码
            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.UseDeveloperExceptionPage();
            //}

            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();  //引入异常中间件,捕获之后出现的异常
            }
            else
            {
                app.UseHsts();  //不是必须添加的,但推荐添加,之后会专门讲解,待续
            }

       //新增的代码
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseMvc();

        }
    }

注意,如果StartUp按照原来空项目的代码,去运行项目的话,像注册,登录,登出等功能页面不能显示,只打印 Hello world;

这里从前面ScaffoldingReadme.txt 文件的说明也能看到,UI的显示需要静态文件和MVC等

4.迁移到数据库

生成的Identity数据库代码需要用到Entity Framework Core Migrations(EFCore的迁移)来创建一个迁移,并更新到数据库

如下:

代码语言:javascript
复制
Add-Migration CreateIdentitySchema
Update-Database

CreateIdentitySchema这个名字可以自己随意取,但是最好能做到见名知义,知道做了哪些迁移

之后,可以自己打开vs上的sql server 对象资源管理器查看数据库和表是否生成成功;

5.运行,查看效果

这里,要说下这个路径了,为什么会是上图标示的这个路径呢

下面展示下目录结构,如下图:

即区域(Areas)下的 Identity/Account/Login

这里应该使用的是一种约定优先的路由方式,

这块之后可能会给出一篇讲解,这里先知道怎么找路由路径即可

注意,下面几个与第一个类似,就不再给出详细图示,可以自己按步骤操作,如果有需要,后面再补充

把Identity基架添加到一个 不存在 认证(authentication)的 Razor项目

1.首先,准备一个项目中原来不带认证的Razor项目

2.把Identity基架添加到项目中

  • 在项目上右键,添加->新搭建基架的项目
  • 标识->添加
  • 选择功能文件(类似登录,登出等),添加

这里操作同第一个,可以按需选择进行添加

3.迁移(Migrations),添加认证,布局

迁移

代码语言:javascript
复制
Add-Migration CreateIdentitySchema
Update-Database

允许认证

在StartUp文件的Configure方法中,在静态文件(UseStaticFiles)之后,调用 UseAuthentication

代码语言:javascript
复制
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication(); //添加认证

        app.UseMvc();
    }
}

布局变化

在布局页面(the layout file)中增加登录分页面(_LoginPartial)

代码语言:javascript
复制
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - RazorNoAuth8</title>

    <environment include="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css" />
    </environment>
    <environment exclude="Development">
        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>
</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a asp-page="/Index" class="navbar-brand">RazorNoAuth8</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-page="/Index">Home</a></li>
                    <li><a asp-page="/About">About</a></li>
                    <li><a asp-page="/Contact">Contact</a></li>
                </ul>
                <partial name="_LoginPartial" />
            </div>
        </div>
    </nav>

    <partial name="_CookieConsentPartial" />

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; 2018 - RazorNoAuth8</p>
        </footer>
    </div>

    <environment include="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    </environment>
    <environment exclude="Development">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
        </script>
        <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>
    </environment>

    @RenderSection("Scripts", required: false)
</body>
</html>

把Identity基架添加到一个 存在 认证(authentication)的 Razor项目

1.首先准备一个项目中原来存在认证的项目

2.把Identity基架添加到项目中

  • 在项目上右键,添加->新搭建基架的项目
  • 标识->添加
  • 选择功能文件(类似登录,登出等),添加

注意,这里在选择布局这个页面操作时,你可以选择已经存在的布局哦,还有数据库上下文,也可以选择使用已经存在的,当然也可以新建

把Identity基架添加到一个 不存在 认证(authentication)的 MVC项目

1.首先准备项目中原来不存在认证的MVC项目

2.把Identity基架添加到项目中

  • 在项目上右键,添加->新搭建基架的项目
  • 标识->添加
  • 选择功能文件(类似登录,登出等),添加

把登录分页(_LoginPartial)添加到Views/Shared/_Layout.cshtml

代码语言:javascript
复制
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - MvcNoAuth3</title>

    <environment include="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css" />
    </environment>
    <environment exclude="Development">
        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>
</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">MvcNoAuth3</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
                </ul>
                <partial name="_LoginPartial" />
            </div>
        </div>
    </nav>

    <partial name="_CookieConsentPartial" />

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; 2018 - MvcNoAuth3</p>
        </footer>
    </div>

    <environment include="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    </environment>
    <environment exclude="Development">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
        </script>
        <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>
    </environment>

    @RenderSection("Scripts", required: false)
</body>
</html>

然后,把 Pages/Shared/_LoginPartial.cshtml 移动到 Views/Shared/_LoginPartial.cshtml 位置

迁移

代码语言:javascript
复制
Add-Migration CreateIdentitySchema
Update-Database

添加认证

代码语言:javascript
复制
public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseMvcWithDefaultRoute(); //使用mvc默认路由
    }
}

把Identity基架添加到一个 存在 认证(authentication)的 MVC项目

1.首先准备一个项目中原本存在认证(authentication)的MVC项目

2.把Identity基架添加到项目中

  • 在项目上右键,添加->新搭建基架的项目
  • 标识->添加
  • 选择功能文件(类似登录,登出等),添加

删除 Pages/Shared 下的文件,和这个目录

创建一个完全的Identity UI(认证界面)资源

下面的代码展示了对比默认Identity UI的一些变化,你可能会想对Identity UI更完全的控制。

代码语言:javascript
复制
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<IdentityUser, IdentityRole>()
        // services.AddDefaultIdentity<IdentityUser>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddRazorPagesOptions(options =>
        {
            options.AllowAreas = true;
            options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
            options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
        });

  //这里设置了登录路径,登出路径,没权限访问的路径
    services.ConfigureApplicationCookie(options =>
    {
        options.LoginPath = $"/Identity/Account/Login";
        options.LogoutPath = $"/Identity/Account/Logout";
        options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
    });

    // using Microsoft.AspNetCore.Identity.UI.Services; 这里注册了一个IEmailSender邮件发送接口的实现
    services.AddSingleton<IEmailSender, EmailSender>();
}

邮件实现的代码:

代码语言:javascript
复制
public class EmailSender : IEmailSender
{
    public Task SendEmailAsync(string email, string subject, string message)
    {
        return Task.CompletedTask;
    }
}

结束!

参考文档:

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.2&tabs=visual-studio#scaffold-identity-into-an-mvc-project-without-existing-authorization

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-04-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 把Identity基架添加到一个空项目
  • 把Identity基架添加到一个 不存在 认证(authentication)的 Razor项目
  • 把Identity基架添加到一个 存在 认证(authentication)的 Razor项目
  • 把Identity基架添加到一个 不存在 认证(authentication)的 MVC项目
  • 把Identity基架添加到一个 存在 认证(authentication)的 MVC项目
  • 创建一个完全的Identity UI(认证界面)资源
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档