一、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. 使用asio进行异步下载http

    下面是官方demo, 给人耳目一新的感觉,以前是总是把c++当成有类功能的C,看完这个感觉不用自己造轮子了,还是要跟上时代的步伐 // // async_client.cpp // ~~~~~~~~~ ...

  2. 编写个shell脚本将/home/test 目录下大于10K的文件转移到/tmp目录下

    #!/bin/sh cd /home/test for i in `ls -l |awk '{if($5>10240) {print $9}}'` do mv $i /tmp done

  3. datagrid数据清空

    方法一: 不管是url方式还是加载本地数据的方式,均可以直接使用loadData方法清空数据,一行代码就可以清空: $('#tt').datagrid('loadData',{total:0,rows ...

  4. linux添加新用户

    使用root用户adduser yj 后面操作有提示 用这种方法新建的用户会在home下生成用户文件夹

  5. VIM速查表-转

    在linux上一直使用vim,慢慢熟悉了它的命令,才终于领悟了什么是编辑器之神. 最近抽空整理了这份速查表,收获颇丰,并分享给大家. 进入vim vim配置 移动光标 屏幕滚动 插入文本类 删除命令 ...

  6. [flask]jinjia2处理表单-实现搜索界面

    思路: 通过flask-wtf创建forms表单类 在app.py中创建search_name()视图函数,实例化form表单类,将通过render_template将form传给html模板 创建h ...

  7. [VBA]利用正则表达式创建函数处理字符串

    1.去除字符串中的数字 Function aa(sr As Range)Set reg = CreateObject("vbscript.regexp")With reg.Glob ...

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

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

  9. Ubuntu 防火墙常用配置操作(ufw)【适用于 Debian 及其衍生版---Linux Mint、Deepin 等】-转

    Ubuntu 防火墙常用配置操作(ufw)[适用于 Debian 及其衍生版---Linux Mint.Deepin 等] 点击访问

  10. squid 3.5.2配置文件

    https://www.cnblogs.com/mchina/p/3812190.html 配置文件就加入下面这几句话: cache_mem 64 MB maximum_object_size 4 M ...