热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

怎么在ASP.NETCore中实现一个身份认证功能

怎么在ASP.NETCore中实现一个身份认证功能?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到

怎么在ASP.NET Core中实现一个身份认证功能?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

创建项目:

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

怎么在ASP.NET Core中实现一个身份认证功能

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

怎么在ASP.NET Core中实现一个身份认证功能

打开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?}"); 
  }); 
}

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

怎么在ASP.NET Core中实现一个身份认证功能

在项目下创建一个文件夹命名为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 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() 
    { 
      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 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 UserList { get; set; } = new List() {
    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 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()
        {
          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 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 UserList { get; set; } = new List() {
    new User { UserName = "User1",Password = "112233"}
  };
  }
}

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

贴入如下代码:

@model TestBasicAuthor.Model.User



  


  @using (Html.BeginForm())
  {
    
      
        
        
      
      
        
        
      
      
        
        
      
      
        
        
      
    
@ViewBag.ErrMsg
UserName@Html.TextBoxFor(m => m.UserName)
Password@Html.PasswordFor(m => m.Password)
  }

打开HomeController.cs

添加一个Action, AuthPage.

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

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


  


  

Auth page

  

if you are not authorized, you can't visit this page.

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

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
  });
}

关于怎么在ASP.NET Core中实现一个身份认证功能问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注编程笔记行业资讯频道了解更多相关知识。


推荐阅读
  • 本文讨论了如何使用Web.Config进行自定义配置节的配置转换。作者提到,他将msbuild设置为详细模式,但转换却忽略了带有替换转换的自定义部分的存在。 ... [详细]
  • 本文介绍了Web学习历程记录中关于Tomcat的基本概念和配置。首先解释了Web静态Web资源和动态Web资源的概念,以及C/S架构和B/S架构的区别。然后介绍了常见的Web服务器,包括Weblogic、WebSphere和Tomcat。接着详细讲解了Tomcat的虚拟主机、web应用和虚拟路径映射的概念和配置过程。最后简要介绍了http协议的作用。本文内容详实,适合初学者了解Tomcat的基础知识。 ... [详细]
  • 开发笔记:Java是如何读取和写入浏览器Cookies的
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Java是如何读取和写入浏览器Cookies的相关的知识,希望对你有一定的参考价值。首先我 ... [详细]
  • 本文介绍了ASP.NET Core MVC的入门及基础使用教程,根据微软的文档学习,建议阅读英文文档以便更好理解,微软的工具化使用方便且开发速度快。通过vs2017新建项目,可以创建一个基础的ASP.NET网站,也可以实现动态网站开发。ASP.NET MVC框架及其工具简化了开发过程,包括建立业务的数据模型和控制器等步骤。 ... [详细]
  • http:my.oschina.netleejun2005blog136820刚看到群里又有同学在说HTTP协议下的Get请求参数长度是有大小限制的,最大不能超过XX ... [详细]
  • 在重复造轮子的情况下用ProxyServlet反向代理来减少工作量
    像不少公司内部不同团队都会自己研发自己工具产品,当各个产品逐渐成熟,到达了一定的发展瓶颈,同时每个产品都有着自己的入口,用户 ... [详细]
  • imx6ull开发板驱动MT7601U无线网卡的方法和步骤详解
    本文详细介绍了在imx6ull开发板上驱动MT7601U无线网卡的方法和步骤。首先介绍了开发环境和硬件平台,然后说明了MT7601U驱动已经集成在linux内核的linux-4.x.x/drivers/net/wireless/mediatek/mt7601u文件中。接着介绍了移植mt7601u驱动的过程,包括编译内核和配置设备驱动。最后,列举了关键词和相关信息供读者参考。 ... [详细]
  • ASP.NET2.0数据教程之十四:使用FormView的模板
    本文介绍了在ASP.NET 2.0中使用FormView控件来实现自定义的显示外观,与GridView和DetailsView不同,FormView使用模板来呈现,可以实现不规则的外观呈现。同时还介绍了TemplateField的用法和FormView与DetailsView的区别。 ... [详细]
  • web.py开发web 第八章 Formalchemy 服务端验证方法
    本文介绍了在web.py开发中使用Formalchemy进行服务端表单数据验证的方法。以User表单为例,详细说明了对各字段的验证要求,包括必填、长度限制、唯一性等。同时介绍了如何自定义验证方法来实现验证唯一性和两个密码是否相等的功能。该文提供了相关代码示例。 ... [详细]
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • 本文介绍了在CentOS上安装Python2.7.2的详细步骤,包括下载、解压、编译和安装等操作。同时提供了一些注意事项,以及测试安装是否成功的方法。 ... [详细]
  • React项目中运用React技巧解决实际问题的总结
    本文总结了在React项目中如何运用React技巧解决一些实际问题,包括取消请求和页面卸载的关联,利用useEffect和AbortController等技术实现请求的取消。文章中的代码是简化后的例子,但思想是相通的。 ... [详细]
  • 树莓派语音控制的配置方法和步骤
    本文介绍了在树莓派上实现语音控制的配置方法和步骤。首先感谢博主Eoman的帮助,文章参考了他的内容。树莓派的配置需要通过sudo raspi-config进行,然后使用Eoman的控制方法,即安装wiringPi库并编写控制引脚的脚本。具体的安装步骤和脚本编写方法在文章中详细介绍。 ... [详细]
  • 本文记录了在vue cli 3.x中移除console的一些采坑经验,通过使用uglifyjs-webpack-plugin插件,在vue.config.js中进行相关配置,包括设置minimizer、UglifyJsPlugin和compress等参数,最终成功移除了console。同时,还包括了一些可能出现的报错情况和解决方法。 ... [详细]
  • Asp.net Mvc Framework 七 (Filter及其执行顺序) 的应用示例
    本文介绍了在Asp.net Mvc中应用Filter功能进行登录判断、用户权限控制、输出缓存、防盗链、防蜘蛛、本地化设置等操作的示例,并解释了Filter的执行顺序。通过示例代码,详细说明了如何使用Filter来实现这些功能。 ... [详细]
author-avatar
恋之-风景-
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有