1.1 认证授权中心代码
在内部系统调用,或者高信任客户端调用可以采用。
使用之前的IdentityServer4 -ClientCredential模式代码,在IdentityServer.ServerCenter
项目中,修改IdentityConfig.cs
配置,新增客户端配置,加入测试用户代码如下:
public class IdentityConfig
{
/// <summary>
/// ApiResource
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetResource()
{
return new List<ApiResource>() {
new ApiResource("UserAPI","OrderAPI"){
} };
}
/// <summary>
/// Client
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
var clientApp = new Client()
{
ClientId = "App1",
ClientName = "App",
AllowedGrantTypes = new List<string>() {
GrantType.ClientCredentials },
ClientSecrets = new List<Secret>() {
new Secret("Secret".Sha256())
},
AllowedScopes = { "UserAPI"}
};
var clientWebMVC = new Client()
{
ClientId = "WebMVC1",
ClientName = "WebMVC1"
,
AllowedGrantTypes = new List<string>(){
GrantType.ResourceOwnerPassword
},
ClientSecrets = new List<Secret>() {
new Secret("WebMVCSecret".Sha256())
}
};
return new List<Client>() {
clientApp,clientWebMVC
};
}
public static List<TestUser> GetTestUsers()
{
return new List<TestUser>()
{
new TestUser(){
Username="WebMVC_Main",
Password="WeMVC_Pwd",
SubjectId="1001"
}
};
}
}
修改Startup.cs文件,使用内存中的测试用户
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()//添加服务
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(IdentityConfig.GetResource())//Api 资源
.AddInMemoryClients(IdentityConfig.GetClients())//Api的客户端
.AddTestUsers(IdentityConfig.GetTestUsers());//添加测试用户
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
启动IdentityServer.ServerCenter
项目,使用PostMan来模拟获取Token。
报文信息参考如下:
POST /connect/token HTTP/1.1
Host: localhost:4000
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 63b8ec74-9901-8721-391c-3c8b9f4076df
client_id=WebMVC1&client_secret=WebMVCSecret&grant_type=password&username=WebMVC_Main&password=WeMVC_Pwd&=
返回信息如下:
{
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImUyM2FkOWMxZmQwZjJjMDU2YTVlN2I3MzU1OWU5MDY1IiwidHlwIjoiSldUIn0.eyJuYmYiOjE1NDQ1MDkyNTAsImV4cCI6MTU0NDUxMjg1MCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo0MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NDAwMC9yZXNvdXJjZXMiLCJVc2VyQVBJIl0sImNsaWVudF9pZCI6IldlYk1WQzEiLCJzdWIiOiIxMDAxIiwiYXV0aF90aW1lIjoxNTQ0NTA5MjUwLCJpZHAiOiJsb2NhbCIsInNjb3BlIjpbIlVzZXJBUEkiXSwiYW1yIjpbInB3ZCJdfQ.NJPDnBvALBH0fbulqpXmviu1M_FT72fnV6GLaL62lvl6mjksaIshaQj-iher1MthCejnjrV_Se9S4vNaSaolDv1wuv5la1Ex3S9_U9D_2sAq4huvjm6SiEexD-rrr9Q1T0kqceJ-AL7dE0wTcwxSBOSBRSSG6soJuKiPsPzIUJJGgsRkj_kmYmuLse2YetAWSRBUl9KNDaiJ55pSH7wQcE3Vp1hxPI6HwBjCQlUSFACFrzcBPEWpCBI4YugYLhYCfWSO98-KJxkrc-hu7dyqakIP3mo2YCGzYJX6qs5UpA1jL0cCbPS0otDo2zYBuQJJoNfzpTdaBXi3Uo_bOeh-2A",
"expires_in": 3600,
"token_type": "Bearer"
}
1.2 第三方Client 调用代码
代码如下:
using System;
using System.Net.Http;
using IdentityModel;
using IdentityModel.Client;
namespace IdentityServer.UseCmd
{
class Program
{
static void Main(string[] args)
{
//1.1 授权服务发现
var disco=DiscoveryClient.GetAsync("http://localhost:4000").Result;
if (disco.IsError)
{
Console.WriteLine(disco.Error);
Console.ReadLine();
return;
}
//1.2 获取token
#region ClientCredential
//var tokenClient = new TokenClient
// (
// //授权 获取token 节点
// disco.TokenEndpoint,
// //ClientId
// "App1",
// //ClientSecret
// "Secret");
//var tokenResponse = tokenClient.RequestClientCredentialsAsync().Result;
//if (tokenResponse.IsError)
//{
// Console.WriteLine(tokenResponse.Error);
// return;
//}
#endregion
var tokenClient = new TokenClient
(
//授权 获取token 节点
disco.TokenEndpoint,
//ClientId
"WebMVC1",
//ClientSecret
"WebMVCSecret");
var tokenResponse = tokenClient.RequestResourceOwnerPasswordAsync(
//测试用户名
"WebMVC_Main",
//测试用户面膜
"WeMVC_Pwd")
.Result;
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
Console.WriteLine(tokenResponse.Json);
//1.3 调用API
HttpClient c = new HttpClient();
//设置授权信息
c.SetBearerToken(tokenResponse.AccessToken);
var jsonRe = c.GetAsync("http://localhost:4001/api/values").Result;
Console.WriteLine(jsonRe.Content.ReadAsStringAsync().Result);
Console.ReadLine();
}
}
}
参考文档:https://identityserver4.readthedocs.io/en/latest/quickstarts/2_resource_owner_passwords.html
网友评论