准备工作

新建MVC项目,然后用VSCode打开

dotnet new mvc --name MvcCookieAuthSample

在Controllers文件夹下新建AdminController.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MvcCookieAuthSample.Models; namespace MvcCookieAuthSample.Controllers
{
public class AdminController : Controller
{
public IActionResult Index()
{
return View();
}
}
}

在Views文件夹下新建Admin文件夹,并在Admin文件夹下新建Index.cshtml

@{
ViewData["Title"] = "Admin";
}
<h2>@ViewData["Title"]</h2> <p>Admin Page</p>

运行结果:

Cookie-based认证实现

在AdminController中添加引用

using Microsoft.AspNetCore.Authorization;

然后我们可以给AdminController添加 [Authorize] 标签

接下来我们需要把认证和授权引用进来,我们使用的是cookie的认证方式,所以在Startup.cs中添加认证的引用。

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

然后在Startup方法中进行cookie的依赖注入

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options=>{//自定义登陆地址,不配置的话则默认为http://localhost:5000/Account/Login
options.LoginPath="/Account/MyLogin";
});

然后我们要在Configure方法中把cookie中间件也添加进来,否则认证授权是不会生效的

app.UseAuthentication();

这时候我们再运行一下:

发现已经自动跳转到登陆地址了。

模拟登陆

我们暂时不做登陆的,只是模拟一下登陆,首先我们创建一个AccountController.cs

然后添加引用

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;

添加两个API用于登陆和登出

        //登陆
public IActionResult MakeLogin()
{
var claims=new List<Claim>(){
new Claim(ClaimTypes.Name,"wangyuting"),
new Claim(ClaimTypes.Role,"admin") };
//必须要加CookieAuthenticationDefaults.AuthenticationScheme,不然无法解析
var claimsIdentity=new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme); HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(claimsIdentity));
return Ok();
} //登出
public IActionResult Logout()
{
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Ok();
}

访问http://localhost:5000/admin会跳转到http://localhost:5000/Account/MyLogin?ReturnUrl=%2Fadmin页面

然后我们访问http://localhost:5000/Account/MakeLogin模拟登陆,然后再访问http://localhost:5000/admin

最后访问http://localhost:5000/Account/logout登出,然后再访问http://localhost:5000/admin发现又跳转到我们自定义的登陆页面。

【ASP.NET Core快速入门】(十)Cookie-based认证实现的更多相关文章

  1. ASP.NET Core快速入门--学习笔记系列文章索引目录

    课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 抓住国庆假期的尾巴完成了此系列课程的学习笔记输出! ASP.NET Core快 ...

  2. 【笔记目录2】【jessetalk 】ASP.NET Core快速入门_学习笔记汇总

    当前标签: ASP.NET Core快速入门 共2页: 上一页 1 2  任务27:Middleware管道介绍 GASA 2019-02-12 20:07 阅读:15 评论:0 任务26:dotne ...

  3. 【笔记目录1】【jessetalk 】ASP.NET Core快速入门_学习笔记汇总

    当前标签: ASP.NET Core快速入门 共2页: 1 2 下一页  任务50:Identity MVC:DbContextSeed初始化 GASA 2019-03-02 14:09 阅读:16 ...

  4. ASP.NET Core 快速入门(Razor Pages + Entity Framework Core)

    引子 自从 2009 年开始在博客园写文章,这是目前我写的最长的一篇文章了. 前前后后,我总共花了 5 天的时间,每天超过 3 小时不间断写作和代码调试.总共有 8 篇文章,每篇 5~6 个小结,总截 ...

  5. ASP.NET Core 快速入门(环境篇)

    [申明]:本人.NET Core小白.Linux小白.MySql小白.nginx小白.而今天要说是让你精通Linux ... 的开机与关机.nginx安装与部署.Core的Hello World .. ...

  6. 【转】ASP.NET Core 快速入门(环境篇)

    原文链接:http://www.cnblogs.com/zhaopei/p/netcore.html [申明]:本人.NET Core小白.Linux小白.MySql小白.nginx小白.而今天要说是 ...

  7. ASP.NET Core 快速入门【第二弹-实战篇】

    上篇讲了asp.net core在linux上的环境部署.今天我们将做几个小玩意实战一下.用到的技术和工具有mysql.websocket.AngleSharp(爬虫html解析).nginx多站点部 ...

  8. ASP.NET Core 快速入门(实战篇)

    上篇讲了<asp.net core在linux上的环境部署>.今天我们将做几个小玩意实战一下.用到的技术和工具有mysql.websocket.AngleSharp(爬虫html解析).n ...

  9. ASP.NET Core快速入门学习笔记(第3章:依赖注入)

    课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 任务16:介绍 1.依赖注入概念详解 从UML和软件建模来理解 从单元测试来理 ...

随机推荐

  1. BZOJ.4842.[NEERC2016]Delight for a Cat(费用流)

    BZOJ 参考这儿. 首先如果一个活动的时间满足条件,那么另一个活动也一定满足.还有就是这题就是费用流没有为什么.不妨假设最初所有时间都用来睡觉,那么我们要对每个\(k\)大小区间选出\([t2,k- ...

  2. 树莓派虚拟环境手动安装HA

    树莓派手动安装 https://www.home-assistant.io/docs/installation/raspberry-pi/ sudo apt-get update sudo apt-g ...

  3. ZOJ4043 : Virtual Singers

    将所有$A$和$B$混在一起排序,那么每个$B$要匹配一个$A$,从左往右依次考虑每个数: 如果是一个$B$: 如果左边没有多余的$A$,那么将其放入堆$q_C$中,表示这个$B$还未匹配. 否则选择 ...

  4. php json_encode与json_decode详解及实例

    通常情况下,json_decode()总是返回一个PHP对象,而不是数组.如果返回数组,需要添加true参数 如:json_decode($res,true) 一.json_encode() 该函数主 ...

  5. mybatis 之数据库 include refid ="base_column_list"

    mybatis 之数据库 include refid ="base_column_list" 对于刚学习使用SSM框架的新手来说,mybatis中的数据库语句有点不一样,下面便是对 ...

  6. sketch2code 有的叫screenshot to code什么的

    先mark一下项目,回头再深究 https://github.com/mzbac/sketch2code https://www.floydhub.com/emilwallner/datasets/h ...

  7. mysql node

    mysql8.0版本 报错:Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol req ...

  8. Paper Reading——LEMNA:Explaining Deep Learning based Security Applications

    Motivation: The lack of transparency of the deep  learning models creates key barriers to establishi ...

  9. 256.Spring Boot+Spring Security: MD5是加密算法吗?

    说明 (1)JDK版本:1.8 (2)Spring Boot 2.0.6 (3)Spring Security 5.0.9 (4)Spring Data JPA 2.0.11.RELEASE (5)h ...

  10. [Swift]LeetCode37. 解数独 | Sudoku Solver

    Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy  ...