asp.net core IdentityServer4 实现 Client credentials(客户端凭证)

OAuth 2.0默认四种授权模式(GrantType)

授权码模式(authorization_code)
简化模式(implicit)
密码模式(resource owner password credentials)
客户端模式(client_credentials)
本章主要介绍客户端模式(client credentials)
,他主要是由两部分构成客户端和认证服务器.
认证服务器在确定客户端信息无误后向客户端返回token,客户端请求资源时带着该token进行访问.(在这种模式中用户可直接向客户端注册,客户端再以自己的名义请求认证服务器)

搭建认证服务器

创建一个Api项目工程,端口设置为5000

Package

PM> Install-package IdentityServer4 -version 2.5.3

创建一个类Config(配置要保护的资源和可以访问该API的客户端服务器)

Copy
///
/// Identity配置
///
public class Config
{
///
/// 定义要保护的资源
///
///
public static IEnumerable GetApiResources() {
return new List
{
new ApiResource(“api1”, “My API”)
};
}
///
/// 定义授权客户端
///
///
public static IEnumerable GetClients() {
return new List
{
new Client()
{
ClientId = “client”,
AllowedGrantTypes = GrantTypes.ClientCredentials, //设置模式,客户端模式
ClientSecrets =
{
new Secret(“secret”.Sha256())
},
AllowedScopes = { “api1” }
}
};
}
}
配置Startup

在ConfigureServices方法中注入IdentityServer4服务

Copy
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddIdentityServer()//IdentityServer4服务
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources()) //配置资源
.AddInMemoryClients(Config.GetClients());//把配置文件的Client配置资源放到内存
}
在Configure方法中添加IdentityServer4服务中间件

app.UseIdentityServer();

搭建Client

创建一个客户端工程项目,端口设置为5001

Package

PM> Install-package IdentityServer4.AccessTokenValidation -version 2.7.0

配置Startup

在ConfigureServices添加认证服务器地址

Copy
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(“Bearer”)
.AddIdentityServerAuthentication(options =>
{
options.Authority = “http://localhost:5000”;//授权服务器地址
options.RequireHttpsMetadata = false;//不需要https
options.ApiName = “api1”;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
在Configure方法中添加IdentityServer4服务中间件

app.UseIdentityServer();
深圳网站建设www.sz886.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值