.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<JsonResult> 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<Claim>(){
                                  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

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

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

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

 

最后实现登出功能:

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

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

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

 

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用ASP.NET Core自带的Identity框架来实现验证账号密码是否在数据库中。Identity框架提供了一套完整的用户身份验证和授权机制,包括用户注册、登录、注销和密码重置等功能,同时支持多种存储数据的方式,包括关系型数据库、非关系型数据库和文件存储等。 下面是一个简单的示例代码,用于验证用户名和密码是否匹配数据库中的记录: ```csharp // 引入命名空间 using Microsoft.AspNetCore.Identity; using System.Threading.Tasks; // 注入UserManager和SignInManager public class AccountController : Controller { private readonly UserManager<IdentityUser> _userManager; private readonly SignInManager<IdentityUser> _signInManager; public AccountController( UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager) { _userManager = userManager; _signInManager = signInManager; } [HttpPost] public async Task<IActionResult> Login(LoginViewModel model) { if (ModelState.IsValid) { // 验证用户名和密码是否匹配数据库中的记录 var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } return View(model); } } ``` 在上面的示例代码中,通过注入`UserManager`和`SignInManager`对象,并调用`PasswordSignInAsync`方法来验证用户名和密码是否匹配数据库中的记录。如果验证成功,则重定向到主页,否则返回错误信息。注意,在使用Identity框架时,需要在`Startup.cs`文件中进行配置和注册。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值