locked
Call WebApi RRS feed

  • Question

  • User-2017229834 posted

    How to call token based web API for authentication?

    Thursday, October 10, 2019 7:21 AM

Answers

  • User-2017229834 posted

    Thank you for your replay..I get that.

    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Net.Http.Formatting;
    
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string baseAddress = "http://localhost:4312";
                Token token = new Token();
                using (var client = new HttpClient())
                {
                    var form = new Dictionary<string, string>
                   {
                       {"grant_type", "password"},
                       {"username", "admin"},
                       {"password", "admin"},
                   };
                    var tokenResponse = client.PostAsync(baseAddress + "/token", new FormUrlEncodedContent(form)).Result;
                    //var token = tokenResponse.Content.ReadAsStringAsync().Result;
                    token = tokenResponse.Content.ReadAsAsync<Token>(new[] { new JsonMediaTypeFormatter() }).Result;
                    if (string.IsNullOrEmpty(token.Error))
                    {
                        Console.WriteLine("Token issued is: {0}", token.AccessToken);
                        Console.WriteLine("Token Type: {0}", token.TokenType);
                    }
                    else
                    {
                        Console.WriteLine("Error : {0}", token.Error);
                    }
                }
    
                // Next Request 
                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.BaseAddress = new Uri(baseAddress);
                    //httpClient1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token.AccessToken);
                    httpClient.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", token.AccessToken));
                    HttpResponseMessage response = httpClient.GetAsync("api/TestMethod").Result;
                    if (response.IsSuccessStatusCode)
                    {
                        System.Console.WriteLine("Success");
                    }
                    string message = response.Content.ReadAsStringAsync().Result;
                    System.Console.WriteLine("URL responese : " + message);
                }
    
                Console.Read();
            }
        }
    }
    

    Regards,

    Vijay Kumar

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 10, 2019 11:47 AM

All replies

  • User61956409 posted

    Hi Vijay,

    How to call token based web API for authentication?

    Normally, you need to make request to get/acquire token first, then make request and pass the token that you got in request header to access resources.

    With Regards,

    Fei Han

    Thursday, October 10, 2019 8:15 AM
  • User-2017229834 posted

    Thank you for your replay..I get that.

    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Net.Http.Formatting;
    
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string baseAddress = "http://localhost:4312";
                Token token = new Token();
                using (var client = new HttpClient())
                {
                    var form = new Dictionary<string, string>
                   {
                       {"grant_type", "password"},
                       {"username", "admin"},
                       {"password", "admin"},
                   };
                    var tokenResponse = client.PostAsync(baseAddress + "/token", new FormUrlEncodedContent(form)).Result;
                    //var token = tokenResponse.Content.ReadAsStringAsync().Result;
                    token = tokenResponse.Content.ReadAsAsync<Token>(new[] { new JsonMediaTypeFormatter() }).Result;
                    if (string.IsNullOrEmpty(token.Error))
                    {
                        Console.WriteLine("Token issued is: {0}", token.AccessToken);
                        Console.WriteLine("Token Type: {0}", token.TokenType);
                    }
                    else
                    {
                        Console.WriteLine("Error : {0}", token.Error);
                    }
                }
    
                // Next Request 
                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.BaseAddress = new Uri(baseAddress);
                    //httpClient1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token.AccessToken);
                    httpClient.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", token.AccessToken));
                    HttpResponseMessage response = httpClient.GetAsync("api/TestMethod").Result;
                    if (response.IsSuccessStatusCode)
                    {
                        System.Console.WriteLine("Success");
                    }
                    string message = response.Content.ReadAsStringAsync().Result;
                    System.Console.WriteLine("URL responese : " + message);
                }
    
                Console.Read();
            }
        }
    }
    

    Regards,

    Vijay Kumar

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 10, 2019 11:47 AM
  • User-2017229834 posted

    And Below is token Class

    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; }
            [JsonProperty("error")]
            public string Error { get; set; }
        }

    Thursday, October 10, 2019 11:54 AM