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

更多脚本样例, 访问微软One Code样例库:http://aka.ms/onescriptsamples 更多代码样例, 访问微软One Script样例库:http://aka.ms/onecodesamples

Core身份认证的更多相关文章

  1. .Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书

    原文:.Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书 一.客户端模式介绍 客户端模式(Client Credentials Grant)是指客户 ...

  2. 深入解读 ASP.NET Core 身份认证过程

    长话短说:上文我们讲了 ASP.NET Core 基于声明的访问控制到底是什么鬼? 今天我们乘胜追击:聊一聊ASP.NET Core 中的身份验证. 身份验证是确定用户身份的过程. 授权是确定用户是否 ...

  3. .Net Core:身份认证组件

    类库组件 .NET Core的身份认证使用的类库如下图:常用的 Microsoft.AspNetCore.Authorization Microsoft.AspNetCore.Authorizatio ...

  4. .NET 黑魔法 - asp.net core 身份认证 - Policy

    身份认证几乎是每个项目都要集成的功能,在面向接口(Microservice)的系统中,我们需要有跨平台,多终端支持等特性的认证机制,基于token的认证方式无疑是最好的方案.今天我们就来介绍下在.Ne ...

  5. ASP.NET Core 身份认证 (Identity、Authentication)

    Authentication和Authorization 每每说到身份验证.认证的时候,总不免说提及一下这2个词.他们的看起来非常的相似,但实际上他们是不一样的. Authentication想要说明 ...

  6. asp.net core 身份认证/权限管理系统简介及简单案例

    如今的网站大多数都离不开账号注册及用户管理,而这些功能就是通常说的身份验证.这些常见功能微软都为我们做了封装,我们只要利用.net core提供的一些工具就可以很方便的搭建适用于大部分应用的权限管理系 ...

  7. .Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式

    一.客户端模式介绍 客户端模式(Client Credentials Grant)是指客户端直接向认证服务(Authorization Server)发送认证请求,获取token,进行认证,一般适用于 ...

  8. Aspen.net core 身份认证

  9. 在ASP.NET Core中使用Angular2,以及与Angular2的Token base身份认证

    注:下载本文提到的完整代码示例请访问:How to authorization Angular 2 app with asp.net core web api 在ASP.NET Core中使用Angu ...

随机推荐

  1. 数据库知识(主要基于Oracle,Sql可参考)

    1.关于Union的知识 select 11 from dual union select 11 from dual 和 select 11 from dual union all select 11 ...

  2. 数据加工处理拼sql

    @Override public void offonShareBill(Boolean fg, Map<String,String[]> map) throws BusinessExce ...

  3. Java 专业人士必备的书籍和网站列表

    对于 Java™ 语言开发人员来说,信息过量是一个真正的问题.每个新入行的程序员都要面临一个令人畏缩的挑战:要进入的行业是一个具有海量知识的行业.要了解的东西简直 太多了.对于有经验的老手来说,情况只 ...

  4. 【网络收集】order by 自定义排序

    使用order by排序,有时候不是根据字符或数字顺序,而是根据实际要求排序. 例如有客户A,B,C,我希望排序结果是B,C,A,那么就要通过自定义的规则排序. 第一种方法,可以构造一张映射表,将客户 ...

  5. 50个常用的笔试、面试sql语句

    50个常用的笔试.面试sql语句 2009-12-17 15:05   Student(S#,Sname,Sage,Ssex) 学生表Course(C#,Cname,T#) 课程表SC(S#,C#,s ...

  6. js 调用php代码

    <?php $test = "var a = ".$_GET['test'].";"; ?> <mce:script type="t ...

  7. Javascript加载速度慢解决办法

    通常我们的网站里面会加载一些js代码,统计啊,google广告啊,百度同盟啊,阿里妈妈广告代码啊,一堆,最后弄得页面加载速度很慢,很慢.解决办法:换一个js包含的方式,让javascript加载速度倍 ...

  8. 基于系统的UIMenuController的使用及自定义UIMenuItem

    1.前言 在开发中 UIMenuController 用得较少,偶尔遇到了,一时竟想不起来,因此做个回顾 2.系统默认支持 UIMenuController 的UI控件 UITextField UIT ...

  9. AMQ学习笔记 - 15. 实践方案:基于ActiveMQ的统一日志服务

    概述 以ActiveMQ + Log4j + Spring的技术组合,实现基于消息队列的统一日志服务. 参考:Spring+Log4j+ActiveMQ实现远程记录日志——实战+分析 与参考文章的比较 ...

  10. 移动Web轮播图IOS卡顿的问题

    晚饭前,被测试吐槽说,banner轮播手动左右滑的时候会卡顿.我一看不科学啊,大水果手机怎么会卡顿.我一看测试手中拿的是iPod,我觉得大概是这小玩意性能不强悍,后来又拿来5S,依然会卡顿,有趣的是, ...