一、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. laravel 发送html邮件是a标签中的url不显示问题

  2. orcal 中的orcal用法

    ROWID是数据的详细地址,通过rowid,Oracle可以快速的定位某行具体的数据的位置. ROWID可以分为物理rowid和逻辑rowid两种.普通的堆表中的rowid是物理rowid,索引组织表 ...

  3. 对《疯狂Spring Cloud微服务架构实战》作者的疑问

    Cloud的程序都是用的内部Tomcat,即使把一个大App分成独立小块,能应付得了你们当年人力运维的大量请求涌入吗? 真不知道淘宝怎么做到的双11一直不垮?真实互联网生产环境是充斥图书市场中的所谓S ...

  4. 解决 Ubuntu 18.10 使用较新的独立显卡输出无法初始化图形界面并配置深度学习开发环境

    原文地址:解决 Ubuntu 18.10 使用较新的独立显卡输出无法初始化图形界面并配置深度学习开发环境 0x00 配置 硬件 OS: Ubuntu 18.10 Base Board: ASUS WS ...

  5. Redis 配置 CONFIG 命令

    redis.conf 文件在 安装目录下 CONFIG 命令查看或设置配置项 先登陆 src/redis-cli -a -a 后面是密码,默认为空,没有密码直接登陆 src/redis-cli 1.查 ...

  6. django路由的二级分发

    基于二级分发设计url路由 path('index/', views.index), path('index/', ([ path('test01/', test01), path('test02/' ...

  7. C# 给某个方法设定执行超时时间-2

    var response = RunTaskWithTimeout<ReturnType>( (Func<ReturnType>)); /// <summary> ...

  8. java:多线程(代理模式,Thread中的方法,Timer,生产者和消费者)

    *进程:一个正在运行的程序,进程是操作系统分配资源的基本单位,每个进行有独立的内存空间,进程之间切换开销较大. *线程:一个轻量级的进程,线程是任务调度的基本单位,一个进程可以有多个线程, * 系统没 ...

  9. JS中document对象 && window对象

    所有的全局函数和对象都属于Window对象的属性和方法. 区别: 1.window 指窗体.Window 对象表示浏览器中打开的窗口. document指页面.document是window的一个子对 ...

  10. jmeter业务建模中遇到的问题

    1.jmeter函数助手中的jexl3函数,不支持${__jexl3(15<${__Random(1,100,)}<36,)}这种写法,须这样写${__jexl3(15<${__Ra ...