前言
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 的客户端服务器)
- /// <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();
搭建 Client
创建一个客户端工程项目, 端口设置为 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
启动授权服务器
发现端点可通过 /.well-known/openid-configuration
获取 token
启动后我们通过 token_endpoint 获取 token
client_id 为我们在授权服务器配置的 clientid,
client_secret 为配置中的 secret,
grant_type 为授权模式此处为客户端模式 (client_credentials),
请求后返回凭证信息,
我们通过 access_token 再去访问资源服务器
使用这种授权类型, 会向 token .
code 200
概要
示例地址:
IdentityServer4 叙述: https://www.cnblogs.com/yyfh/p/11590383.html
来源: https://www.cnblogs.com/yyfh/p/11595658.html