您的位置:首页 > 编程语言 > ASP

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

2020-01-14 10:10 671 查看

前言

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

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

搭建认证服务器

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

Package

PM> Install-package IdentityServer4 -version 2.5.3

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

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

在ConfigureServices方法中注入IdentityServer4服务

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();

搭建 Api Resource

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

Package

PM> Install-package IdentityServer4.AccessTokenValidation -version 2.7.0

配置Startup

在ConfigureServices添加认证服务器地址

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();

测试

在客户端values控制器上面增加[Authorize]

直接访问资源服务器http://localhost:5001/api/values

访问受限了 code 401

启动授权服务器

http://localhost:5000/.well-known/openid-configuration

发现端点可通过/.well-known/openid-configuration

获取token

启动后我们通过token_endpoint获取token

client_id为我们在授权服务器配置的clientid,
client_secret为配置中的secret,
grant_type为授权模式此处为客户端模式(client_credentials),
请求后返回凭证信息,
我们通过access_token再去访问资源服务器
使用这种授权类型,会向token 。

code 200

概要

示例地址:https://github.com/fhcodegit/IdentityServer4.Samples
IdentityServer4叙述:https://www.geek-share.com/detail/2780475620.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
HueiFeng 发布了50 篇原创文章 · 获赞 53 · 访问量 2271 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐