加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

ASP.NET Core身份验证

发布时间:2020-12-16 07:11:37 所属栏目:asp.Net 来源:网络整理
导读:asp.net core 身份验证 本文旨在演示如果使用内置的 identity 实现 asp.net core 的身份验证,不会进行其它扩展。本文将通过最简单的代码演示如何进行登录和身份验证操作。 使用Authentication 我们创建好 asp.net core 项目以后,需要在ConfigureServices中

asp.net core 身份验证

本文旨在演示如果使用内置的 identity 实现 asp.net core 的身份验证,不会进行其它扩展。本文将通过最简单的代码演示如何进行登录和身份验证操作。

使用Authentication

我们创建好 asp.net core 项目以后,需要在ConfigureServices中添加Authentication的服务配置,代码如下:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,o =>
    {
        o.LoginPath = new PathString("/Account/Login");
        o.AccessDeniedPath = new PathString("/Account/AccessDenied");
    });

然后,在Configure中添加上如下代码,注意,UseAuthentication要放在UseMvc前面。

app.UseAuthentication();
app.UseMvc().UseMvcWithDefaultRoute();

添加Account控制器

在完成第一步后,我们需要添加一个控制器,来进行登录、退出等操作,通常把这些功能放在AccountController中。关键代码如下:

/// <summary>
/// 登录页面
/// </summary>
/// <returns></returns>
public IActionResult Login()
{
    return View();
}

/// <summary>
/// 模拟登录
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> Login(string userName)
{
    //根据登录名获取用户身份,以及判断密码等操作
    var user = new SysUserIdentity { Name = userName,IsAuthenticated = true };

    if (user != null)
    {
        user.AuthenticationType = CookieAuthenticationDefaults.AuthenticationScheme;
        var identity = new ClaimsIdentity(user);
        identity.AddClaim(new Claim(ClaimTypes.Name,user.Name));

        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(identity));

        return Redirect("/Account");
    }
    ViewBag.Errormessage = "登录失败,用户名密码不正确";
    return View();
}

/// <summary>
/// 退出登录
/// </summary>
/// <returns></returns>
public async Task<IActionResult> Logout()
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return Redirect("/Account");
}

每一个Action的作用如下:

  • Login - Get:用来响应Get请求,提供用户输入用户名、密码的页面。
  • Login - Post:用来响应Post请求,对用户输入的用户名和密码进行验证,验证通过后分发票据
  • Logout - Get:用来响应Get请求,退出登录。

获取用户身份

当用户通过上面的代码登录以后,在用户访问其它页面时,我们需要获取到用户的身份,为了演示如何获取到身份信息,我们想AccountController中添加一个Index页面,代码如下:

/// <summary>
/// 获取登录人信息
/// </summary>
/// <returns></returns>
[Authorize]
public async Task<IActionResult> Index()
{
    var auth = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    if (auth.Succeeded)
    {
        string userName = auth.Principal.Identity.Name;
        //重新获取用户身份
        var user = new SysUserIdentity() { Name = userName,IsAuthenticated = true };
        return View(user);
    }

    return Redirect("~/Account/Login");
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读