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 = "1111111"; userLoginDto.Password = "111111"; 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 = "13212778804"; addDealerDto.Parentid = Guid.Parse("f060477a-14a8-4ef5-b4b1-1fce2f844c9e"); addDealerDto.EleMoney = 100; 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>() { "028222223" }; addDealerDto.ContactZeros = new List<string>() { "熊猫区" }; addDealerDto.IsDefaultContact = new List<int>() { 1 }; 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[0].Value; } } } return null; } } }
上面为在util项目中创建一个控制器类 继承了这个控制器类的 控制器可以使用其中的方法 获取token中的数据 例如以下: