DDD实战11 在项目中使用JWT的token 进行授权验证

步骤:
1.首先要在webapi的管道中 使用认证(Authentication)
2.要在webapi的服务中注册验证条件
代码如下:
namespace Dealer.WebApi
{
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)
{
//2 注册验证条件
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
//是否验证颁发者
ValidateIssuer = true,
//是否验证被颁发者
ValidateAudience = true,
//是否验证过期时间
ValidateLifetime = true,
//是否密钥
ValidateIssuerSigningKey = true,
ValidIssuer = "颁发者",
ValidAudience = "受众",
IssuerSigningKey = JwtSecurityKey.Create("imyourfather_iwanttobegreat")
};
}); 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();
}
AppSetting.SetAppSetting(Configuration.GetSection("ConnectString")); //1.使得webapi支持验证第一步,在管道中注册使用验证
app.UseAuthentication(); app.UseMvc();
}
}
}
3 为webapi控制器中的方法 设置授权 或者 允许匿名

上图所示 为授权给角色为普通用户

上图为允许匿名
步骤4 客户端请求需要授权的地址时在请求头中带上token 下面为一段带token请求的单元测试
[TestMethod]
public void AddDealerForAuthentication()
{
hc = new HttpClient();
UserLoginDto userLoginDto = new UserLoginDto();
userLoginDto.Telephone = "";
userLoginDto.Password = ""; string request = JsonConvert.SerializeObject(userLoginDto);
HttpContent httpContent = new StringContent(request);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = hc.PostAsync("http://localhost:56532/api/Dealer/UserLogin/", httpContent).Result;
var responseValue = response.Content.ReadAsStringAsync().Result;
var responseObj = JsonConvert.DeserializeObject<ResultEntity<UserLoginResultDto>>(responseValue);
//从返回的数据中取出 token
var token = responseObj.Data.Token; AddDealerDto addDealerDto = new AddDealerDto();
addDealerDto.Name = "谢尔顿";
addDealerDto.Tel = "";
addDealerDto.Parentid = Guid.Parse("f060477a-14a8-4ef5-b4b1-1fce2f844c9e");
addDealerDto.EleMoney = ;
addDealerDto.ContactNames = new List<string>() { "谢尔顿" };
addDealerDto.ContactProvinces = new List<string>() { "四川" };
addDealerDto.ContactCities = new List<string>() { "成都" };
addDealerDto.ContactStreets = new List<string>() { "熊猫大道" };
addDealerDto.ContactTels = new List<string>() { "" };
addDealerDto.ContactZeros = new List<string>() { "熊猫区" };
addDealerDto.IsDefaultContact = new List<int>() { }; HttpClient client = new HttpClient();
//请求的时候 在请求头中 带上授权信息 注意下面这行代码
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
request = JsonConvert.SerializeObject(addDealerDto);
httpContent = new StringContent(request);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response = client.PostAsync("http://localhost:56532/api/Dealer/AddDealer/", httpContent).Result;
responseValue = response.Content.ReadAsStringAsync().Result; }
步骤5 如果要在请求中获取token中的某项数据 可以参考一下代码:4
namespace Util.Bearer
{
//为了要使用MVC Controller 要安装 Microsoft.AspNetCore.Mvc.Core包
public class BearerUserInfoController :Controller
{
public string GetUserName()
{
var principal = HttpContext.User as ClaimsPrincipal;
if (principal!=null)
{
foreach (var claim in principal.Claims)
{
if (claim.Subject!=null)
{
var sunjectClaims = claim.Subject.Claims as List<Claim>;
return sunjectClaims[].Value;
}
}
}
return null;
}
}
}
上面为在util项目中创建一个控制器类 继承了这个控制器类的 控制器可以使用其中的方法 获取token中的数据 例如以下:

DDD实战11 在项目中使用JWT的token 进行授权验证的更多相关文章
- DDD实战10 在项目中使用JWT的token
在使用过程中报过一个错误:The algorithm: 'HS256' requires the SecurityKey.KeySize to be greater than '128' bits 是 ...
- 【一起学设计模式】观察者模式实战:真实项目中屡试不爽的瓜娃EventBus到底如何实现观察者模式的?
申明 本文章首发自本人公众号:壹枝花算不算浪漫,如若转载请标明来源! 感兴趣的小伙伴可关注个人公众号:壹枝花算不算浪漫 22.jpg 前言 之前出过一个设计模式的系列文章,这些文章和其他讲设计模式的文 ...
- 实战派 | Java项目中玩转Redis6.0客户端缓存!
原创:微信公众号 码农参上,欢迎分享,转载请保留出处. 哈喽大家好啊,我是Hydra. 在前面的文章中,我们介绍了Redis6.0中的新特性客户端缓存client-side caching,通过tel ...
- sau交流学习社区--songEagle开发系列:Vue.js + Koa.js项目中使用JWT认证
一.前言 JWT(JSON Web Token),是为了在网络环境间传递声明而执行的一种基于JSON的开放标准(RFC 7519). JWT不是一个新鲜的东西,网上相关的介绍已经非常多了.不是很了解的 ...
- 实战:vue项目中导入swiper插件
版本选择 swiper是个常用的插件,现在已经迭代到了第四代:swiper4.常用的版本是swiper3和swiper4,我选择的是swiper3. 安装 安装swiper3的最新版本3.4.2: n ...
- 个人博客开发系列:Vue.js + Koa.js项目中使用JWT认证
前言 JWT(JSON Web Token),是为了在网络环境间传递声明而执行的一种基于JSON的开放标准(RFC 7519). 更多的介绍和说明,以及各种原理,我在此就不多赘诉了.JWT不是一个新鲜 ...
- spring cloud实战与思考(四) JWT之Token主动失效
需求: JWT泄露.密码重置等场景下,需要将未过期但是已经不安全的JWT主动失效. 本文不再复述JWT的基础知识,不了解的小伙伴可以自行Google一下.这里主要是针对以上需求聊一聊解决方案.如果服务 ...
- ASP.NET Core WebAPI中使用JWT Bearer认证和授权
目录 为什么是 JWT Bearer 什么是 JWT JWT 的优缺点 在 WebAPI 中使用 JWT 认证 刷新 Token 使用授权 简单授权 基于固定角色的授权 基于策略的授权 自定义策略授权 ...
- Asp.Net Core 3.1 学习3、Web Api 中基于JWT的token验证及Swagger使用
1.初始JWT 1.1.JWT原理 JWT(JSON Web Token)是目前最流行的跨域身份验证解决方案,他的优势就在于服务器不用存token便于分布式开发,给APP提供数据用于前后端分离的项目. ...
随机推荐
- 【BZOJ 4199】 [Noi2015]品酒大会
[链接]h在这里写链接 [题意] 给你一个长度为n的字符串s; 标志了每一杯酒; 以及n个数字,表示每一杯酒的美味度ai. 两杯酒(i,j)称为r相似 当且仅当 ...
- Learn from Architects of Buildings
 Learn from Architects of Buildings Keith Braithwaite Architecture is a social act and the material ...
- 幻灯展示jQuery插件supersized
主要特性: 能够自动修改图片大小适合浏览器的页面大小 通过幻灯展示的循环背景可以动态加载并且可以设置变化方式 核心版本可以支持仅仅需要背景变化大小的需要 键盘导航 整合Flickr - 可以从用户,组 ...
- js进阶 12-8 如何知道上一个函数的返回值是什么(如何判断上一个函数是否执行成功)
js进阶 12-8 如何知道上一个函数的返回值是什么(如何判断上一个函数是否执行成功) 一.总结 一句话总结:event的result属性即可. 1.event的result属性的实际应用场景是什么? ...
- php websocket-网页实时聊天之PHP实现websocket(ajax长轮询和websocket都可以时间网络聊天室)
php websocket-网页实时聊天之PHP实现websocket(ajax长轮询和websocket都可以时间网络聊天室) 一.总结 1.ajax长轮询和websocket都可以时间网络聊天室 ...
- POJ 3624 Charm Bracelet 0-1背包
传送门:http://poj.org/problem?id=3624 题目大意:XXX去珠宝店,她需要N件首饰,能带的首饰总重量不超过M,要求不超过M的情况下,使首饰的魔力值(D)最大. 0-1背包入 ...
- 29、从零写USB摄像头驱动之通过urb接受数据后上报数据是函数中fid的作用
原因分析如下: 视频数据是由一帧一帧数据组成,为了防止数据错乱,会给每一帧数据分配一个frameid,从第0帧开始,接着是第1帧,接着又是第0帧这样交错进行的,对usb摄像头来说每一帧数据来源于多个包 ...
- embed-it_Integrator memory compile工具使用之二
embed-it_Integrator memory compile工具使用之二 主要内容 使用ish接口自动加载memory的cfg文件运行生成memory 脚本内容 打开Integrate &am ...
- ArcGIS IQueryFilter接口
樱木 原文IQueryFilter 1.IQueryFilter::SubFields (1)默认值为“*”,即查询时返回整行数据,如果只需要某一个字段数据(比如“Country”字段),则可以指定 ...
- linux(debian)系统django配远程连接sqlserver数据库
费了将近一天时间.最终解决,记下来留给须要的人 须要安装的: python-odbc : https://github.com/mkleehammer/pyodbc下载后install 安装pytho ...