JWT(json web token)--.JwtBearer IdentityServer4--客户端凭证授权
新建ASP .NET Core Web Api ,名称Linjie.JWT.IDS4
2、右键项目 NuGet程序包管理工具 添加IdentityServer4,注意版本 不要选4.x.x以上的,选择4.x.x以下的,本文选择的是3.1.3,原因是4.x.x版本相对3.x.x版本的改动比较大
3、添加类 IDS4Client,该类用于获取数据代码如下:
using IdentityServer4.Models; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace Linjie.JWT.IDS4 { public class IDS4Client { public static IEnumerable<Client> GetClient() { return new[] { new Client() { //ClientCredentials 客户端验证的话,只需要ClientId,ClientSecrets即可 ClientId = "id123456", ClientSecrets = new []{ new Secret("secret123456".Sha256()) },//注意密码必须要加密,本文使用Sha256加密 AllowedGrantTypes =GrantTypes.ClientCredentials,//授权方式是有5种,本文使用最简单的客户端授权方式 ClientCredentials AllowedScopes = new [] { "webapi" },//访问应用域 Claims = new List<Claim> { //身份信息 new Claim(IdentityModel.JwtClaimTypes.Role,"李四"), new Claim(ClaimTypes.Email,"8888@qq.com"), new Claim(IdentityModel.JwtClaimTypes.NickName,"kkkk")}, }}; } public static IEnumerable<ApiResource> GetResources() { return new[] { new ApiResource("webapi") }; } } }
4、修改类 Startup,代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Linjie.JWT.IDS4 { 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) { services.AddControllers(); services.AddIdentityServer()//认证授权服务器 .AddDeveloperSigningCredential()//认证授权证书,这类使用临时的开发版证书,运行时会自动生成一个证书tempkey .AddInMemoryClients(IDS4Client.GetClient())//设置认证的授权类型 .AddInMemoryApiResources(IDS4Client.GetResources());//设置认证的授权可以访问的资源 } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseIdentityServer();//启用认证授权服务器 app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
5、运行项目,获取token
这里有几点注意项
1、使用ids4 获取token时,约定:地址+/connect/token,请求地址为 https://lip:port/connect/token,本文使用http://localhost:5000/connect/token
2、请求方法POST,请求参数client_Id,client_secret,grant_type
如下:
使用postman 请求地址,获取token,如下图
可以使用 https://jwt.io/ 来解析,如下图
6、IdentityServer4产生的token的使用
a、新建项目ASP .NET Core Web Api ,名称Linjie.WebApi,NuGet程序管理包添加IdentityServer4.AccessTokenValidation,
b、添加TestController类,代码如下
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Linjie.WebApi.Controllers { [ApiController] [Route("webapi/[controller]")] public class TestController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<TestController> _logger; public TestController(ILogger<TestController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } [HttpGet("{id}")] public string Get(int id) { var rng = $"收到数据:{id}"; return rng; } [Authorize]//添加授权验证,访问该接口需要token验证 [HttpGet("late/{id}")] public string GetLate(int id) { var rng = $"需要授权验证,收到数据:{id}"; return rng; } } }
c、startup类代码如下
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using IdentityServer4.AccessTokenValidation; namespace Linjie.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) { services.AddControllers(); services.AddAuthentication("Bearer")//设置认证授权的主题方案,不能写成bearer,必须时 Bearer .AddIdentityServerAuthentication(option => { option.Authority = "http://localhost:6000";//ids4 认证授权服务器地址 option.ApiName = "webapi";//api资源 option.RequireHttpsMetadata = false; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication();//启用认证 app.UseAuthorization();//启用权限验证 app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
d、修改Linjie.JWT.IDS4中的,launchSettings.json的applicationUrl,改成 "applicationUrl": "https://localhost:6001;http://localhost:6000",然后 同时启动Linjie.JWT.IDS4和Linjie.WebApi项目,访问 http://localhost:5000/webapi/test/late/1
访问http://localhost:6000/connect/token 获取token,在postman中添加token,类型为Bearer Token,
再访问 http://localhost:5000/webapi/test/late/1 如下: