欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-09 15:47:40
asp.net core 2最简单的登录功能 源代码在此 创建asp.net core Web Mvc项目 配置下选项 项目目录结构 在Models文件夹下新建两个实体类 在项目文件夹下新建Data文件夹,新建DbContext类 在Startup.cs文件中的ConfigureServices下添 ......

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

 源代码在此

创建asp.net core web mvc项目

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

配置下选项

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

项目目录结构

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

 

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

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

    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类

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

 

    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服务

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

 

        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下配置数据库连接字符串

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

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

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

 

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

 

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

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

 

添加控制器和视图

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

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

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

 

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

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

 

在homecontroller中编写一个login方法

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

 

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中添加一个导航栏

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

 

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

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

 

就可以启动项目。

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

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

 

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

 

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

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