浅谈如何在ASP.NET Core中实现一个基础的身份认证

 更新时间:2021年9月22日 10:05  点击:2206

ASP.NET终于可以跨平台了,但是不是我们常用的ASP.NET, 而是叫一个ASP.NET Core的新平台,他可以跨Windows, Linux, OS X等平台来部署你的web应用程序,你可以理解为,这个框架就是ASP.NET的下一个版本,相对于传统ASP.NET程序,它还是有一些不同的地方的,比如很多类库在这两个平台之间是不通用的。

今天首先我们在ASP.NET Core中来实现一个基础的身份认证,既登陆功能。

前期准备:

1.推荐使用 VS 2015 Update3 作为你的IDE,下载地址:https://www.jb51.net/softjc/446184.html

2.你需要安装.NET Core的运行环境以及开发工具,这里提供VS版:https://www.jb51.net/softs/472362.html

创建项目:

在VS中新建项目,项目类型选择ASP.NET Core Web Application (.NET Core), 输入项目名称为TestBasicAuthor。

接下来选择 Web Application, 右侧身份认证选择:No Authentication

打开Startup.cs

在ConfigureServices方法中加入如下代码:

services.AddAuthorization(); 

在Configure方法中加入如下代码:

app.UseCookieAuthentication(new CookieAuthenticationOptions 
{ 
  AuthenticationScheme = "Cookie", 
  LoginPath = new PathString("/Account/Login"), 
  AccessDeniedPath = new PathString("/Account/Forbidden"), 
  AutomaticAuthenticate = true, 
  AutomaticChallenge = true 
});

完整的代码应该是这样:

public void ConfigureServices(IServiceCollection services) 
{ 
  services.AddMvc(); 
 
  services.AddAuthorization(); 
} 
 
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
  app.UseCookieAuthentication(new CookieAuthenticationOptions 
  { 
    AuthenticationScheme = "Cookie", 
    LoginPath = new PathString("/Account/Login"), 
    AccessDeniedPath = new PathString("/Account/Forbidden"), 
    AutomaticAuthenticate = true, 
    AutomaticChallenge = true 
  }); 
 
  app.UseMvc(routes => 
  { 
    routes.MapRoute( 
       name: "default", 
       template: "{controller=Home}/{action=Index}/{id?}"); 
  }); 
}

你或许会发现贴进去的代码是报错的,这是因为还没有引入对应的包,进入报错的这一行,点击灯泡,加载对应的包就可以了。

在项目下创建一个文件夹命名为Model,并向里面添加一个类User.cs

代码应该是这样

public class User
{
  public string UserName { get; set; }
  public string Password { get; set; }
}

创建一个控制器,取名为:AccountController.cs

在类中贴入如下代码:

[HttpGet] 
public IActionResult Login() 
{ 
  return View(); 
} 
 
[HttpPost] 
public async Task<IActionResult> Login(User userFromFore) 
{ 
  var userFromStorage = TestUserStorage.UserList 
    .FirstOrDefault(m => m.UserName == userFromFore.UserName && m.Password == userFromFore.Password); 
 
  if (userFromStorage != null) 
  { 
    //you can add all of ClaimTypes in this collection 
    var claims = new List<Claim>() 
    { 
      new Claim(ClaimTypes.Name,userFromStorage.UserName) 
      //,new Claim(ClaimTypes.Email,"emailaccount@microsoft.com") 
    }; 
 
    //init the identity instances 
    var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin")); 
 
    //signin 
    await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties 
    { 
      ExpiresUtc = DateTime.UtcNow.AddMinutes(20), 
      IsPersistent = false, 
      AllowRefresh = false 
    }); 
 
    return RedirectToAction("Index", "Home"); 
  } 
  else 
  { 
    ViewBag.ErrMsg = "UserName or Password is invalid"; 
 
    return View(); 
  } 
} 
 
public async Task<IActionResult> Logout() 
{ 
  await HttpContext.Authentication.SignOutAsync("Cookie"); 
 
  return RedirectToAction("Index", "Home"); 
}

相同的文件里让我们来添加一个模拟用户存储的类

//for simple, I'm not using the database to store the user data, just using a static class to replace it.
public static class TestUserStorage
{
  public static List<User> UserList { get; set; } = new List<User>() {
    new User { UserName = "User1",Password = "112233"}
  };
}

接下来修复好各种引用错误。

完整的代码应该是这样

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TestBasicAuthor.Model;
using System.Security.Claims;
using Microsoft.AspNetCore.Http.Authentication;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace TestBasicAuthor.Controllers
{
  public class AccountController : Controller
  {
    [HttpGet]
    public IActionResult Login()
    {
      return View();
    }

    [HttpPost]
    public async Task<IActionResult> Login(User userFromFore)
    {
      var userFromStorage = TestUserStorage.UserList
        .FirstOrDefault(m => m.UserName == userFromFore.UserName && m.Password == userFromFore.Password);

      if (userFromStorage != null)
      {
        //you can add all of ClaimTypes in this collection 
        var claims = new List<Claim>()
        {
          new Claim(ClaimTypes.Name,userFromStorage.UserName) 
          //,new Claim(ClaimTypes.Email,"emailaccount@microsoft.com") 
        };

        //init the identity instances 
        var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin"));

        //signin 
        await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties
        {
          ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
          IsPersistent = false,
          AllowRefresh = false
        });

        return RedirectToAction("Index", "Home");
      }
      else
      {
        ViewBag.ErrMsg = "UserName or Password is invalid";

        return View();
      }
    }

    public async Task<IActionResult> Logout()
    {
      await HttpContext.Authentication.SignOutAsync("Cookie");

      return RedirectToAction("Index", "Home");
    }
  }

  //for simple, I'm not using the database to store the user data, just using a static class to replace it.
  public static class TestUserStorage
  {
    public static List<User> UserList { get; set; } = new List<User>() {
    new User { UserName = "User1",Password = "112233"}
  };
  }
}

在Views文件夹中创建一个Account文件夹,在Account文件夹中创建一个名位index.cshtml的View文件。

贴入如下代码:

@model TestBasicAuthor.Model.User

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
</head>
<body>
  @using (Html.BeginForm())
  {
    <table>
      <tr>
        <td></td>
        <td>@ViewBag.ErrMsg</td>
      </tr>
      <tr>
        <td>UserName</td>
        <td>@Html.TextBoxFor(m => m.UserName)</td>
      </tr>
      <tr>
        <td>Password</td>
        <td>@Html.PasswordFor(m => m.Password)</td>
      </tr>
      <tr>
        <td></td>
        <td><button>Login</button></td>
      </tr>
    </table>
  }
</body>
</html>

打开HomeController.cs

添加一个Action, AuthPage.

[Authorize]
[HttpGet]
public IActionResult AuthPage()
{
  return View();
}

在Views/Home下添加一个视图,名为AuthPage.cshtml

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
</head>
<body>
  <h1>Auth page</h1>

  <p>if you are not authorized, you can't visit this page.</p>
</body>
</html>

到此,一个基础的身份认证就完成了,核心登陆方法如下:

await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties
{
  ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
  IsPersistent = false,
  AllowRefresh = false
});

启用验证如下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
  app.UseCookieAuthentication(new CookieAuthenticationOptions
  {
    AuthenticationScheme = "Cookie",
    LoginPath = new PathString("/Account/Login"),
    AccessDeniedPath = new PathString("/Account/Forbidden"),
    AutomaticAuthenticate = true,
    AutomaticChallenge = true
  });
}

在某个Controller或Action添加[Author],即可配置位需要登陆验证的页面。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章

  • ASP.NET购物车实现过程详解

    这篇文章主要为大家详细介绍了ASP.NET购物车的实现过程,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-22
  • .NET Core下使用Kafka的方法步骤

    这篇文章主要介绍了.NET Core下使用Kafka的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • 在ASP.NET 2.0中操作数据之七十二:调试存储过程

    在开发过程中,使用Visual Studio的断点调试功能可以很方便帮我们调试发现程序存在的错误,同样Visual Studio也支持对SQL Server里面的存储过程进行调试,下面就让我们看看具体的调试方法。...2021-09-22
  • Win10 IIS 安装.net 4.5的方法

    这篇文章主要介绍了Win10 IIS 安装及.net 4.5及Win10安装IIS并配置ASP.NET 4.0的方法,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-22
  • 详解.NET Core 3.0 里新的JSON API

    这篇文章主要介绍了详解.NET Core 3.0 里新的JSON API,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • .net数据库操作框架SqlSugar的简单入门

    这篇文章主要介绍了.net数据库操作框架SqlSugar的简单入门,帮助大家更好的理解和学习使用.net技术,感兴趣的朋友可以了解下...2021-09-22
  • ASP.NET Core根据环境变量支持多个 appsettings.json配置文件

    这篇文章主要介绍了ASP.NET Core根据环境变量支持多个 appsettings.json配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • 记一次EFCore类型转换错误及解决方案

    这篇文章主要介绍了记一次EFCore类型转换错误及解决方案,帮助大家更好的理解和学习使用asp.net core,感兴趣的朋友可以了解下...2021-09-22
  • 详解ASP.NET Core 中基于工厂的中间件激活的实现方法

    这篇文章主要介绍了ASP.NET Core 中基于工厂的中间件激活的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-22
  • C#使用Ado.Net更新和添加数据到Excel表格的方法

    这篇文章主要介绍了C#使用Ado.Net更新和添加数据到Excel表格的方法,较为详细的分析了OLEDB的原理与使用技巧,可实现较为方便的操作Excel数据,需要的朋友可以参考下...2020-06-25
  • .NET C#利用ZXing生成、识别二维码/条形码

    ZXing是一个开放源码的,用Java实现的多种格式的1D/2D条码图像处理库,它包含了联系到其他语言的端口。这篇文章主要给大家介绍了.NET C#利用ZXing生成、识别二维码/条形码的方法,文中给出了详细的示例代码,有需要的朋友们可以参考借鉴。...2020-06-25
  • asp.net通过消息队列处理高并发请求(以抢小米手机为例)

    这篇文章主要介绍了asp.net通过消息队列处理高并发请求(以抢小米手机为例),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • ASP.NET单选按钮控件RadioButton常用属性和方法介绍

    RadioButton又称单选按钮,其在工具箱中的图标为 ,单选按钮通常成组出现,用于提供两个或多个互斥选项,即在一组单选钮中只能选择一个...2021-09-22
  • Underscore源码分析

    Underscore 是一个 JavaScript 工具库,它提供了一整套函数式编程的实用功能,但是没有扩展任何 JavaScript 内置对象。这篇文章主要介绍了underscore源码分析相关知识,感兴趣的朋友一起学习吧...2016-01-02
  • ASP.NET 2.0中的数据操作:使用两个DropDownList过滤的主/从报表

    在前面的指南中我们研究了如何显示一个简单的主/从报表, 该报表使用DropDownList和GridView控件, DropDownList填充类别,GridView显示选定类别的产品. 这类报表用于显示具有...2016-05-19
  • 详解.NET Core 使用HttpClient SSL请求出错的解决办法

    这篇文章主要介绍了.NET Core 使用HttpClient SSL请求出错的解决办法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2021-09-22
  • Python调用.NET库的方法步骤

    这篇文章主要介绍了Python调用.NET库的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-05-09
  • ASP.NET中iframe框架点击左边页面链接 右边显示链接页面内容

    这篇文章主要介绍了ASP.NET中iframe框架点击左边页面链接,右边显示链接页面内容的实现代码,感兴趣的小伙伴们可以参考一下...2021-09-22
  • 创建一个完整的ASP.NET Web API项目

    ASP.NET Web API具有与ASP.NET MVC类似的编程方式,ASP.NET Web API不仅仅具有一个完全独立的消息处理管道,而且这个管道比为ASP.NET MVC设计的管道更为复杂,功能也更为强大。下面创建一个简单的Web API项目,需要的朋友可以参考下...2021-09-22
  • ASP.NET连接MySql数据库的2个方法及示例

    这篇文章主要介绍了ASP.NET连接MySql数据库的2个方法及示例,使用的是MySQL官方组件和ODBC.NET,需要的朋友可以参考下...2021-09-22