原文:ASP.NET Core 2.1 JWT token (一) - 简书

JwtBearer认证是一种标准的,通用的,无状态的,与语言无关的认证方式。Bearer验证属于HTTP协议标准验证。

如果不希望api被所有人调用,就要 控制 api 的访问权限,只有通过认证的用户,才允许调用api。

Bearer Token(Token 令牌)

为了验证使用者的身份,需要客户端向服务器端提供一个可靠的验证信息,称为Token,这个token通常由Json数据格式组成,通过hash散列算法生成一个字符串,所以称为Json Web Token(Json表示令牌的原始值是一个Json格式的数据,web表示是在互联网传播的,token表示令牌,简称JWT)。

JWT

一个JWT:

{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiQW5nZWxhRGFkZHkiLCJleHAiOjE1MzMwOTAxMjQsImlzcyI6Imp3dHRlc3QiLCJhdWQiOiJqd3R0ZXN0In0.JAw0Jdg9Z_bFXm8Chsw5ZFfhKDk9lV-g-TkqN7cUcf8"
}

JWT是由 . 分割的三部分组成:

头部(Header)

载荷(Payload) : 这一部分是JWT主要的信息存储部分,其中包含了许多种的声明(claims)。

签名(Signature):使用保存在服务端的秘钥对其签名,用来验证发送者的JWT的同时也能确保在期间不被篡改。

生成jwt token

在一个Controller的方法中生成 jwt token ,一般在用户登陆 验证方法中,如果用户登陆验证成功 , 就 返回一个 token 。

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens; namespace JWTTest.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IConfiguration _configuration; public ValuesController(IConfiguration configuration)
{
_configuration = configuration;
} // GET api/values
[HttpGet]
//[Authorize]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
} // POST api/values
[HttpPost]
public IActionResult Post(string username, string password)
{
if (username == "AngelaDaddy" && password == "123456")
{
// push the user’s name into a claim, so we can identify the user later on.
var claims = new[]
{
new Claim(ClaimTypes.Name, username)
};
//sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit.
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
//.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token.
/**
* Claims (Payload)
Claims 部分包含了一些跟这个 token 有关的重要信息。 JWT 标准规定了一些字段,下面节选一些字段: iss: The issuer of the token,token 是给谁的 发送者
audience: 接收的
sub: The subject of the token,token 主题
exp: Expiration Time。 token 过期时间,Unix 时间戳格式
iat: Issued At。 token 创建时间, Unix 时间戳格式
jti: JWT ID。针对当前 token 的唯一标识
除了规定的字段外,可以包含其他任何 JSON 兼容的字段。
* */
var token = new JwtSecurityToken(
issuer: "jwttest",
audience: "jwttest",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds); return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
} return BadRequest("用户名密码错误");
} }
}

在appsettings.json中:

{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"SecurityKey": "dd%88*377f6d&f£$$£$FdddFF33fssDG^!3"
}

测试生成token :

1.jpg
使用jwt验证

在Startup.cs中配置 服务 ,添加jwt 验证 服务:

using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens; namespace JWTTest
{
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)
{
//添加jwt验证:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = true,//是否验证失效时间
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidAudience = "jwttest",//Audience
ValidIssuer = "jwttest",//Issuer,这两项和前面签发jwt的设置一致
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]))//拿到SecurityKey
};
}); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
} // 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();
}
else
{
app.UseHsts();
} app.UseAuthentication();//启用验证
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
测试

新建一个Conroller , 在需要验证的地方加上 [Authorize] :

using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; namespace JWTTest.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
// GET api/values
[HttpGet]
[Authorize]//添加Authorize标签,可以加在方法上,也可以加在类上
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
}
}
  1. get请求 : api/test 发生错误,无法通过验证
  2. post 请求 : api/test/1 返回 " value "
  3. post请求 : api/values?username=AngelaDaddy&password=123456 返回{

    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiQW5nZWxhRGFkZHkiLCJleHAiOjE1MzMwOTAxMjQsImlzcyI6Imp3dHRlc3QiLCJhdWQiOiJqd3R0ZXN0In0.JAw0Jdg9Z_bFXm8Chsw5ZFfhKDk9lV-g-TkqN7cUcf8"

    }

    4.发送get请求的时候,在header中带上 token ,请求 api/test , 通过验证,请求成功,返回 ["value1","value2"]

    2.jpg

参考 :

https://www.cnblogs.com/RainingNight/p/jwtbearer-authentication-in-asp-net-core.html

https://www.jianshu.com/p/294ea94f0087?utm_source=oschina-app

ASP.NET Core 2.1 JWT token (一) - 简书的更多相关文章

  1. ASP.NET Core 2.1 JWT Token 使用 (二) - 简书

    原文:ASP.NET Core 2.1 JWT Token 使用 (二) - 简书 接上文,https://www.jianshu.com/p/c5f9ea3b4b65 ASP.NET Core 2. ...

  2. asp.net core使用identity+jwt保护你的webapi(三)——refresh token

    前言 上一篇已经介绍了identity的注册,登录,获取jwt token,本篇来完成refresh token. 开始 开始之前先说明一下为什么需要refresh token. 虽然jwt toke ...

  3. 在ASP.NET Core中实现一个Token base的身份认证

    注:本文提到的代码示例下载地址> How to achieve a bearer token authentication and authorization in ASP.NET Core 在 ...

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

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

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

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

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

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

  7. asp.net core使用identity+jwt保护你的webapi(二)——获取jwt token

    前言 上一篇已经介绍了identity在web api中的基本配置,本篇来完成用户的注册,登录,获取jwt token. 开始 开始之前先配置一下jwt相关服务. 配置JWT 首先NuGet安装包: ...

  8. asp.net core使用identity+jwt保护你的webapi(一)——identity基础配置

    前言 用户模块几乎是每个系统必备的基础功能,如果每次开发一个新项目时都要做个用户模块,确实非常无聊.好在asp.net core给我们提供了Identity,使用起来也是比较方便,如果对用户这块需求不 ...

  9. ASP.NET Core 2.2 : 二十六. 应用JWT进行用户认证及Token的刷新

    来源:https://www.cnblogs.com/FlyLolo/p/ASPNETCore2_26.html 本文将通过实际的例子来演示如何在ASP.NET Core中应用JWT进行用户认证以及T ...

随机推荐

  1. CSS3中resize属性

    说明: resize属性是指定一个元素是否可由用户调整大小的. 语法: resize:none | both | horizontal | vertical none:用户不可一调整元素的尺寸(默认值 ...

  2. js操作对象属性用点和用中括号有什么不同

    书读百遍其义自见 学习<JavaScript设计模式>一书时,学习工厂模式这一章节,发现了对象后使用中括号的情况,如下: var Factory=function(type,content ...

  3. bounds与frame的区别及setBounds的使用

    转自http://www.cocoachina.com/ios/20140925/9755.html 在iOS开发中经常遇到两个词Frame和bounds,本文主要阐述Frame和bound的区别,尤 ...

  4. 20180209-os模块

    下面将学习关于os模块的相关操作 项目练习的目录结构如下:所有的操作都是基于os_exercise.py模块 1.获取当前的Python脚本的工作目录路径 os.getcwd() # 1.获取当前目录 ...

  5. shortcut to add throws declaration in Intellij Idea

    When a piece of code needs error handling, IntelliJ underlines it with red. Set your pointer on that ...

  6. 在Linux服务器上运行jar包,并且使jar包一直处于后台执行

    1.我jar包在linux的目录为/a/bbb.jar         正常情况下,使用在/a目录下使用  java -jar bbb.jar 可以直接运行该jar包的项目,运行成功之后使用crtl+ ...

  7. centos 6.5 关闭防火墙

    关闭防火墙分为临时关闭和永久关闭.临时关闭重启系统后恢复正常,永久关闭重启系统后仍然是关闭状态 临时关闭与开启 service iptables stop service iptables start ...

  8. 一文带你领略虚拟化领域顶级技术会议KVM Forum 2018

    KVM Forum是由Linux基金会组织的高端技术论坛会议,主要为社区各个维护者,开发人员,和用户提供一个讨论Linux虚拟化技术发展趋势以及挑战的交流场所.参会人员都集中在KVM虚拟化相关领域,是 ...

  9. C#_winform登陆框验证码的实现

    验证码技术已愈来愈成熟,从最初的数字.字母.字符.汉字已经到目前的语言,其应用也甚广,之前大多数只有在网站上可以看到,现在在一些客户端软件也经常可见(比如证券相关软件).之前做的一个基于 C# 客户端 ...

  10. LOJ 6433 「PKUSC2018」最大前缀和——状压DP

    题目:https://loj.ac/problem/6433 想到一个方案中没有被选的后缀满足 “该后缀的任一前缀和 <=0 ”. 于是令 dp[ S ] 表示选了点集 S ,满足任一前缀和 & ...