在实际使用中,可能会遇到,aspi接口验证和view页面的登录验证情况。asp.core 同样支持两种兼容。

首先在startup.cs 启用身份验证。

 var secrityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]));
services.AddSingleton(secrityKey);
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(option => //cookies 方式
{
option.LoginPath = "/Login";
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => //jwt 方式
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = true,//是否验证失效时间
ClockSkew = TimeSpan.FromSeconds(30),
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidAudience = Configuration["JWTDomain"],//Audience
ValidIssuer = Configuration["JWTDomain"],//Issuer
IssuerSigningKey = secrityKey//拿到SecurityKey
};
});

Configure 方法中须加入

  app.UseAuthentication(); //授权
app.UseAuthorization(); //认证 认证方式有用户名密码认证 app.MapWhen(context =>
{
var excludeUrl = new string[] { "/api/login/getinfo", "/api/login/login", "/api/login/modifypwd" }; //注意小写
return context.Request.Path.HasValue
&& context.Request.Path.Value.Contains("Login")
&& context.Request.Headers.ContainsKey("Authorization")
&& !(excludeUrl.Contains(context.Request.Path.Value.ToLower()));
}, _app =>
{
_app.Use(async (context, next) =>
{
context.Response.StatusCode = 401;
});
});

在login页面,后台代码

            var uid = Request.Form["code"] + "";
var pwd = Request.Form["pwd"] + ""; var info = _mysql.users.Where(m => m.user_code == uid&&m.delflag==0).FirstOrDefault();
if (info == null)
{
return new JsonResult(new
{
success = false,
msg = "用户不存在"
});
}
if (info.pwd != pwd)
{
return new JsonResult(new
{
success = false,
msg = "用户密码不正确"
});
} //创建一个身份认证
var claims = new List<Claim>() {
new Claim(ClaimTypes.Sid,info.id), //用户ID
new Claim(ClaimTypes.Name,info.user_code) //用户名称
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
//var identity = new ClaimsIdentity(claims, "Login");
//var userPrincipal = new ClaimsPrincipal(identity);
//HttpContext.SignInAsync("MyCookieAuthenticationScheme", userPrincipal, new AuthenticationProperties
//{
// ExpiresUtc = DateTime.UtcNow.AddMinutes(30),
// IsPersistent = true
//}).Wait(); var authProperties = new AuthenticationProperties
{
//AllowRefresh = <bool>,
// Refreshing the authentication session should be allowed.
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60),
// The time at which the authentication ticket expires. A
// value set here overrides the ExpireTimeSpan option of
// CookieAuthenticationOptions set with AddCookie.
IsPersistent = true,
// Whether the authentication session is persisted across
// multiple requests. When used with cookies, controls
// whether the cookie's lifetime is absolute (matching the
// lifetime of the authentication ticket) or session-based. //IssuedUtc = <DateTimeOffset>,
// The time at which the authentication ticket was issued. //RedirectUri = <string>
// The full path or absolute URI to be used as an http
// redirect response value.
}; await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);

 Controler控制器部分,登录代码:

[HttpPost("Login")]
public async Task<JsonResult> Login(getdata _getdata)
{
var userName = _getdata.username;
var passWord = _getdata.password;
var info = _mysql.users.Where(m => m.user_code == userName && m.delflag == 0).FirstOrDefault();
if (info == null)
{
return new JsonResult(new
{
state = false,
code = -1,
data = "",
msg = "用户名不存在!"
});
}
if (CommonOp.MD5Hash(info.pwd).ToLower() != passWord)
{
return new JsonResult(new
{
state = false,
code = -2,
data = "",
msg = "用户密码不正确!"
});
} #region 身份认证处理
var secrityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["SecurityKey"]));
List<Claim> claims = new List<Claim>();
claims.Add(new Claim("user_code", info.user_code));
claims.Add(new Claim("id", info.id)); var creds = new SigningCredentials(secrityKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _config["JWTDomain"],
audience: _config["JWTDomain"],
claims: claims,
expires: DateTime.Now.AddMinutes(120),
signingCredentials: creds); return new JsonResult(new
{
state = true,
code = 0,
data = new JwtSecurityTokenHandler().WriteToken(token),
msg = "获取token成功" });
#endregion
}

注意, 受身份验证的控制器部分,要加入如下属性头,才可以生效。

    [Authorize(AuthenticationSchemes = "Bearer,Cookies")]
public class ControllerCommonBase : ControllerBase
{ }

 

这样一个Controler 控制器,能够兼容两种模式啦。

asp.core 同时兼容JWT身份验证和Cookies 身份验证两种模式的更多相关文章

  1. 第三节:Windows平台部署Asp.Net Core应用(基于IIS和Windows服务两种模式)

    一. 简介 二. 文件系统发布至IIS 三. Web部署发布至IIS 四. FTP发布至IIS 五. Windows服务的形式发布 ! 作       者 : Yaopengfei(姚鹏飞) 博客地址 ...

  2. asp.net中TextBox只能输入数字的最简洁的两种方法

    如下TextBox <asp:textboxonkeypress="isnum()"id="TextBox1"runat="server&quo ...

  3. 验证整数 Double 转 int 两种写法

    Double  转int 1)之前一直是使用强转 Double num = Double.parseDouble(object.toString());   int n = (int)num;   i ...

  4. ASP.NET Core 6框架揭秘实例演示[05]:依赖注入基本编程模式

    毫不夸张地说,整个ASP.NET Core就是建立在依赖注入框架之上的.ASP.NET Core应用在启动时构建管道所需的服务,以及管道处理请求使用到的服务,均来源于依赖注入容器.依赖注入容器不仅为A ...

  5. ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统

    为什么使用 Jwt 最近,移动开发的劲头越来越足,学校搞的各种比赛都需要用手机 APP 来撑场面,所以,作为写后端的,很有必要改进一下以往的基于 Session 的身份认证方式了,理由如下: 移动端经 ...

  6. ASP.NET Core系列:JWT身份认证

    1. JWT概述 JSON Web Token(JWT)是目前流行的跨域身份验证解决方案. JWT的官网地址:https://jwt.io JWT的实现方式是将用户信息存储在客户端,服务端不进行保存. ...

  7. ASP.NET Core WebApi基于JWT实现接口授权验证

    一.ASP.Net Core WebApi JWT课程前言 我们知道,http协议本身是一种无状态的协议,而这就意味着如果用户向我们的应用提供了用户名和密码来进行用户认证,那么下一次请求时,用户还要再 ...

  8. ASP.NET Core 2.1 JWT token (一) - 简书

    原文:ASP.NET Core 2.1 JWT token (一) - 简书 JwtBearer认证是一种标准的,通用的,无状态的,与语言无关的认证方式.Bearer验证属于HTTP协议标准验证. 如 ...

  9. 如何简单的在 ASP.NET Core 中集成 JWT 认证?

    前情提要:ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统 文章超长预警(1万字以上),不想看全部实现过程的同学可以直接跳转到末尾查看成果或者一键安装相关的 nuget 包 自上一 ...

随机推荐

  1. HDU ACM 8.13 T2 的 O(m)做法

    前言 由于本人比较拉所以看起来很啰嗦,将就看就好. 题目大意 \(n\)种包,每个包里面有一大一小两个球,选小球的代价是\(1\),大球的代价是\(2\),可以都不选,若一次性买两个包,则可以优惠\( ...

  2. html基础 表单相关属性综合实战案例 附有注释

    html结构代码: <form > <!-- form 为了让重置按钮生效--> <h1>青春不常在,抓紧谈恋爱</h1> <hr> 昵称: ...

  3. 分别使用time 和 datetime模块记录当前时间

    工作中经常混淆这两种方法 现记录一下 加深印象 代码如下: >>> import time>>> import datetime>>> ct1 = ...

  4. unittest_认识unittest(1)

    unittest是python内置的单元测试框架,具备编写用例.组织用例.执行用例.输出报告等自动化框架的条件. 使用unittest前需要了解该框架的五个概念: 即test case,test su ...

  5. 编写java程序压缩Linux本地目录

    注:图片如果损坏,点击文章链接:https://www.toutiao.com/i6809285459722633736/ 创建工程 使用maven工程 勾选,然后下一步 填写基本信息 注意改一下编码 ...

  6. SYCOJ223图书管理员

    题目-图书管理员 (shiyancang.cn) 图书馆中每本书都有一个图书编码,可以用于快速检索图书,这个图书编码是一个正整数. 每位借书的读者手中有一个需求码,这个需求码也是一个正整数. 如果一本 ...

  7. day 12 default后面是否还可以跟case

    (1).有以下程序: #include<stdio.h> void main(){ int case,float printF; printf("输入2个数\n"): ...

  8. RHCSA 第八天

    1.查询ip的几种方式: ip, ifconfig, nmcli,nmtui 2.nmcli命令使用: a.在ens160网卡上新建连接static_con,并配置静态ip b.在ens160网卡上新 ...

  9. 复盘报告:心跳数据丢失,从发现到解决历经一年多的bug

    时间线 大约在2020年10月,内网测试服服务端更新,发现进程A重启后,与其他进程之间的心跳协议不通,不能正常的提供服务.重启后,就正常了. 这个情况持续了很长时间.只在重启时才会出现,且发生概率很低 ...

  10. 微服务架构 | 3.4 HashiCorp Consul 注册中心

    目录 前言 1. Consul 基础知识 1.1 Consul 是什么 1.2 Consul 的特点 2. 安装并运行 Consul 服务器 2.1 下载 Consul 2.2 运行 Consul 服 ...