如何在ASP.NET Core中实现一个基础的身份认证
注:本文提到的代码示例下载地址> How to achieve a basic authorization in ASP.NET Core
如何在ASP.NET Core中实现一个基础的身份认证
ASP.NET终于可以跨平台了,但是不是我们常用的ASP.NET, 而是叫一个ASP.NET Core的新平台,他可以跨Windows, Linux, OS X等平台来部署你的web应用程序,你可以理解为,这个框架就是ASP.NET的下一个版本,相对于传统ASP.NET程序,它还是有一些不同的地方的,比如很多类库在这两个平台之间是不通用的。
今天首先我们在ASP.NET Core中来实现一个基础的身份认证,既登陆功能。
前期准备:
1.推荐使用 VS 2015 Update3 作为你的IDE,下载地址:www.visualstudio.com
2.你需要安装.NET Core的运行环境以及开发工具,这里提供VS版:www.microsoft.com/net/core
创建项目:
在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],即可配置位需要登陆验证的页面。
最后:如何运行这个Sample以及下载完整的代码请访问:How to achieve a basic authorization in ASP.NET Core
如何在ASP.NET Core中实现一个基础的身份认证的更多相关文章
- [转]如何在ASP.NET Core中实现一个基础的身份认证
本文转自:http://www.cnblogs.com/onecodeonescript/p/6015512.html 注:本文提到的代码示例下载地址> How to achieve a bas ...
- 如何在ASP.NET Core中实现CORS跨域
注:下载本文的完整代码示例请访问 > How to enable CORS(Cross-origin resource sharing) in ASP.NET Core 如何在ASP.NET C ...
- 如何在ASP.NET Core中应用Entity Framework
注:本文提到的代码示例下载地址> How to using Entity Framework DB first in ASP.NET Core 如何在ASP.NET Core中应用Entity ...
- 如何在ASP.NET Core中使用Azure Service Bus Queue
原文:USING AZURE SERVICE BUS QUEUES WITH ASP.NET CORE SERVICES 作者:damienbod 译文:如何在ASP.NET Core中使用Azure ...
- 如何在ASP.NET Core中自定义Azure Storage File Provider
文章标题:如何在ASP.NET Core中自定义Azure Storage File Provider 作者:Lamond Lu 地址:https://www.cnblogs.com/lwqlun/p ...
- 如何在ASP.NET Core中使用JSON Patch
原文: JSON Patch With ASP.NET Core 作者:.NET Core Tutorials 译文:如何在ASP.NET Core中使用JSON Patch 地址:https://w ...
- [翻译] 如何在 ASP.Net Core 中使用 Consul 来存储配置
[翻译] 如何在 ASP.Net Core 中使用 Consul 来存储配置 原文: USING CONSUL FOR STORING THE CONFIGURATION IN ASP.NET COR ...
- [译]如何在ASP.NET Core中实现面向切面编程(AOP)
原文地址:ASPECT ORIENTED PROGRAMMING USING PROXIES IN ASP.NET CORE 原文作者:ZANID HAYTAM 译文地址:如何在ASP.NET Cor ...
- 如何在 ASP.Net Core 中使用 Serilog
记录日志的一个作用就是方便对应用程序进行跟踪和排错调查,在实际应用上都是引入 日志框架,但如果你的 日志文件 包含非结构化的数据,那么查询起来将是一个噩梦,所以需要在记录日志的时候采用结构化方式. 将 ...
随机推荐
- 利用Python进行数据分析(14) pandas基础: 数据转换
数据转换指的是对数据的过滤.清理以及其他的转换操作. 移除重复数据 DataFrame里经常会出现重复行,DataFrame提供一个duplicated()方法检测各行是否重复,另一个drop_dup ...
- iOS Interface Builder:在.xib文件中加载另一个.xib文件
在开发中,经常会用到一个需要重复使用的模块,比如好友列表中每个用户的展示或每条动态,这些都是相同的模版,这样我们就可以把这个部分提取出来放到一个单独的.xib中.那么提取出的.xib如何在其他.xib ...
- 『.NET Core CLI工具文档』(十二)dotnet-pack
说明:本文是个人翻译文章,由于个人水平有限,有不对的地方请大家帮忙更正. 原文:dotnet-pack 翻译:dotnet-pack 名称 dotnet-pack - 将代码打包成 NuGet 包 概 ...
- App内测神器之蒲公英
一.前言部分 没使用蒲公英之前一直采用非常傻B的方式给公司App做内部测试,要么发个测试包让公司测试人员用iTUnes 自己安装 要么苦逼的一个个在我Xcode上直接安装测试包,操作起来又麻烦又苦逼, ...
- poj1698--最大流(Dinic)
题目大意: 爱丽丝要拍电影,有n部电影,规定爱丽丝每天只能拍一部电影,每部电影在每个礼拜只有固定的几天可以拍电影,只可以拍前面w个礼拜,并且这部电影要拍d天,问爱丽丝能不能拍完所有的电影. 思路: 建 ...
- Android事件总线
Android中Activity.Service.Fragment之间的相互通信比较麻烦,主要有以下一些方法: (1)使用广播,发送者发出广播,接收者接收广播后进行处理: (2)使用Handler和M ...
- VMware安装CentOS时,无法以图形界面安装解决办法
有的同学问: 用虚拟机软件(vmware.VirtualBox)安装CentOS系统时, 安装过程中没有中文,也没有出现图形界面,都是以命令行方式去安装, 有时候又会出现图形界面,不知道哪里配置的问题 ...
- MyEclipse相关部署问题
部署Tomcat如果用MyEclipse自动部署方式很有可能出现一个问题: 服务器关联的这个项目却关联到其他的项目上,导致运行时还在运行以前的项目 解决方法: 将状态提示栏的service里的tomc ...
- Atitit.java c#.net php项目中的view复用(jsp,aspx,php的复用)
Atitit.java c#.net php项目中的view复用(jsp,aspx,php的复用) 1.1. Keyword1 1.2. 前言1 2. Java项目使用.Net的aspx页面view1 ...
- 如何在Node.js中合并两个复杂对象
通常情况下,在Node.js中我们可以通过underscore的extend或者lodash的merge来合并两个对象,但是对于像下面这种复杂的对象,要如何来应对呢? 例如我有以下两个object: ...