ASP.NET Core 2.1 JWT token (一) - 简书
原文: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 :
使用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";
}
}
}
- get请求 : api/test 发生错误,无法通过验证
- post 请求 : api/test/1 返回 " value "
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 (一) - 简书的更多相关文章
- ASP.NET Core 2.1 JWT Token 使用 (二) - 简书
原文:ASP.NET Core 2.1 JWT Token 使用 (二) - 简书 接上文,https://www.jianshu.com/p/c5f9ea3b4b65 ASP.NET Core 2. ...
- asp.net core使用identity+jwt保护你的webapi(三)——refresh token
前言 上一篇已经介绍了identity的注册,登录,获取jwt token,本篇来完成refresh token. 开始 开始之前先说明一下为什么需要refresh token. 虽然jwt toke ...
- 在ASP.NET Core中实现一个Token base的身份认证
注:本文提到的代码示例下载地址> How to achieve a bearer token authentication and authorization in ASP.NET Core 在 ...
- 如何简单的在 ASP.NET Core 中集成 JWT 认证?
前情提要:ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统 文章超长预警(1万字以上),不想看全部实现过程的同学可以直接跳转到末尾查看成果或者一键安装相关的 nuget 包 自上一 ...
- ASP.NET Core系列:JWT身份认证
1. JWT概述 JSON Web Token(JWT)是目前流行的跨域身份验证解决方案. JWT的官网地址:https://jwt.io JWT的实现方式是将用户信息存储在客户端,服务端不进行保存. ...
- ASP.NET Core WebApi基于JWT实现接口授权验证
一.ASP.Net Core WebApi JWT课程前言 我们知道,http协议本身是一种无状态的协议,而这就意味着如果用户向我们的应用提供了用户名和密码来进行用户认证,那么下一次请求时,用户还要再 ...
- asp.net core使用identity+jwt保护你的webapi(二)——获取jwt token
前言 上一篇已经介绍了identity在web api中的基本配置,本篇来完成用户的注册,登录,获取jwt token. 开始 开始之前先配置一下jwt相关服务. 配置JWT 首先NuGet安装包: ...
- asp.net core使用identity+jwt保护你的webapi(一)——identity基础配置
前言 用户模块几乎是每个系统必备的基础功能,如果每次开发一个新项目时都要做个用户模块,确实非常无聊.好在asp.net core给我们提供了Identity,使用起来也是比较方便,如果对用户这块需求不 ...
- ASP.NET Core 2.2 : 二十六. 应用JWT进行用户认证及Token的刷新
来源:https://www.cnblogs.com/FlyLolo/p/ASPNETCore2_26.html 本文将通过实际的例子来演示如何在ASP.NET Core中应用JWT进行用户认证以及T ...
随机推荐
- Web前端基础学习-1
HTML5/CSS简介 首先来说一说什么是HTML5,HTML5可以认为是字面上的意义,也就是HTML的第五代产品,当然从另一个角度来说它是一种新的富客户端解决方案. HTML5 将成为 HTML.X ...
- iOS crash log 解析
iOS开发中,经常遇到App在开发及测试时不会有问题,但是装在别人的设备中会出现各种不定时的莫名的 crash,因为iOS设备会保存应用的大部分的 crash Log,所以可以通过 crash Log ...
- Python中集合类型的使用
集合类型 多个不重复元素的无序组合 集合类型的表示 建立非空集合的方式可以用{}来表示 采用set()来表示 集合类型的操作符 S|T 返回一个新集合,这个集合包含S与T中的所有元素. S-T 返回一 ...
- jenkins部署的零碎知识
环境要求 1)版本控制子系统(SVN):SVN服务器.项目对应版本库.版本库中钩子程序(提交代码后,触发Jenkins自动打包并部署到应用服务器)(2)持续集成子系统(存在Jenkins的服务器):J ...
- go语言从例子开始之Example34.速率限制
速率限制(英) 是一个重要的控制服务资源利用和质量的途径.Go 通过 Go 协程.通道和打点器优美的支持了速率限制. Example: package main import "fmt&qu ...
- ubuntu14.0 服务器webmin安装
添加相关的源“: sudo vim /et/apt/source.list 在文件后添加: deb http://download.webmin.com/download/repository sar ...
- token理解
什么是JWT Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点 ...
- springBoot+mysql+mybatis demo [基本配置] [遇到的问题]
springBoot+mysql+mybatis的基本配置: 多环境 application.properties spring.profiles.active=dev spring.applicat ...
- 接口上传base64编码图片
package com.*.util; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io. ...
- leetcode-167周赛-1291-顺次数
题目描述: 自己的提交: class Solution: def sequentialDigits(self, low: int, high: int) -> List[int]: l,h = ...