因为害怕token泄露出现问题,所以从未在项目中使用jwt。但这玩意现在真的很火,趁有空还是研究了一下。

在aspnetcore中实现jwt很简单,感觉微软把很多工作都做了,虽然开发效率上去了,但是使得c#的程序员变得很傻,很多事情都是知其然而不知其所以然,只能绑死在微软这条大船上越行越远,唉~~

jwt一般在webapi的项目使用比较多,但我下面的代码都是在MVC环境上测试的,用法上应该没什么区别。

一、添加和配置JWT

1、引入nuget包

VS中点击 工具 > 管理解决方案 NuGet 程序包,搜索 IdentityModel,安装到项目

2、添加JWT配置项

打开  appsettings.json ,添加节点

"Authentication": {
"JwtBearer": {
"IsEnabled": "true",
"SecurityKey": "JWTStudyWebsite_DI20DXU3",
"Issuer": "JWTStudy",
"Audience": "JWTStudyWebsite"
}
}

3、新建  JWTConfiguration.cs 文件,内容如下:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Text; namespace JWTStudent.Website.Extensions
{
public static class JwtConfiguration
{
public static void AddJwtConfiguration(this IServiceCollection services, IConfiguration configuration)
{
if (bool.Parse(configuration["Authentication:JwtBearer:IsEnabled"]))
{
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = "JwtBearer";
options.DefaultChallengeScheme = "JwtBearer";
}).AddJwtBearer("JwtBearer", options =>
{
options.Audience = configuration["Authentication:JwtBearer:Audience"]; options.TokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])), // Validate the JWT Issuer (iss) claim
ValidateIssuer = true,
ValidIssuer = configuration["Authentication:JwtBearer:Issuer"], // Validate the JWT Audience (aud) claim
ValidateAudience = true,
ValidAudience = configuration["Authentication:JwtBearer:Audience"], // Validate the token expiry
ValidateLifetime = true, // If you want to allow a certain amount of clock drift, set that here
ClockSkew = TimeSpan.Zero
};
});
}
}
}
}

4、在StartUp.cs的ConfigurationServices方法内,添加如下代码:

services.AddJwtConfiguration(Configuration);

二、创建AccessTokenController,用于申请和发放JWT

public IActionResult Post([FromBody]LoginModel model)
{
var user = TempData.Users.FirstOrDefault(m => m.Account == model.Account && m.Pw == model.Pw); if (user != null)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, user.Account),
new Claim(ClaimTypes.Role, user.Role)
}; var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_configuration["Authentication:JwtBearer:SecurityKey"]));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(
_configuration["Authentication:JwtBearer:Issuer"],
_configuration["Authentication:JwtBearer:Audience"],
claims,
expires: DateTime.Now.AddMinutes(),
signingCredentials: credentials
); return Ok(new AccessTokenResult {Token = new JwtSecurityTokenHandler().WriteToken(token), Code = });
} return Ok(new AccessTokenResult {Code = , Token = ""});
}

LoginModel是自定义的登录模型,很简单,仅包含用户名和密码两个字段。AccessTokenResult是自定义的返回结果,int类型的Code,登录成功则返回200,失败为0,Token是生成的JWT

三、测试

1、创建TestController,并为其添加  Authorization  描述

2、运行程序,打开Postman,访问 http://localhost:5000/test

不出所料,访问被拒绝,提示没有授权。

3、获取JWT

访问 http://localhost:5000/api/accesstoken

4、使用Token重新访问受限的Action

拷贝token的值,重新请求 http://localhost:5000/test,在Headers上添加一项,KEY 为 Authorization,VALUE 为 Bear+空格+token值

【aspnetcore】配置使用jwt验证的更多相关文章

  1. Jwt验证登录

    练习模板:https://gitee.com/zh1446802857/swagger-multi-version-api.git Jwt在我的 认知里,是一套门锁.别人(用户)需要用到你的接口 的时 ...

  2. 踩坑之路---JWT验证

    使用JWT验证客户的携带的token 客户端在请求接口时,需要在request的head中携带一个token令牌 服务器拿到这个token解析获取用户资源,这里的资源是非重要的用户信息 目前我的理解, ...

  3. webapi中使用token验证(JWT验证)

    本文介绍如何在webapi中使用JWT验证 准备 安装JWT安装包 System.IdentityModel.Tokens.Jwt 你的前端api登录请求的方法,参考 axios.get(" ...

  4. Nginx实现JWT验证-基于OpenResty实现

    介绍 权限认证是接口开发中不可避免的问题,权限认证包括两个方面 接口需要知道调用的用户是谁 接口需要知道该用户是否有权限调用 第1个问题偏向于架构,第2个问题更偏向于业务,因此考虑在架构层解决第1个问 ...

  5. nginx配置ssl双向验证 nginx https ssl证书配置

    1.安装nginx 参考<nginx安装>:http://www.ttlsa.com/nginx/nginx-install-on-linux/ 如果你想在单IP/服务器上配置多个http ...

  6. nginx配置https双向验证(ca机构证书+自签证书)

    nginx配置https双向验证 服务端验证(ca机构证书) 客户端验证(服务器自签证书) 本文用的阿里云签发的免费证书实验,下载nginx安装ssl,文件夹有两个文件 这两个文件用于做服务器http ...

  7. 如何为ASP.NET Core的强类型配置对象添加验证

    原文: Adding validation to strongly typed configuration objects in ASP.NET Core 作者: Andrew Lock 译文: La ...

  8. centos6.5中部署Zeppelin并配置账号密码验证

    centos6.5中部署Zeppelin并配置账号密码验证1.安装JavaZeppelin支持的操作系统如下图所示.在安装Zeppelin之前,你需要在部署的服务器上安装Oracle JDK 1.7或 ...

  9. golang学习笔记10 beego api 用jwt验证auth2 token 获取解码信息

    golang学习笔记10 beego api 用jwt验证auth2 token 获取解码信息 Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放 ...

随机推荐

  1. js一个游戏小笔记

    昨天写了个飞机大战的游戏,没弄好的一点是如何移动炮台. 开始我把移动代码写到了炮台类里面,但是怎么按都不移动.(最烦,代码对,效果不对,╮(╯▽╰)╭) 问过老师才知道,这种移动类游戏,应该把  控制 ...

  2. 修改initrd.img里ko文件的一个小tips

    在经历以下步骤解开initrd.img文件之后: 若file initrd.img 指示initrd.img为gzip文件,则2: mv initrd.img initrd.gz gunzip -d ...

  3. Queue——C#浅谈

    1.Queue定义 System.Collections.Queue类表示对象的先进先出集合,存储在 Queue(队列) 中的对象在一端插入,从另一端移除. 2.优点 1.能对集合进行顺序处理(先进先 ...

  4. pig入门教程(2)

    本文可以让刚接触pig的人对一些基础概念有个初步的了解. 本文的大量实例都是作者Darran Zhang(website: codelast.com)在工作.学习中总结的经验或解决的问题,并且添加了较 ...

  5. 【机器学习】推荐系统、SVD分解降维

    推荐系统: 1.基于内容的实现:KNN等 2.基于协同滤波(CF)实现:SVD → pLSA(从LSA发展而来,由SVD实现).LDA.GDBT SVD算是比较老的方法,后期演进的主题模型主要是pLS ...

  6. ERROR: JDWP Unable to get JNI 1.2 environment的解决方法

    当执行如下代码时: //从控制台获取输入 InputStream is = System.in; Scanner scanner = new Scanner(is); System.out.print ...

  7. 关闭QtCreator的vim风格编辑模式

    今天不小心点到了键盘的快捷键Alt+V,使QtCreator进入了vim风格编辑模式,导致快捷键拷贝粘贴都不正常,找了下资料才发现是这个问题.具体操作如下: 打开QtCreator去掉下列位置的勾选或 ...

  8. Jquery的parent和parents(找到某一特定的祖先元素)用法

    <!-- parent是指取得一个包含着所有匹配元素的唯一父元素的元素集合. parents则是取得一个包含着所有匹配元素的祖先元素的元素集合(不包含根元素).可以通过一个可选的表达式进行筛选. ...

  9. Python中的循环语句

    Python中有while循环和for循环 下面以一个小例子来说明一下用法,用户输入一些数字,输出这些数字中的最大值和最小值 array = [5,4,3,1] for i in array: pri ...

  10. Pillow不支持color emoji font!

    我想在MAC下面用pillow把一些文本转换成PNG图片,在转普通文字的时候都没问题,但在遇到emoji字符的时候就搞不定了,代码如下: import loggingimport PIL.Image ...