1-新建.net core控制台应用程序
E:\coding\netcore\IdentityServerSample>dotnet new console --name ThridPartDemo
2-使用nuget工具安装 IdentityModel
3-编写API调用,说明http://localhost:5000是授权服务器, 5001是网站服务器客户端,即提供资源端
class Program
{
static void Main(string[] args)
{
var discovery = DiscoveryClient.GetAsync("http://localhost:5000").Result;
if(discovery.IsError){
Console.WriteLine(discovery.Error);
}
Console.WriteLine(discovery.TokenEndpoint);
TokenClient tokenClient = new TokenClient(discovery.TokenEndpoint,"client","secret");
var tokenResponse = tokenClient.RequestClientCredentialsAsync("api").Result;
if(tokenResponse.IsError){
Console.WriteLine($"tokenResponse Error: {tokenResponse.Error}");
}else{
Console.WriteLine(tokenResponse.Json);
} HttpClient httpClient = new HttpClient();
httpClient.SetBearerToken(tokenResponse.AccessToken);
var response = httpClient.GetAsync("http://localhost:5001/api/values").Result; if(response.IsSuccessStatusCode){
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
} Console.ReadLine();
}
}
使用dotnet run运行后,结果如下