zoukankan      html  css  js  c++  java
  • ASP.NET Core身份验证

    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");
    }
    
  • 相关阅读:
    Hibernate映射之数组属性, 集合属性(list、set和map)
    org.hibernate.type.SerializationException: could not deserialize 反序列化失败
    linux下同一个tomcat部署多个项目
    Nexus私服 Maven
    maven 父子项目 聚合与继承 生命周期 打包插件 依赖打包 jar pom war
    IDEA中创建Web聚合项目(Maven多模块项目)
    为什么要在linux命令前加上 ./ 什么时候才需要在命令前加上./
    web.xml 介绍 and pom.xml 介绍
    有趣的linux命令
    SpringMVC 中常见注释
  • 原文地址:https://www.cnblogs.com/youring2/p/10886129.html
Copyright © 2011-2022 走看看