步骤:

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 进行授权验证的更多相关文章

  1. DDD实战10 在项目中使用JWT的token

    在使用过程中报过一个错误:The algorithm: 'HS256' requires the SecurityKey.KeySize to be greater than '128' bits 是 ...

  2. 【一起学设计模式】观察者模式实战:真实项目中屡试不爽的瓜娃EventBus到底如何实现观察者模式的?

    申明 本文章首发自本人公众号:壹枝花算不算浪漫,如若转载请标明来源! 感兴趣的小伙伴可关注个人公众号:壹枝花算不算浪漫 22.jpg 前言 之前出过一个设计模式的系列文章,这些文章和其他讲设计模式的文 ...

  3. 实战派 | Java项目中玩转Redis6.0客户端缓存!

    原创:微信公众号 码农参上,欢迎分享,转载请保留出处. 哈喽大家好啊,我是Hydra. 在前面的文章中,我们介绍了Redis6.0中的新特性客户端缓存client-side caching,通过tel ...

  4. sau交流学习社区--songEagle开发系列:Vue.js + Koa.js项目中使用JWT认证

    一.前言 JWT(JSON Web Token),是为了在网络环境间传递声明而执行的一种基于JSON的开放标准(RFC 7519). JWT不是一个新鲜的东西,网上相关的介绍已经非常多了.不是很了解的 ...

  5. 实战:vue项目中导入swiper插件

    版本选择 swiper是个常用的插件,现在已经迭代到了第四代:swiper4.常用的版本是swiper3和swiper4,我选择的是swiper3. 安装 安装swiper3的最新版本3.4.2: n ...

  6. 个人博客开发系列:Vue.js + Koa.js项目中使用JWT认证

    前言 JWT(JSON Web Token),是为了在网络环境间传递声明而执行的一种基于JSON的开放标准(RFC 7519). 更多的介绍和说明,以及各种原理,我在此就不多赘诉了.JWT不是一个新鲜 ...

  7. spring cloud实战与思考(四) JWT之Token主动失效

    需求: JWT泄露.密码重置等场景下,需要将未过期但是已经不安全的JWT主动失效. 本文不再复述JWT的基础知识,不了解的小伙伴可以自行Google一下.这里主要是针对以上需求聊一聊解决方案.如果服务 ...

  8. ASP.NET Core WebAPI中使用JWT Bearer认证和授权

    目录 为什么是 JWT Bearer 什么是 JWT JWT 的优缺点 在 WebAPI 中使用 JWT 认证 刷新 Token 使用授权 简单授权 基于固定角色的授权 基于策略的授权 自定义策略授权 ...

  9. Asp.Net Core 3.1 学习3、Web Api 中基于JWT的token验证及Swagger使用

    1.初始JWT 1.1.JWT原理 JWT(JSON Web Token)是目前最流行的跨域身份验证解决方案,他的优势就在于服务器不用存token便于分布式开发,给APP提供数据用于前后端分离的项目. ...

随机推荐

  1. Java反射机制的简单应用

    一直感觉java的反射机制非常强大,可是可用的地方不多.在android学习的时候.一直想实现挂断电话的功能,可是系统并没有提供开放的api接口,看了一下网上使用反射机制来实现该功能,确实非常强大,非 ...

  2. [Docker] Build a Simple Node.js Web Server with Docker

    Learn how to build a simple Node.js web server with Docker. In this lesson, we'll create a Dockerfil ...

  3. swift学习第十三天:类的构造函数

    类的构造函数 构造函数的介绍 构造函数类似于OC中的初始化方法:init方法 默认情况下载创建一个类时,必然会调用一个构造函数 即便是没有编写任何构造函数,编译器也会提供一个默认的构造函数. 如果是继 ...

  4. 【JAVA编码专题】总结 分类: B1_JAVA 2015-02-11 15:11 290人阅读 评论(0) 收藏

    第一部分:编码基础 为什么需要编码:用计算机看得懂的语言(二进制数)表示各种各样的字符. 一.基本概念 ASCII.Unicode.big5.GBK等为字符集,它们只定义了这个字符集内有哪些字符,以及 ...

  5. hadoop配置文件的加载机制 分类: A1_HADOOP 2015-01-21 11:29 839人阅读 评论(0) 收藏

    hadoop通过Configuration类来保存配置信息 1.通过Configuration.addResource()来加载配置文件 2.通过Configuration.get***()来获取配置 ...

  6. 使用Verdi理解RTL design

    使用Verdi理解RTL design 接触到一些RTL代码,在阅读与深入理解的过程中的一些思考记录 协议与设计框图 认真反复阅读理解相关协议与设计框图,一个design的设计文档中,设计框图展示了这 ...

  7. Windows Server 2012 R2 部署 Exchange 2013

    我的环境在DC上 ,一般建议Exchange 增加DC 通过管理员权限执行PowerShell 来安装一些IIS组件, 安装命令例如以下: Install-WindowsFeature AS-HTTP ...

  8. 11G、12C安装结束需要做的一些操作

    修改spfile参数:修改前,先备份 create pfile from spfile; alter system set memory_target=0 scope=spfile;alter sys ...

  9. Django表单上传

    任务描述:实现表单提交(上传文件) 1.项目目录: 2.源代码: regist.html <!DOCTYPE html> <html lang="en"> ...

  10. [React Router v4] Render Multiple Components for the Same Route

    React Router v4 allows us to render Routes as components wherever we like in our components. This ca ...