//从元数据中发现终结点,查找IdentityServer(5000端口) var disco = DiscoveryClient.GetAsync("http://localhost:5000").Result; //向IdentityServer请求令牌 var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret"); var tokenResponse = tokenClient.RequestClientCredentialsAsync("api1").Result; if (tokenResponse.IsError) { Console.WriteLine(tokenResponse.Error); return; } Console.WriteLine(tokenResponse.Json); //访问Api var client = new HttpClient(); //把令牌添加进请求 client.SetBearerToken(tokenResponse.AccessToken); var response = client.GetAsync("http://localhost:5001/identity").Result; if (!response.IsSuccessStatusCode) { Console.WriteLine(response.StatusCode); } else { var content = response.Content.ReadAsStringAsync().Result; Console.WriteLine(content); } Console.Read();
var client = new HttpClient(); string key = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImIwODUyMWFiNWE0ZTFiMmZiYjBiY2FkZGRkMTUxNjZjIiwidHlwIjoiSldUIn0.eyJuYmYiOjE1NjA4NDM5MTYsImV4cCI6MTU2MDg0NzUxNiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJhcGkxIl0sImNsaWVudF9pZCI6ImNsaWVudCIsInNjb3BlIjpbImFwaTEiXX0.YPP2xcNTDuOXROHFQ2mkSLH35m6uBJmKYXgrRJDbrSsZ9PySjRXnK0DOBzqYMZfs89FD7ik5RmQeVPjzheeFqEzvYdHIV-8veXffUSToIOvf_5BB33Qdkk6XqziyQBNlb6hJQeQOC6QbORdf6J6IvdgzWUiVfKaZPnb-BCgy2lcM5eA5o97If4amaEc4trT9T4ifL7WJ8rLOxNMgDsbGzqsu2WjZeekFQdtnP4bP2GHGzYGxN0MKKCF8LcQ1VWwrkuYlYtfDIPYxzP72AOxtMEDetJHTiFSLn9D39f5_LY-8jY0nmCwG5TClor3Tv4P3PNpLih1YEFG4SWrjZPkQoA"; HttpWebRequest request = WebRequest.Create("http://localhost:5001/identity") as HttpWebRequest; request.Method = "GET"; var headers = request.Headers; headers["Authorization"] = "Bearer " + key; //传递进去认证Token request.Headers = headers; HttpWebResponse response; try { //获得响应流 response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { response = null; } Stream s = response.GetResponseStream(); StringBuilder str = new StringBuilder(); if (response.StatusCode == HttpStatusCode.OK) { Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); StreamReader readStream = new StreamReader(s, encode); Char[] read = new Char[256]; int count = readStream.Read(read, 0, 256); while (count > 0) { str.Append(new String(read, 0, count)); count = readStream.Read(read, 0, 256); } s.Close(); readStream.Close(); } Console.WriteLine(str); Console.Read();