identityServer4-客户端模式

客户端模式

开始以前请先看下阮一峰大神的OAuth2.0的博客,或者这个系列的前两篇关于OAuith和openid的介绍,对这两个东西有个大概的了解,同时贴出一些参考的博客

授权服务器搭建

第一步安装identityServer4

Install-Package identityserver4

第二步编写配置类

我们新建一个叫identityServerContent的webapi的项目
添加一个config类

//config 
public class config {
      //配置api resource
   public static List GetResources()
   {
        return new List
        {
               new ApiResource('api','My API')
        }      
   }
    
   public static List GetClients()
   {
       return new List()
      {
          new Client()
          {
                ClientId="client",
                AllowedGrantTypes= GrantTypes.ClientCredentials,//模式:最简单的模式
                ClientSecrets={//私钥
                        new Secret("secret".Sha256())
                },
                AllowedScopes={//可以访问的Resource
                        "api"
                }
          }
      }
   }

}
第三步注入identityServer4

在Startup.cs中注入ids4

services.AddIdentityServer()
    .AddDeveloperSigningCredential()//添加开发人员签名凭据
    .AddInMemoryApiResources(Config.GetResources())//添加内存apiresource
    .AddInMemoryClients(Config.GetClients());//添加内存client

到此我们的授权服务端算是完成了

客户端集成IdentityServer

安装包

首先新建一个webapi的项目,同时安装中间件
dotnet new webapi --name ClientCredentialApi
Install-Package IdentityServer4.AccessTokenValidation

注入Di
services.AddAuthentication("Bearer")//添加授权模式
    .AddIdentityServerAuthentication(Options=>{
        Options.Authority="http://localhost:5000";//授权服务器地址
        Options.RequireHttpsMetadata=false;//是否是https
        Options.ApiName="api";
   });

同时把所有控制器打上[Authorize]的标记,到此我们客户端配置已经完成了

使用postman来测试接口

我们分别启动这两个项目,5000端口代表授权服务器,5001代表Api服务器
1.使用postman来测试调用

到此我们的客户端模式编写完成,下篇我们将开始密码模式
推荐参考 博客园 晓晨master大佬的identityServer4系列

你可能感兴趣的:(identityServer4-客户端模式)