客户端模式(Client Credentials Grant)是指客户端直接向认证服务(Authorization Server)发送认证请求,获取token
,进行认证,通常适用于受信任的客户端。
java
- 客户端向认证服务器进行认证,并请求一个访问令牌
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();
}
- 启动项
image.png
因为未使用MVC
,访问该api
返回404。IdentityServer4
提供一个地址可获取相关配置项。
http://examplehostname.com.well-known/openid-configuration/
访问 http://localhost:5000/.well-known/openid-configuration 将返回的信息序列化以下
api
scopes_supported": ["ImageResource", "Api", "offline_access"]
即为
Config
中配置的访问的资源
AllowedScopes
。
- 使用
postman
获取token
image.png
grant_type
为客户端受权client_credentials
,client_id
与Client_Secret
为Config
中配置的ClientId
与Secret
。接下来建立一个可访问的资源。
- 建立一个资源服务项目
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
,请求成功。
image.png