locked
WebAPI individual account - register and authent works, get fails RRS feed

  • Question

  • User-1799713556 posted

    Hi, is there any chance someone can take a quick look at this (bad, I know) code and tell me where I'm going wrong please? It's not production code, it's playtime, and I know I'm doing something very, very stupid.

    I'm connecting to WebAPI with Individual Account authentication from a console app, registering, logging in, then trying a Get - which fails with a 401, unauthorised response. If I remove the [Authorize] attribute from the Values controller, it works just fine.

    My code is:

            public static void WebApiAuthentThenGet()
            {
                string baseAddr = "http://localhost:58991/";
                string username = "a2@user.com";
                string password = "PASS_word1";
    
                Console.WriteLine("Create request");
                CookieContainer cookies = new CookieContainer();
                HttpClientHandler handler = new HttpClientHandler();
                handler.CookieContainer = cookies;
                var client = new HttpClient(handler);
                client.BaseAddress = new Uri(baseAddr);
    
                Console.WriteLine("Register");
                var register = client.PostAsync("api/account/register",
                    new FormUrlEncodedContent(
                        new Dictionary<string, string> { { "Email", username }, { "Password", password }, { "ConfirmPassword", password } }
                    )).Result;
                register.EnsureSuccessStatusCode();
    
                Console.WriteLine("Login");
                var login = client.PostAsync("/token",
                    new FormUrlEncodedContent(
                        new Dictionary<string, string> { { "grant_type", "password" }, { "username", username }, { "password", password } }
                    )).Result;
                login.EnsureSuccessStatusCode();
    
                Console.WriteLine("Display cookie");
                IEnumerable<Cookie> responseCookies = cookies.GetCookies(client.BaseAddress).Cast<Cookie>();
                foreach (Cookie cookie in responseCookies)
                {
                    Console.WriteLine(cookie.Name + ": " + cookie.Value);
                }
    
                Console.WriteLine("Get authorized data");
                var getall = client.GetAsync("api/values").Result;
                getall.EnsureSuccessStatusCode();
            }
    

    When I look at the get request in Fiddler, I can see that no cookie is attached. Does anyone know why that happens please? I thought the CookieContainer would attach the cookie from the authent step? Also, if there are any other howlers / mistakes in the code (I'm learning here!) please just say.

    Thanks a lot, HT.

    Tuesday, May 26, 2015 9:39 AM

Answers

  • User-782957977 posted

    You will get Access Token as JSON object. Please delete your code using cookie and add following code
     var result = login.Content.ReadAsStringAsync().Result;
     // De-Serialize into a dictionary and return:
     Dictionary<string, string> tokenDictionary =
     JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
     string accessToken = tokenDictionary["access_token"];
    
    // Call Web Api using access Token
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
     var response = client.GetAsync("Api/values").Result;

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 26, 2015 11:53 PM

All replies

  • User-782957977 posted

    You will get Access Token as JSON object. Please delete your code using cookie and add following code
     var result = login.Content.ReadAsStringAsync().Result;
     // De-Serialize into a dictionary and return:
     Dictionary<string, string> tokenDictionary =
     JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
     string accessToken = tokenDictionary["access_token"];
    
    // Call Web Api using access Token
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
     var response = client.GetAsync("Api/values").Result;

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 26, 2015 11:53 PM
  • User-1799713556 posted

    Mate, that is fantastic, thanks very much. 

    I have just dumped out my CookieContainer cookie, and my access token and can see that they are different.

    I have marked your answer as the correct one (obviously, it's perfect, thanks). Just if you get the chance, do you know what the purpose of the CookieContainer cookie is please? I'm not setting it myself, I thought it was the auth cookie.

    Cheers, HT.

    Wednesday, May 27, 2015 12:48 AM
  • User-782957977 posted

    Asp.Net Web Api token based authentication  will not create any Auth cookie  and it includes Access token in response body.

    Wednesday, May 27, 2015 9:54 PM