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

 

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

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

 

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

scaffoldingreadme.txt 


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文件类中,增加如下代码:

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的迁移)来创建一个迁移,并更新到数据库

如下:

add-migration createidentityschema
update-database

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

 

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

 

5.运行,查看效果

 

 

 

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

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

即区域(areas)下的 identity/account/login 

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

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

 

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

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

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

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

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

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

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

迁移

add-migration createidentityschema
update-database

 

允许认证

在startup文件的configure方法中,在静态文件(usestaticfiles)之后,调用 useauthentication 

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)

<!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 中

<!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 位置

 

迁移

add-migration createidentityschema
update-database

 

添加认证

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更完全的控制。

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>(); }

 

邮件实现的代码:

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