1、新建一个ClientCredentialConsole的控制台应用程序
2、使用第三方客户端调用模式的步骤
1、引入IdentityModel 2、测试连接授权服务器 3、通过client和secret从授权服务器中获取token 4、在bearer中添加token调用api
class Program { static void Main(string[] args) { var client = new HttpClient(); var disco = client.GetDiscoveryDocumentAsync("http://localhost:5000").Result; if (disco.IsError) { Console.WriteLine(disco.Error); return; } var tokenResponse = client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = disco.TokenEndpoint, ClientId = "myself", ClientSecret = "secret", Scope = "api1scope" }).Result; if (tokenResponse.IsError) { Console.WriteLine(tokenResponse.Error); return; } Console.WriteLine(tokenResponse.Json); client.SetBearerToken(tokenResponse.AccessToken); var response = client.GetAsync("http://localhost:5001/WeatherForecast").Result; if (!response.IsSuccessStatusCode) { Console.WriteLine(response.StatusCode);
return;
}
else {
var content = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(JArray.Parse(content.ToString()));
}
}
}
3、将授权和api两个项目开启,再开启console
以上就是token 和api请求的过程。