AuthentificationExample/ConsoleApp1/Program.cs
2024-10-24 11:49:21 +05:00

38 lines
1.2 KiB
C#

// See https://aka.ms/new-console-template for more information
using RestSharp;
using System.Text.Json;
var keyCloackHost = "localhost:8080";
var webApiHost = "localhost:44358";
var restClient = new RestClient();
var request = new RestRequest($"http://{keyCloackHost}/realms/TestRealm/protocol/openid-connect/token", Method.Post);
//параметры для body
request.AddParameter("username", "myuser");
request.AddParameter("password", 123456);
request.AddParameter("client_id", "public-client");
request.AddParameter("grant_type", "password");
var keyCloackResponse = await restClient.PostAsync(request);
if (keyCloackResponse.IsSuccessful)
{
var token = JsonSerializer.Deserialize<JwtToken>(keyCloackResponse.Content);
var access_token = token.AccessToken;
var webApiRequest = new RestRequest($"https://{webApiHost}/WeatherForecast", Method. Get);
webApiRequest.AddHeader("Authorization", "Bearer " + access_token);
var webApiResponse = await restClient.GetAsync(webApiRequest);
if (webApiResponse.IsSuccessful) {
Console.WriteLine(webApiResponse.Content);
}
else
{
Console.WriteLine(webApiResponse.StatusDescription);
}
}
else
{
Console.WriteLine(keyCloackResponse.StatusDescription);
}