原文: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. How To Find Out Attachments By File Type In Outlook?

    ext: (extension extension) Take the attachments of zip files and of txt files for example, just ente ...

  2. pass value from shell to sql

    echo 'please enter new userid need create' read new_usr echo 'please enter userid to model' read mod ...

  3. 简单说下cookie,LocalStorage与SessionStorage.md

    最近在网上看到有人讨论这三个的一些概念与区别,发现自己也一直没有较好的总结,所以查阅了一些资料来阐述一下. 基本概念 cookie cookie英文意思是小甜饼,是原来的网景公司创造,目前是在客户端存 ...

  4. 警惕黑客利用新方法绕过Office安全链接

    东方联盟黑客安全研究人员透露,一些黑客已经发现绕过MicrosoftOffice365的安全功能,该功能最初旨在保护用户免受恶意软件和网络钓鱼攻击. 被称为安全链接的功能已被包含在Office365软 ...

  5. 插入排序->希尔排序

    /** * 插入排序 */ public class InsertSort { public static void main(String[] args){ int[] arr = {5,5,2,6 ...

  6. PowerDesigner 小技巧

    PowerDesigner 重现快捷工具栏 palette :Tools -->customsize toolbars-->palette(调色板)勾选 如何在PDM中列表显示TABLE的 ...

  7. IDEA使用中的快捷键

    项目与项目之间的跳转: Ctrl+Alt+]             下一个窗口. Ctrl+Alt+[             跳转回上一个窗口. 文件之间的跳转: Ctrl+E.          ...

  8. SCJP读书之知识点:

    1:实例变量和局部变量 实例变量:是在类中进行声明的,可以有public,private等修饰符进行修饰. 局部变量:在方法中进行声明,生命周期就是方法开始,到方法结束.但是可以进行对象的引用来调用. ...

  9. php pi()函数 语法

    php pi()函数 语法 pi()函数是什么意思? php pi()函数用于获取圆周率值,语法是pi(),这个函数只是单纯的用来获取圆周率值深圳大理石平台 作用:获取圆周率值 语法:pi() 参数: ...

  10. 使用kindeditor直接粘贴本地图片或者是qq截图

    我司需要做一个需求,就是使用富文本编辑器时,不要以上传附件的形式上传图片,而是以复制粘贴的形式上传图片. 在网上找了一下,有一个插件支持这个功能. WordPaster 安装方式如下: 直接使用Wor ...