【aspnetcore】配置使用jwt验证
因为害怕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验证的更多相关文章
- Jwt验证登录
练习模板:https://gitee.com/zh1446802857/swagger-multi-version-api.git Jwt在我的 认知里,是一套门锁.别人(用户)需要用到你的接口 的时 ...
- 踩坑之路---JWT验证
使用JWT验证客户的携带的token 客户端在请求接口时,需要在request的head中携带一个token令牌 服务器拿到这个token解析获取用户资源,这里的资源是非重要的用户信息 目前我的理解, ...
- webapi中使用token验证(JWT验证)
本文介绍如何在webapi中使用JWT验证 准备 安装JWT安装包 System.IdentityModel.Tokens.Jwt 你的前端api登录请求的方法,参考 axios.get(" ...
- Nginx实现JWT验证-基于OpenResty实现
介绍 权限认证是接口开发中不可避免的问题,权限认证包括两个方面 接口需要知道调用的用户是谁 接口需要知道该用户是否有权限调用 第1个问题偏向于架构,第2个问题更偏向于业务,因此考虑在架构层解决第1个问 ...
- nginx配置ssl双向验证 nginx https ssl证书配置
1.安装nginx 参考<nginx安装>:http://www.ttlsa.com/nginx/nginx-install-on-linux/ 如果你想在单IP/服务器上配置多个http ...
- nginx配置https双向验证(ca机构证书+自签证书)
nginx配置https双向验证 服务端验证(ca机构证书) 客户端验证(服务器自签证书) 本文用的阿里云签发的免费证书实验,下载nginx安装ssl,文件夹有两个文件 这两个文件用于做服务器http ...
- 如何为ASP.NET Core的强类型配置对象添加验证
原文: Adding validation to strongly typed configuration objects in ASP.NET Core 作者: Andrew Lock 译文: La ...
- centos6.5中部署Zeppelin并配置账号密码验证
centos6.5中部署Zeppelin并配置账号密码验证1.安装JavaZeppelin支持的操作系统如下图所示.在安装Zeppelin之前,你需要在部署的服务器上安装Oracle JDK 1.7或 ...
- golang学习笔记10 beego api 用jwt验证auth2 token 获取解码信息
golang学习笔记10 beego api 用jwt验证auth2 token 获取解码信息 Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放 ...
随机推荐
- grep的用法(转)
grep参数 -c : 显示匹配的行数(就是显示有多少行匹配了): -n :显示匹配内容所在文档的行号: -i :匹配时忽略大小写: -s :错误信息不输出: -v :输出不匹配内容: -o : ...
- 2006浙大火星A+B
题目描述: 读入两个不超过25位的火星正整数A和B,计算A+B.需要注意的是:在火星上,整数不是单一进制的,第n位的进制就是第n个素数.例如:地球上的10进制数2,在火星上记为“1,0”,因为 ...
- 【转】 Pro Android学习笔记(六一):Preferences(5):组织Preference
目录(?)[-] PreferenceCategory Child Preference PreferenceCategory 如果有多个preference,我们希望能在他们组织在一起.有两种方式, ...
- UML核心元素--分析类
分析类共有三个:边界类(boundary).控制类(control)和实体类(entity),这些分析类都是类的版型.分析类是跨越需求到设计实现的桥梁. 边界类:从需求向现实的转换过程中,任何两个有交 ...
- [51nod1272]最大距离(贪心)
解题关键:对num进行排序,从前往后扫id,及时更新 #include<cstdio> #include<cstring> #include<algorithm> ...
- 【总结整理】JQuery基础学习---动画
jQuery中隐藏元素的hide方法 让页面上的元素不可见,一般可以通过设置css的display为none属性.但是通过css直接修改是静态的布局,如果在代码执行的时候,一般是通过js控制元素的st ...
- SpringSecurity04 利用JPA和SpringSecurity实现前后端分离的认证和授权
1 环境搭建 1.1 环境说明 JDK:1.8 MAVEN:3.5 SpringBoot:2.0.4 SpringSecurity:5.0.7 IDEA:2017.02旗舰版 1.2 环境搭建 创建一 ...
- 转:基于InfluxDB&Grafana的JMeter实时性能测试数据的监控和展示
本文主要讲述如何利用JMeter监听器Backend Listener,配合使用InfluxDB+Grafana展示实时性能测试数据 关于JMeter实时测试数据 JMeter从2.11版本开始,命令 ...
- MQTT协议实现Eclipse Paho学习总结二
一.概述 前一篇博客(MQTT协议实现Eclipse Paho学习总结一) 写了一些MQTT协议相关的一些概述和其实现Eclipse Paho的报文类别,同时对心跳包进行了分析.这篇文章,在不涉及MQ ...
- 1.如何绕过WAF(Web应用防火墙)
一:大小写转换法: 看字面就知道是什么意思了,就是把大写的小写,小写的大写.比如: SQL:sEleCt vERsIoN(); XSS:)</script> 出现原因:在waf里,使用 ...