• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >ASP.NET > 浅谈如何在ASP.NET Core中实现一个基础的身份认证

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

作者:微软一站式示例代码库 字体:[增加 减小] 来源:互联网 时间:2017-05-11

微软一站式示例代码库通过本文主要向大家介绍了浅谈中国酒文化论文,浅谈执业药师的作用,浅谈和田玉的且末料,浅谈应收账款的论文,浅谈等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

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

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

前期准备:

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

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

创建项目:

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

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

打开Startup.cs

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

services.AddAuthorization(); 
</div>

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

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

完整的代码应该是这样:

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?}"); 
  }); 
}
</div>

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

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

代码应该是这样

public class User
{
  public string UserName { get; set; }
  public string Password { get; set; }
}
</div>

创建一个控制器,取名为: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"); 
}
</div>

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

//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"}
  };
}
</div>

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

完整的代码应该是这样

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

</div>

在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>
      &l



 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • 浅谈如何在ASP.NET Core中实现一个基础的身份认证
  • 浅谈ASP.NET中多层架构
  • 浅谈ASP.NET中MVC 4 的JS/CSS打包压缩功能
  • 浅谈c#设计模式之单一原则
  • 浅谈.net平台下深拷贝和浅拷贝
  • 浅谈.NET中加密和解密的实现方法分享
  • 浅谈类型转换操作符is/as

相关文章

  • 2018-08-20WebApiClient的接口输入验证方法
  • 2017-05-11Asp.net下载功能的解决方案代码
  • 2017-05-11ASP.NET笔记之广告控件的使用方法
  • 2017-05-11在C#中生成与PHP一样的MD5 Hash Code的方法
  • 2017-05-11ASP.NET服务器端控件RadioButtonList,DropDownList,CheckBoxList的取值、赋值用法
  • 2017-05-11asp.net实现调用存储过程并带返回值的方法
  • 2017-05-11ASP.NET中弹出消息框的几种常见方法
  • 2017-05-11用CSS实现图片倾斜 只支持IE
  • 2017-05-11ASP.NET中FileUpload文件上传控件应用实例
  • 2017-05-11C#将DataTable转化为List<T>

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • asp.net System.Net.Mail 发送邮件
    • 解读ASP.NET 5 & MVC6系列教程(12):基于Lamda表达式的强类型Routing实现
    • vb 中的MD5加密在asp.net中的实现
    • ADO.Net对oracle数据库操作的实例代码
    • ASP.NET实现根据URL生成网页缩略图的方法
    • asp.net 的错误处理机制讲解
    • 详解ASP.NET验证码的生成方法
    • asp.net Ext grid 显示列表
    • ASP.NET Core与NLog集成的完整步骤
    • ASP.NET数组删除重复值实现代码

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有