什么是IdentityServer4
官方解释:IdentityServer4是基于ASP.NET Core实现的认证和授权框架,是对OpenID Connect和OAuth 2.0协议的实现。
通俗来讲,就是服务端对需要认证授权的资源(客户端请求资源)在外层使用IdentityServer4框架进行封装加壳,用户只能通过获取IdentityServer4颁发的Token令牌才能进行资源访问。
下面开始进入正题,如何快速搭建实现API接口鉴权。
准备:1.下载准备NetCore sdk环境
2.本文开发环境为VS2019,部分代码可能和之前的版本不同。
第一步,新建权限认证服务项目,本文以Net Core API项目模板为例(也可以选择其他模板)

第二步,添加IdentityServer4 Nuget程序包。不同版本依赖的NetCoe sdk环境不同,需手动选择合适版本。

这里提醒一下,有些同学的系统可能添加Nuget程序包时,发现无法找到程序包。我们这里找出了解决方法,点击Nuget程序包添加页面的右上角设置按钮,看到如下页面,手动添加如下的nuget.org,然后重新搜索即可。

第三步,添加IdentityServer4配置管理类。本文以用户密码授权模式为例。
public class Config
{
/// <summary>
/// 定义资源范围
/// </summary>
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "我的第一个API")
};
}
/// <summary>
/// 定义访问的资源客户端
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client{
ClientId="client",//定义客户端ID
ClientSecrets=
{
new Secret("secret".Sha256())//定义客户端秘钥
},
AllowedGrantTypes=GrantTypes.ResourceOwnerPassword,//授权方式为用户密码模式授权,类型可参考GrantTypes枚举
AllowedScopes={ "api1"}//允许客户端访问的范围
}
};
}
/// <summary>
/// 这个方法是来规范tooken生成的规则和方法的。一般不进行设置,直接采用默认的即可。
/// </summary>
/// <returns></returns>
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new IdentityResource[]
{
new IdentityResources.OpenId()
};
}
}
第四步,Startup启动类中注册服务中间件
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()//注册服务
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())//配置类定义的授权范围
.AddInMemoryClients(Config.GetClients())//配置类定义的授权客户端
.AddTestUsers(new List<TestUser> { new TestUser { Username = "Admin", Password = "123456", SubjectId = "001", IsActive = true } });//模拟测试用户,这里偷懒了,用户可以单独管理,最好不要直接在这里New
services.AddControllers();
}
// 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();
});
}








