当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net core 登录身份认证(Cookie)

asp.net core 登录身份认证(Cookie)

2018年12月20日  | 移动技术网IT编程  | 我要评论

西八府塘,致青春签名,薄荷

asp.net core 2最简单的登录功能

 源代码在此

创建asp.net core web mvc项目

配置下选项

项目目录结构

 

在models文件夹下新建两个实体类

    public class test
    {
        public int id { get; set; }
        [required]
        [display(name = "某人")]
        public string someone { get; set; }
        [required]
        [display(name = "某事")]
        public string something { get; set; }

    }
    public class user
    {
        public int id { get; set; }
        [required]
        [display(name = "用户名")]
        public string username { get; set; }
        [display(name = "密码")]
        [required]
        public string userpwd { get; set; }
        public string nothing { get; set; }
    }

在项目文件夹下新建data文件夹,新建dbcontext类

 

    public class mydbcontext:dbcontext
    {
        public mydbcontext(dbcontextoptions<mydbcontext> options) : base(options) { }

        public dbset<user> users { get; set; }
        public dbset<test> tests { get; set; }
    }

 

在startup.cs文件中的configureservices下添加dbcontext服务

 

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

            //sqlserver
            services.adddbcontext<mydbcontext>(x => x.usesqlserver(configuration.getconnectionstring("defaultconnection")));


            services.addmvc().setcompatibilityversion(compatibilityversion.version_2_2);
        }

在appsettings.json下配置数据库连接字符串

打开程序包管理器控制台,执行生成数据库上下文和创建更新数据库命令

 

 

去数据库查看下表是否生成,并直接添加一个种子数据。

 

添加控制器和视图

 

生成之后的项目结构目录如下

 

在homecontroller中编写一个login方法

 

public class homecontroller : controller
    {
        private readonly mydbcontext _context;

        public homecontroller(mydbcontext context)
        {
            _context = context;
        }
        public iactionresult index()
        {
            return view();
        }

        public iactionresult privacy()
        {
            return view();
        }

        [responsecache(duration = 0, location = responsecachelocation.none, nostore = true)]
        public iactionresult error()
        {
            return view(new errorviewmodel { requestid = activity.current?.id ?? httpcontext.traceidentifier });
        }

        [httppost]
        public async task<iactionresult> login(user user)
        {
            var loginuser = await _context.users.firstordefaultasync(u => u.username == user.username);
            if (loginuser == null)
                return badrequest("没有该用户");
            if (loginuser.userpwd != user.userpwd)
                return badrequest("密码错误");

            //声明对象创建
            var claims = new list<claim>
            {
                new claim(claimtypes.name, user.username)
            };
            claimsidentity useridentity = new claimsidentity(claims, "login");
            claimsprincipal principal = new claimsprincipal(useridentity);
            await httpcontext.signinasync(principal);
            //写入httpcontext

            return redirecttoaction("index", "test");
        }
    }

在startup中添加cookie认证服务并使用

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

            //sqlserve
            services.adddbcontext<mydbcontext>(x => x.usesqlserver(configuration.getconnectionstring("defaultconnection")));

            //添加cookie认证服务
            services.addauthentication(cookieauthenticationdefaults.authenticationscheme)
            .addcookie(options =>
            {
                options.loginpath = "/home/index/";

            });


            services.addmvc().setcompatibilityversion(compatibilityversion.version_2_2);
        }

        // 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();
            }
            else
            {
                app.useexceptionhandler("/home/error");
            }

            //使用认证服务
            app.useauthentication();

            app.usestaticfiles();
            app.usecookiepolicy();

            app.usemvc(routes =>
            {
                routes.maproute(
                    name: "default",
                    template: "{controller=home}/{action=index}/{id?}");
            });
        }

修改views/home/index.cshtml为下面内容

@model cookieauth.models.user
@{
    viewdata["title"] = "home page";
}
<div class="row">
    <div class="col-md-4">
        <section>
            <form method="post" asp-action="login">
                <h4>login</h4>
                <hr />

                <div class="form-group">
                    <label asp-for="username"></label>
                    <input asp-for="username" class="form-control" />
                </div>

                <div class="form-group">
                    <label asp-for="userpwd"></label>
                    <input asp-for="userpwd" type="password" class="form-control" />
                </div>

                <div class="form-group">
                    <button type="submit" class="btn btn-default">登录</button>
                </div>

            </form>
        </section>
    </div>
</div>

在_layout中添加一个导航栏

 

然后在test控制器中添加认证特性

 

就可以启动项目。

如果不没输入正确的地址是会被重定向到登录页面。

 

 

就这样先,如果是已有项目 只需要在startup中添加cookie认证服务以及在login和logout方法中创建和销毁声明。

在controller或者action中添加启动认证或者不启用认证随意配置

 

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

相关文章:

验证码:
移动技术网