.Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书

时间:2023-03-09 14:52:02
.Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书

原文:.Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书

一、客户端模式介绍

客户端模式(Client Credentials Grant)是指客户端直接向认证服务(Authorization Server)发送认证请求,获取token,进行认证,一般适用于受信任的客户端。

.Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书
image.png

请求步骤为:

  • 客户端向认证服务器进行认证,并请求一个访问令牌token
  • 认证服务器进行认证,通过之后,返回客户端一个访问令牌。

二、创建认证服务

  • 创建一个认证服务IdentityServerCenter,通过NuGet安装IdentityServer4
  • 添加配置资源与客户端的文件,引入using IdentityServer4.Models
   public class Config
{
public static IEnumerable<ApiResource> GetResources()
{
return new List<ApiResource> {
new ApiResource {
Name = "ImageResource",
Scopes={ new Scope ("ImageResource")},//Scopes必须配置,否则获取token时返回 invalid_scope
},
new ApiResource { Name = "FileResourse" },
new ApiResource { Name="Api", Scopes={new Scope ("Api") } }
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client> {
new Client {
ClientId = "ClientId",
AllowedGrantTypes =GrantTypes.ClientCredentials,//授权模式:客户端模式
AllowedScopes={ "ImageResource","Api" }, //允许访问的资源 GetResources()中配置的
ClientSecrets={ new Secret { Value= "ClientSecret".Sha256(), Expiration=DateTime.Now.AddMinutes(5)} }
} };
}
}
  • 注入IdentityServer4,添加IdentityServer4配置
        public void ConfigureServices(IServiceCollection services)
{
//注入IdentityServer 添加IdentityServer4配置
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetResources()) //添加配置的资源ApiResource
.AddInMemoryClients(Config.GetClients());//添加配置的客户端Client
// services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
  • 使用IdentityServer4
     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//使用IdentityServer
app.UseIdentityServer();
}
  • 启动项
    .Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书
    image.png

    由于未使用MVC,访问该api返回404。IdentityServer4提供一个地址可获取相关配置项。

http://examplehostname.com.well-known/openid-configuration/

访问 http://localhost:5000/.well-known/openid-configuration 将返回的信息序列化如下

.Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书
image.png

scopes_supported": ["ImageResource", "Api", "offline_access"]即为Config中配置的访问的资源AllowedScopes

  • 使用postman获取token
    .Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书
    image.png

    grant_type为客户端授权client_credentials,client_idClient_SecretConfig中配置的ClientIdSecret。接下来创建一个可访问的资源。

三、创建资源服务

  • 创建一个资源服务项目ImageResourceApi
  • 注入认证
 public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(config => {
config.DefaultScheme = "Bearer";
}).AddIdentityServerAuthentication(option=> {
option.ApiName = "ImageResource";
option.Authority = "http://localhost:5000"; //认证服务的url
option.ApiSecret = "ClientSecret".ToSha256();// 访问的secret
option.RequireHttpsMetadata = false; });
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
} app.UseHttpsRedirection();
//使用认证
app.UseAuthentication();
app.UseMvc();
}
  • 启动资源服务,返回401未授权;
  • 使用postman带着token请求资源服务ImageResourceApi,请求成功。
    .Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书
    image.png