using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks; namespace Fiver.Security.Authentication
{
public class Startup
{
public void ConfigureServices(
IServiceCollection services)
{
services.AddAuthentication("FiverSecurityScheme")
.AddCookie("FiverSecurityScheme", options =>
{
options.AccessDeniedPath = new PathString("/Security/Access");
options.Cookie = new CookieBuilder
{
//Domain = "",
HttpOnly = true,
Name = ".Fiver.Security.Cookie",
Path = "/",
SameSite = SameSiteMode.Lax,
SecurePolicy = CookieSecurePolicy.SameAsRequest
};
options.Events = new CookieAuthenticationEvents
{
OnSignedIn = context =>
{
Console.WriteLine("{0} - {1}: {2}", DateTime.Now,
"OnSignedIn", context.Principal.Identity.Name);
return Task.CompletedTask;
},
OnSigningOut = context =>
{
Console.WriteLine("{0} - {1}: {2}", DateTime.Now,
"OnSigningOut", context.HttpContext.User.Identity.Name);
return Task.CompletedTask;
},
OnValidatePrincipal = context =>
{
Console.WriteLine("{0} - {1}: {2}", DateTime.Now,
"OnValidatePrincipal", context.Principal.Identity.Name);
return Task.CompletedTask;
}
};
//options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
options.LoginPath = new PathString("/Security/Login");
options.ReturnUrlParameter = "RequestPath";
options.SlidingExpiration = true;
}); services.AddMvc();
} //public void ConfigureServices(
// IServiceCollection services)
//{
// services.AddAuthentication("FiverSecurityScheme")
// .AddCookie("FiverSecurityScheme", options =>
// {
// options.AccessDeniedPath = new PathString("/Security/Access");
// options.LoginPath = new PathString("/Security/Login");
// }); // services.AddMvc();
//} public void Configure(
IApplicationBuilder app,
IHostingEnvironment env)
{
app.UseDeveloperExceptionPage(); app.UseAuthentication(); app.UseMvcWithDefaultRoute();
}
}
}
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Fiver.Security.Authentication.Models.Security;
using System.Security.Claims;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authentication;
using System; namespace Fiver.Security.Authentication.Controllers
{
public class SecurityController : Controller
{
public IActionResult Login(string requestPath)
{
ViewBag.RequestPath = requestPath ?? "/";
return View();
} [HttpPost]
public async Task<IActionResult> Login(LoginInputModel inputModel)
{
if (!IsAuthentic(inputModel.Username, inputModel.Password))
return View(); // create claims
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "Sean Connery"),
new Claim(ClaimTypes.Email, inputModel.Username)
}; // create identity
ClaimsIdentity identity = new ClaimsIdentity(claims, "cookie"); // create principal
ClaimsPrincipal principal = new ClaimsPrincipal(identity); // sign-in
await HttpContext.SignInAsync(
scheme: "FiverSecurityScheme",
principal: principal,
properties: new AuthenticationProperties
{
//IsPersistent = true, // for 'remember me' feature
//ExpiresUtc = DateTime.UtcNow.AddMinutes(1)
}); return Redirect(inputModel.RequestPath ?? "/");
//return RedirectToAction("Index", "Home");
} public async Task<IActionResult> Logout(string requestPath)
{
await HttpContext.SignOutAsync(
scheme: "FiverSecurityScheme"); return RedirectToAction("Login");
} public IActionResult Access()
{
return View();
} #region " Private " private bool IsAuthentic(string username, string password)
{
return (username == "james" && password == "bond");
} #endregion
}
}

ASP.NET Core 2.0 Cookie Authentication的更多相关文章

  1. asp.net core 2.0 cookie的使用

    本文假设读者已经了解cookie的概念和作用,并且在传统的.net framework平台上使用过. cookie的使用方法和之前的相比也有所变化.之前是通过cookie的add.set.clear. ...

  2. net core体系-web应用程序-4net core2.0大白话带你入门-11asp.net core 2.0 cookie的使用

    asp.net core 2.0 cookie的使用   本文假设读者已经了解cookie的概念和作用,并且在传统的.net framework平台上使用过. cookie的使用方法和之前的相比也有所 ...

  3. Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员、后台管理员同时登录

    1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...

  4. ASP.NET Core 2.0 多应用实现Cookie共享

    前言 .NET Core 2.0 发布之后,在Authentication中间件部分,相关API有不少改动(官方文档),本文主要讲的就是实现应用Cookie共享,对Cookie中间件使用不了解的可以去 ...

  5. ASP.NET Core 1.0 静态文件、路由、自定义中间件、身份验证简介

    概述 ASP.NET Core 1.0是ASP.NET的一个重要的重新设计. 例如,在ASP.NET Core中,使用Middleware编写请求管道. ASP.NET Core中间件对HttpCon ...

  6. 在ASP.NET Core 2.0中使用CookieAuthentication

    在ASP.NET Core中关于Security有两个容易混淆的概念一个是Authentication(认证),一个是Authorization(授权).而前者是确定用户是谁的过程,后者是围绕着他们允 ...

  7. ASP.NET CORE中使用Cookie身份认证

    大家在使用ASP.NET的时候一定都用过FormsAuthentication做登录用户的身份认证,FormsAuthentication的核心就是Cookie,ASP.NET会将用户名存储在Cook ...

  8. Asp.net core 2.0.1 Razor 的使用学习笔记(三)

    ASP.net core 2.0.0 中 asp.net identity 2.0.0 的基本使用(二)—用户账户及cookie配置 修改用户账户及cookie配置 一.修改密码强度和用户邮箱验证规则 ...

  9. Asp.Net Core 2.0 项目实战(2)NCMVC一个基于Net Core2.0搭建的角色权限管理开发框架

    Asp.Net Core 2.0 项目实战(1) NCMVC开源下载了 Asp.Net Core 2.0 项目实战(2)NCMVC一个基于Net Core2.0搭建的角色权限管理开发框架 Asp.Ne ...

随机推荐

  1. <网络编程>IO复用

    IO复用是一种机制,一个进程可以监听多个描述符,一旦某个描述符就绪(读就绪和写就绪),能够同志程序进行相应的读写操作. 目前支持I/O复用的系统调用有select,poll,pselect,epoll ...

  2. 本地搭了http服务(localhost),怎么在vue环境下,通过axios获取到接口数据

    1. 找到 vue项目\config\index.js 文件 2. proxyTable: { '/api': { target: 'http://127.0.0.1:9420', changeOri ...

  3. Vue2.x源码学习笔记-Vue构造函数

    我们知道使用vue.js开发应用时,都是new Vue({}/*options*/) 那Vue构造函数上有哪些静态属性和方法呢?其原型上又有哪些方法呢? 一般我都会在浏览器中输入Vue来look se ...

  4. Jmeter自定义Java请求,继承AbstractJavaSamplerClient

    首先,使用Eclipse新建一个项目,然后从Jmeter的lib/ext目录下中拷贝ApacheJMeter_java.jar和ApacheJMeter_core.jar两个文件,然后引入这两个JAR ...

  5. echarts 图例显示到右边

    原: legend: { data:['同龄普通孩子','已具备技能','已泛化技能','已掌握技能','学习中'] }, 改: legend: { data:['同龄普通孩子','已具备技能','已 ...

  6. .NetCore实践爬虫系统(一)解析网页内容

    爬虫系统的意义 爬虫的意义在于采集大批量数据,然后基于此进行加工/分析,做更有意义的事情.谷歌,百度,今日头条,天眼查都离不开爬虫. 今日目标 今天我们来实践一个最简单的爬虫系统.根据Url来识别网页 ...

  7. H5 36-背景定位属性

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. UnderWater+SDN论文之六

    Protocol Emulation Platform Based on Microservice Architecture for Underwater Acoustic Networks Sour ...

  9. myeclipse使用hibernate5框架load延迟装载对象报错_$$_javassist_0 cannot be cast to javassist.util.proxy.Proxy

    jar包问题,将hibernate-core-5.0.12.Final.jar删除,换为hibernate-core-4.2.3.final.jar搞定.注意项目运行过后可能删不掉jar包,只需关闭m ...

  10. Codeforces Round #534 (Div. 2)D. Game with modulo-1104-D(交互+二分+构造)

    D. Game with modulo time limit per test 1 second memory limit per test 256 megabytes input standard ...