当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net core系列 46 Identity介绍

asp.net core系列 46 Identity介绍

2019年03月22日  | 移动技术网IT编程  | 我要评论

卡布西游小水虎,风流十三少,淄博市天气

一. identity 介绍

  asp.net core identity是一个会员系统,可为asp.net core应用程序添加登录功能。可以使用sql server数据库配置身份以存储用户名,密码和配置文件数据。或者,可以使用另一个持久性存储,例如,azure表存储。下面学习如何使用identity注册,登录以及基架标识。

  

  1.1 identity搭建演示

    下面使用vs 2017来演示:

      1.选择“文件” > “新建” > “项目”。

      2.选择“asp.net core web应用程序”。 将项目命名webappidentitydemo具有项目下载相同的命名空间。 单击 “确定”。

      3.选择 asp.net core web mvc应用程序,然后选择更改身份验证。

      4.选择单个用户帐户然后单击确定。

    生成的项目包含了identity会员系统,目录结构如下所示,生成后的目录结构有疑惑,怎么没看见identity会员系统相关的model, controller,cshtml等文件,继续往下了解。

    (1) 修改连接字符串

      找到appsettings.json文件,修改connectionstrings的数据库连接字符串, 默认是连接本机sql server数据库,我改成了连接远程数据库。

"connectionstrings": {
    "defaultconnection": "data source = 172.168.16.75;initial catalog =identitydb; user id = hsr;password =js*2015;"
  },

     (2) 基于生成的迁移代码,同步到数据库 

      pm> update-database 

    (3) 配置identity服务

        public void configureservices(iservicecollection services)
        {
            services.configure<cookiepolicyoptions>(options =>
            {
                // this lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.checkconsentneeded = context => true;
                options.minimumsamesitepolicy = samesitemode.none;
            });

            services.adddbcontext<applicationdbcontext>(options =>
                options.usesqlserver(
                    configuration.getconnectionstring("defaultconnection")));
services.adddefaultidentity<identityuser>() .adddefaultui(uiframework.bootstrap4) .addentityframeworkstores<applicationdbcontext>(); services.configure<identityoptions>(options => { // password settings. options.password.requiredigit = true; options.password.requirelowercase = true; options.password.requirenonalphanumeric = true; options.password.requireuppercase = true; options.password.requiredlength = 6; options.password.requireduniquechars = 1; // lockout settings. options.lockout.defaultlockouttimespan = timespan.fromminutes(5); options.lockout.maxfailedaccessattempts = 5; options.lockout.allowedfornewusers = true; // user settings. options.user.allowedusernamecharacters = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789-._@+"; options.user.requireuniqueemail = false; }); services.configureapplicationcookie(options => { // cookie settings options.cookie.httponly = true; options.expiretimespan = timespan.fromminutes(5); options.loginpath = "/identity/account/login"; options.accessdeniedpath = "/identity/account/accessdenied"; options.slidingexpiration = true; }); services.addmvc().setcompatibilityversion(compatibilityversion.version_2_2); }

    (4) 确认调用useauthentication中间件

public void configure(iapplicationbuilder app, ihostingenvironment env)
{
    if (env.isdevelopment())
    {
        app.usedeveloperexceptionpage();
        app.usedatabaseerrorpage();
    }
    else
    {
        app.useexceptionhandler("/error");
        app.usehsts();
    }

    app.usehttpsredirection();
    app.usestaticfiles();
    app.usecookiepolicy();
    app.useauthentication();
    app.usemvc();
}

     (5) 启动程序,首页提供了注册,登录的链接

      注册成功后/identity/account/register,在数据库中aspnetusers表会新增一条数据(密码:asp.netcore123)。注册成功后,说明数据库连接没有问题,会跳到登录页identity/account/login

      虽然没有看到identity会员系统相关文件,其实已经内置由razor类库提供。identity razor类库使用该identity areas公开端点。例如:

             /identity/account/login

             /identity/account/logout

             /identity/account/manage

  

二. 基架标识(scaffold identity )

  asp.net core 2.1 及更高版本提供了asp.net core identity作为razor 类库。 包含identity的应用程序可以应用基架,来有选择地添加包含在identity razor 类库 (rcl) 的源代码。 建议生成源代码,以便修改代码和更改行为(根据开发需求扩展identity)。 例如,可以指示基架生成在注册过程中使用的代码。 生成的代码优先于标识 rcl 中的相同代码。 若要获取的用户界面的完全控制,并且使用默认 rcl,等下参考2.2。      

   

  2.1 使用scaffold identity 授权到mvc 项目

      1.从解决方案资源管理器,右键单击该项目 >添加 > 新基架项。

      2.从左窗格添加基架对话框中,选择标识 > 添加。

      3.在中add 标识添加对话框中,选择所需的选项。

    下面使用现有的数据上下文,选择所有文件,以便后面重写,如下所示。

    生成需要重写的文件后,如下所示(可以比对上图1.1的areas目录),注意生成的是razor page 文件,不是mvc视图控制器。之前上面的疑惑解除了。

    

  2.2 创建完整的identity ui 源

   上面2.1中运行scaffold identity,保持了对identity ui的完全控制。以下突出显示的代码显示默认identity ui 替换identity在 asp.net core 2.1 web 应用的更改。 需要执行此操作以具有完全控制权限的identity  ui。

    public void configureservices(iservicecollection services)
        {
            services.configure<cookiepolicyoptions>(options =>
            {
                // this lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.checkconsentneeded = context => true;
                options.minimumsamesitepolicy = samesitemode.none;
            });

            services.adddbcontext<applicationdbcontext>(options =>
                options.usesqlserver(
                    configuration.getconnectionstring("defaultconnection")));

            services.addidentity<identityuser, identityrole>()
            //services.adddefaultidentity<identityuser>()
                .adddefaultui(uiframework.bootstrap4)
                .addentityframeworkstores<applicationdbcontext>();

            services.configure<identityoptions>(options =>
            {
                // password settings.
                options.password.requiredigit = true;
                options.password.requirelowercase = true;
                options.password.requirenonalphanumeric = true;
                options.password.requireuppercase = true;
                options.password.requiredlength = 6;
                options.password.requireduniquechars = 1;

                // lockout settings.
                options.lockout.defaultlockouttimespan = timespan.fromminutes(5);
                options.lockout.maxfailedaccessattempts = 5;
                options.lockout.allowedfornewusers = true;

                // user settings.
                options.user.allowedusernamecharacters =
                "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789-._@+";
                options.user.requireuniqueemail = false;
            });

            //services.configureapplicationcookie(options =>
            //{
            //    // cookie settings
            //    options.cookie.httponly = true;
            //    options.expiretimespan = timespan.fromminutes(5);

            //    options.loginpath = "/identity/account/login";
            //    options.accessdeniedpath = "/identity/account/accessdenied";
            //    options.slidingexpiration = true;
            //});

            services.configureapplicationcookie(options =>
            {
                // cookie settings
                options.cookie.httponly = true;
                options.expiretimespan = timespan.fromminutes(5);

                options.loginpath = $"/identity/account/login";
                options.logoutpath = $"/identity/account/logout";
                options.accessdeniedpath = $"/identity/account/accessdenied";
            });

            // services.addmvc().setcompatibilityversion(compatibilityversion.version_2_2);
            services.addmvc().setcompatibilityversion(compatibilityversion.version_2_1)
                .addrazorpagesoptions(options =>
                {
                    options.allowareas = true;
                    options.conventions.authorizeareafolder("identity", "/account/manage");
                    options.conventions.authorizeareapage("identity", "/account/logout");
                });
        }

     选择修改login.cshtml文件,在里面随变加点标记xxxx, 运行显示成功,以后就可以自定义样式布局和扩展权限功能。

 

     

   参考文献

   asp.net core 上的identity简介

   asp.net core 项目中的scaffold-identity

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网