zl程序教程

您现在的位置是:首页 >  后端

当前栏目

ASP.NET Core技术--使用客户端凭证保护API接口

2023-06-13 09:17:24 时间

将IdentityServer4部署到应用中具备如下特点:

  1)、认证服务

  2)、单点登陆

  3)、API访问控制

  4)、联合网关

  5)、专注于定制

  6)、成熟的开源系统

  7)、免费和商业支持

其中API访问控制是IdentityServer4的重要用途之一。换言之,它可以是实现对API接口的保护。具体的步骤如下:

创建空项目

dotnet new -i IdentityServer4.Templates
dotnet new is4empty -n IdentityServer

Install-Package IdentityServer4

定义API资源

public static IEnumerable<ApiResource> GetApis()
{
 return new List<ApiResource>

 {

 new ApiResource("api1", "My API")
 };
}

定义客户端

public static IEnumerable<Client> GetClients()
{
 return new List<Client>
 {
 new Client
 {
 ClientId = "client",
 // no interactive user, use the clientid/secret for 
authentication

 AllowedGrantTypes = GrantTypes.ClientCredentials,
 // secret for authentication

 ClientSecrets =
 {
 new Secret("secret".Sha256())
 },

 // scopes that client has access to

 AllowedScopes = { "api1" }
 }
 };
}

配置IdentityServer服务

public void ConfigureServices(IServiceCollection services) {  var builder = services.AddIdentityServer()  .AddInMemoryIdentityResources(Config.GetIdentityResources())  .AddInMemoryApiResources(Config.GetApis())  .AddInMemoryClients(Config.GetClients()); }

基于策略的授权

参考microsoft官网:

https://learn.microsoft.com/zh-cn/aspnet/core/security/authorization/policies?view=aspnetcore-7.0