1.新建ASP.NET Core Web 应用程序,程序文件如下图
引用以下包
2.新建config类配置客户端列表
public static class Config
{
public static IEnumerable<IdentityResource> IdentityResources =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
/// <summary>
/// api范围
/// </summary>
public static IEnumerable<ApiScope> ApiScopes =>
new ApiScope[]
{
new ApiScope("api")
};
/// <summary>
/// api资源
/// </summary>
public static IEnumerable<ApiResource> ApiResources =>
new ApiResource[]
{
new ApiResource("api","#api")
{
Scopes = { "api" }
}
};
public static IEnumerable<Client> GetClientConfigList()
{
var appInfo = Account.Instance.GetApps(); //这个是从数据库获取已配置的客户端。
List<Client> Clients = new List<Client>();
foreach (var item in appInfo)
{
Client client = new Client();
client.ClientId = item.App_ID;
client.AllowedGrantTypes = GrantTypes.ClientCredentials;//授权类型,这里使用的是客户端凭证模式
client.ClientSecrets.Add(new Secret(item.App_Key.Sha256()));
client.AllowedScopes.Add("api");
client.AccessTokenLifetime = 36000;//配置Token 失效时间
Clients.Add(client);
}
return Clients;
}
}
public class Account
{
public static Account Instance = new Account();
public List<Z_Token> GetApps()
{
var list = ConetextHelper.context.Set<Z_Token>().ToList();
return list;
}
}
3.在Startup.cs里面配置id4
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.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
services.AddIdentityServer(options =>
{
options.Caching.ClientStoreExpiration = TimeSpan.FromMinutes(5);//设置缓存过期时间 多久去数据去取一次数据库? ? ? ? ? ?
}).AddInMemoryIdentityResources(Config.IdentityResources)
.AddInMemoryApiScopes(Config.ApiScopes)
.AddInMemoryApiResources(Config.ApiResources)//把受保护的Api资源添加到内存中
.AddClientStore<ClientStore>().AddInMemoryCaching()
.AddClientStoreCache<ClientStore>()
.AddSigningCredential(new X509Certificate2(Path.Combine(basePath,
Configuration["Certificates:CertPath"]), //证书
Configuration["Certificates:Password"])); ;//证书密码
}
// 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.UseRouting();
//启用id4,将id4中间件添加到管道中
app.UseIdentityServer();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("IdentityServer is Already Start!");
});
});
}
}
证书,证书密码在appsettings.json里配置
"Certificates": {
"CertPath": "Certificates/idsrv4.pfx",
"Password": "123.zg"
}
4.证书和证书密码来源配置
1>下载Openssl
https://oomake.com/download/openssl
2>配置环境变量
3>生成证书
打开cmd,cd 到项目文件中
1.申请一个私钥,在命令行中输入:openssl genrsa -out idsrv4.key 2048
2.申请一个公钥,在命令行中输入:openssl req -newkey rsa:2048 -nodes -keyout idsrv4.key -x509 -days 365 -out idsrv4.cer
Country Name (2 letter code) []:CN // 输入国家代码,中国填写
CNState or Province Name (full name) []:JiangSu // 输入省份,这里填写 HangZhouLocality Name (eg, city) []:NanJing // 输入城市,我们这里也填写 HangZhouOrganization Name (eg, company) []:newWave // 输入组织机构(或公司名)
Organizational Unit Name (eg, section) []:newWave // 输入机构部门
Common Name (eg, fully qualified host name) []:awave // 输入域名
Email Address []:461192412@qq.com // 你的邮箱地址
3.openssl pkcs12 -export -in idsrv4.cer -inkey idsrv4.key -out idsrv4.pfx
输入密码和确认密码
4>验证JWT Token
网址:https://jwt.io/
5.webapi调用
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
1>在Startup.cs里面配置
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.AddDbContext<StudyNetCoreContext>(optionsBuilder => {
var dataAppSetting = Configuration.GetConnectionString("SqlServer");
if (dataAppSetting == null)
{
throw new Exception("未配置数据库连接");
}
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("SqlServer")); //读取配置文件中的链接字符串
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).
AddJwtBearer(JwtBearerDefaults.AuthenticationScheme,
options => {
//身份认证平台地址(身份认证时会去这个地址验证token是否有效)
options.Authority = Configuration["AppSettings:IdentityServerUrl"];
options.RequireHttpsMetadata = false; //一般默认(true),开发环境时可以设置为false
options.TokenValidationParameters.RequireExpirationTime = true; //是否需要超时时间参数
//apiResource
options.Audience = Configuration["AppSettings:Audience"];
options.SaveToken = true;
});
services.AddControllersWithViews();
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Configuration[“AppSettings:IdentityServerUrl”];这里是id4微服务的地址
Configuration[“AppSettings:Audience”];这里是微服务开发的可访问资源名称
app.UseAuthentication();
app.UseAuthorization(); 启用验证
2>在api控制器里面加上 [Authorize],代表验证
3>token效果调用
微服务网址: https://localhost:44320/connect/token
访问参数:grant_type:client_credentials //客户端凭证
client_id:客户端名称
client_secret:客户端秘钥
获取到token后,调用自己的webapi资源
在头文件里面加上参数:
Authorization :Bearer+空格+token
访问成功,权限验证全部完成。