一、Startup类配置

ConfigureServices中

            //添加jwt验证:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = true,//是否验证失效时间
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidIssuer = Configuration["Jwt:Issuer"],//appsettings.json文件中定义的Issuer
ValidAudience = Configuration["Jwt:Issuer"],//appsettings.json文件中定义的Audience
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};//appsettings.json文件中定义的JWT Key
});

Configure 启用中间件

            app.UseAuthentication(); // 注意添加这一句,启用jwt验证

整体代码:

    public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//添加jwt验证:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,//validate the server
ValidateAudience = true,//ensure that the recipient of the token is authorized to receive it
ValidateLifetime = true,//check that the token is not expired and that the signing key of the issuer is valid
ValidateIssuerSigningKey = true,//verify that the key used to sign the incoming token is part of a list of trusted keys
ValidIssuer = Configuration["Jwt:Issuer"],//appsettings.json文件中定义的Issuer
ValidAudience = Configuration["Jwt:Issuer"],//appsettings.json文件中定义的Audience
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};//appsettings.json文件中定义的JWT Key
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//跨域
app.UseCors(builder =>
{
builder.SetIsOriginAllowed(origin => true)
.AllowAnyHeader()
.WithMethods("GET", "POST")
.AllowCredentials();
});
app.UseAuthentication(); // 注意添加这一句,启用jwt验证 app.UseMvc();
}
}

二、appsetting.json中配置

  "Jwt": {
"Key": "veryVerySecretKey",
"Issuer": "http://localhost:53111"
}

整体代码:

{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"Jwt": {
"Key": "veryVerySecretKey",
"Issuer": "http://localhost:53111"
},
"AllowedHosts": "*"
}

如图:

三、Api控制器中  根据登录信息生成token令牌

整体代码:

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens; namespace Temp.Controllers
{
[Route("api/[controller]/[action]")] //Api控制器
[ApiController]
public class OAuthController : ControllerBase
{
private readonly IConfiguration _config; public OAuthController(IConfiguration configuration)
{
_config = configuration;
}
/// <summary>
/// login
/// </summary>
/// <returns></returns>
[HttpPost]
public string Token(string user, string password)
{
//验证用户名和密码
var claims = new Claim[] { new Claim(ClaimTypes.Name, "John"), new Claim(JwtRegisteredClaimNames.Email, "john.doe@blinkingcaret.com") }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(
//颁发者
issuer: _config["Jwt:Issuer"],
//接收者
audience: _config["Jwt:Issuer"],
//添加claims
claims: claims,
//指定token的生命周期,过期时间
expires: DateTime.Now.AddMinutes(),
//签名证书
signingCredentials: creds);
//一个典型的JWT 字符串由三部分组成: //header: 头部,meta信息和算法说明
//payload: 负荷(Claims), 可在其中放入自定义内容, 比如, 用户身份等
//signature: 签名, 数字签名, 用来保证前两者的有效性 //三者之间由.分隔, 由Base64编码.根据Bearer 认证规则, 添加在每一次http请求头的Authorization字段中, 这也是为什么每次这个字段都必须以Bearer jwy - token这样的格式的原因.
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}

四、对授权的进行验证

效果如下:

获取资源:

注意:这个地方要默认取消

一、Core授权-2 之.net core 基于Jwt实现Token令牌的更多相关文章

  1. .net core 基于Jwt实现Token令牌

    Startup类ConfigureServices中 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJw ...

  2. 基于JWT的Token开发案例

    代码地址如下:http://www.demodashi.com/demo/12531.html 0.准备工作 0-1运行环境 jdk1.8 maven 一个能支持以上两者的代码编辑器,作者使用的是ID ...

  3. ASP.NET Web API 2系列(四):基于JWT的token身份认证方案

    1.引言 通过前边的系列教程,我们可以掌握WebAPI的初步运用,但是此时的API接口任何人都可以访问,这显然不是我们想要的,这时就需要控制对它的访问,也就是WebAPI的权限验证.验证方式非常多,本 ...

  4. ASP.NET WebApi 基于JWT实现Token签名认证

    一.前言 明人不说暗话,跟着阿笨一起玩WebApi!开发提供数据的WebApi服务,最重要的是数据的安全性.那么对于我们来说,如何确保数据的安全将会是需要思考的问题.在ASP.NET WebServi ...

  5. token 与 基于JWT的Token认证

    支持跨域访问,无状态认证 token特点 支持跨域访问: Cookie是不允许垮域访问的,这一点对Token机制是不存在的,前提是传输的用户认证信息通过HTTP头传输 无状态(也称:服务端可扩展行): ...

  6. 基于JWT的Token认证机制及安全问题

    [干货分享]基于JWT的Token认证机制及安全问题 https://bbs.huaweicloud.com/blogs/06607ea7b53211e7b8317ca23e93a891

  7. 基于JWT的Token身份验证

    ​ 身份验证,是指通过一定的手段,完成对用户身份的确认.为了及时的识别发送请求的用户身份,我们调研了常见的几种认证方式,cookie.session和token. 1.Cookie ​ cookie是 ...

  8. 基于JWT实现token验证

    JWT的介绍 Json Web Token(JWT)是目前比较流行的跨域认证解决方案,是一种基于JSON的开发标准,由于数据是可以经过签名加密的,比较安全可靠,一般用于前端和服务器之间传递信息,也可以 ...

  9. Asp.Net Core 3.1 学习3、Web Api 中基于JWT的token验证及Swagger使用

    1.初始JWT 1.1.JWT原理 JWT(JSON Web Token)是目前最流行的跨域身份验证解决方案,他的优势就在于服务器不用存token便于分布式开发,给APP提供数据用于前后端分离的项目. ...

随机推荐

  1. 在RHEL6_Oracle_Linux_6上生成正确的udev_rule_规则文件

    1. #首先确认是 Linux 6.0以上版本 [root@vrh6 dev]# cat /etc/issue          Oracle Linux Server release 6.2Kern ...

  2. SQLServer备份计划制定

    SQLServer备份计划制定 一.备份计划制定 管理-->维护计划-->维护计划向导: 可选择全库备份.差异备份.事务日志备份 为保障数据的完整性:可采用备份策略1.数据量小的场景,数据 ...

  3. P1070道路游戏题解

    日常吐槽 作为hin久hin久以前考试考到过的一道题窝一直咕咕咕到现在才想起来去做因为讲解都忘干净了然后自己重新考虑发现被卡了3天 题面 看到题目发现这题的dp状态似乎有点不是很明确? 我们来理一理题 ...

  4. Vs2019+openjdk12 本地Debug环境搭建过程

    1. VS2019下载和安装 这个就不写了 2. cygwin安装: https://jingyan.baidu.com/article/455a99507c0b78a166277809.html 需 ...

  5. [flask]jinjia2-模板 url_for的使用

    url_for是什么? url_for()用于生成URL的函数,是Flask内置模板的1个全局函数 url_for()用来获取URL,用法和在Python脚本中相同.url_for的参数是视图的端点( ...

  6. idea 编译 netty 源码

    git clone netty 源码,运行 example 报错 全量 mvn compile -DskipTests=true 后,依然报错 手动在 netty-buffer 模块中添加对应的依赖 ...

  7. Java学习之==>注释、数据类型、变量、运算符

    一.注释 在Java中有3种标记注释的方式,最常用的方式是 // ,其注释的内容从 // 开始,到本行结束.但需要注意的是,我们不建议把注释写在代码的尾部(即尾注释),我们建议把注释写在代码的上一行, ...

  8. Word2007—如何快速取消自动编号

    有时候自动编号很麻烦,有没有好的办法可以快速取消呢. 1.禁止自动编号.在Word为其自动加上编号时,只要按下Ctrl+Z键撤销操作,此时自动编号会消失,而且每次键入数字时,该功能就会被禁止了. 2. ...

  9. Java SE 8 docs——Static Methods、Instance Methods、Abstract Methods、Concrete Methods和field

    一.Static Methods.Instance Methods.Abstract Methods.Concrete Methods ——Static Methods:静态方法 ——Instance ...

  10. Cocos2d-X多线程(3) cocos2dx中的线程安全

    在使用多线程时,总会遇到线程安全的问题.cocos2dx 3.0系列中新加入了一个专门处理线程安全的函数performFunctionInCocosThread(),他是Scheduler类的一个成员 ...