.Net Core 登陆验证

为了实现用户登录前无法直接通过地址栏进入主页面,实现登录验证功能

 

 Startup.cs 配置服务和中间件:

public void ConfigureServices(IServiceCollection services)
        {

            //添加授权支持,并添加使用Cookie的方式,配置登录页面和没有权限时的跳转页面
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
                {
                    o.LoginPath = new PathString("/Home/Login");            //登录路径:这是当用户试图访问资源但未经过身份验证时,程序将会将请求重定向到这个相对路径。
                    o.AccessDeniedPath = new PathString("/Home/Error");     //禁止访问路径:当用户试图访问资源时,但未通过该资源的任何授权策略,请求将被重定向到这个相对路径。
                    o.SlidingExpiration = true; //Cookie可以分为永久性的和临时性的。 临时性的是指只在当前浏览器进程里有效,浏览器一旦关闭就失效(被浏览器删除)。 永久性的是指Cookie指定了一个过期时间,在这个时间到达之前,此cookie一直有效(浏览器一直记录着此cookie的存在)。 slidingExpriation的作用是,指示浏览器把cookie作为永久性cookie存储,但是会自动更改过期时间,以使用户不会在登录后并一直活动,但是一段时间后却自动注销。也就是说,你10点登录了,服务器端设置的TimeOut为30分钟,如果slidingExpriation为false,那么10: 30以后,你就必须重新登录。如果为true的话,你10: 16分时打开了一个新页面,服务器就会通知浏览器,把过期时间修改为10: 46。
                });
        }
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseAuthentication(); //身份验证中间件
        }

后台Login方法:

public async Task Login(string uName,string password)
        {
           try
            {
                if (string.IsNullOrEmpty(uName) || string.IsNullOrEmpty(password))
                {
                    return Json(new { result = false, msg = "请完善信息后登录" });
                }
                string strSql = "select * from t_user where userName=@userName and password =@password";
                DataTable dt = DBHelper.GetDataTable(strSql, new MySqlParameter("@userName", uName), new MySqlParameter("@password", password));
                if (dt !=null)
                {
                    #region 登录认证,存入Cookie
                        //登录认证,存入Cookie
                        var claims = new List(){
                                  new Claim(ClaimTypes.Name,uName),new Claim("password",password),new Claim("roleID",dt.Rows[0]["roleID"].ToString())
                               };
                        //init the identity instances 
                        var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));
                        //signin 
                        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
                        {
                            ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                            IsPersistent = false,
                            AllowRefresh = false
                        });
                    #endregion
                    return Json(new { result = true, userName=dt.Rows[0]["userName"], password = dt.Rows[0]["password"], roleID = dt.Rows[0]["roleID"] });
                }
                else
                {
                    return Json(new { result = false,msg= "用户名或密码输入错误,请重新输入" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { result = false, msg = "登录失败" + ex.Message });
            }
        }

注:Login方法红框的配置必须与Startup.cs配置一样

Login

startup.cs

然后在控制器页面方法上加上特性过滤

.Net Core 登陆验证_第1张图片

[Authorize] :进行登陆验证,验证通过后才能进入页面,否则跳转到设置好的页面地址

[AllowAnonymous]:跳过验证,加上该标签就可以在登陆验证时跳过该方法,一般加在登陆页上

 

最后实现登出功能:

public async Task Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return Json(new { msg = "退出成功" });
        }

一句话就ok,依然要注意 这里用的是.SignOutAsync,而不是.SignInAsync,CookieAuthenticationDefaults.AuthenticationScheme ,也必须和配置的一样。

以上就是一个简单的.NET Core 登陆验证。

 

你可能感兴趣的:(ASP.NET,Core)