DDD实战11 在项目中使用JWT的token 进行授权验证
2024-10-01 23:19:04
步骤:
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中的数据 例如以下:
最新文章
- Sublime Text 3 快捷键汇总
- express-16 与生产相关的问题2
- no.1
- 解决Ubuntu下Sublime Text 3无法输入中文
- 使用Windows Azure PowerShell远程管理Windows Azure虚拟机
- Liunx系统学习一,liunx系统的目录结构及含义
- Android系统移植与驱动开发——第六章——使用实例来理解Linux驱动开发及心得
- P0口上拉电阻选择
- poi HSSFRichTextString 对cell中的每一段文字设置字体
- javaFile循环列出指定目录下的所有文件(源代码)
- NET那点不为人知的事
- Objective-c 多线程操作 自定义NSOperation 模拟下载
- 【转】Java并发的AQS原理详解
- Oracle课程档案,第五天
- 2、Python-流程控制
- c/c++ 某些特殊数的大小
- Java入门与基础算法班 - 课程大纲
- 内存,缓存,cpu,硬盘关系
- 图解 CMS 垃圾回收机制,你值得拥有(转 强烈推荐)
- 13 tcp3次握手 4次释放 mac和ip 访问百度的过程
热门文章
- 【hdu 6194】string string string
- HBase -ROOT-和.META.表结构(region定位原理) 分类: B7_HBASE 2015-03-13 20:52 90人阅读 评论(0) 收藏
- keil编译后Program Size: Code=46284 RO-data=988 RW-data=580 ZI-data=1094588
- ConcurrentLinkedQueue使用方法
- 关于CoordinatorLayout与Behavior的一点分析
- Django项目开发实例之我的博客
- <;Linux>; Linux下一些常用命令(个人记录)
- http://lists.mysql.com/mysql
- STL map 按key值和按value值排序
- 后台报错java.lang.IllegalArgumentException: Invalid character found in the request target.