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