GetToken From c# codebehind using HttpClient

        public Token GetToken(string _baseUrl, string userName,string password)
        {
            var client = new HttpClient();

            var authorizationHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes("xyz:secretKey"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authorizationHeader);

            var form = new Dictionary<string, string>
               {
                   {"grant_type", "password"},
                   {"username", userName},
                   {"password",password},
               };

            var tokenResponse = client.PostAsync(_baseUrl + "token", new FormUrlEncodedContent(form)).Result;
            string state = tokenResponse.Content.ReadAsStringAsync().Result;

            var token = JsonConvert.DeserializeObject<Token>(state);
            return token;
        }


   public class Token
   {
        [JsonProperty("access_token")]
        public string AccessToken { get; set; }

        [JsonProperty("token_type")]
        public string TokenType { get; set; }

        [JsonProperty("expires_in")]
        public int ExpiresIn { get; set; }

        [JsonProperty("refresh_token")]
        public string RefreshToken { get; set; }
    }

Comments

Popular posts from this blog

Provision AWS EC2 Instance and RDS with Terraform, and Deploy Spring Boot App to EC2 Instance via GitHub Action Pipeline

JQuery UI Autocomplete, custom HTML structure for result?

Easy Ui Jquery easyui-textbox change onChange event