0

I have an API on a MVC website I have created using token based authentication. This works great on one of my applications, but on another I am getting "Authorization has been denied for this request.".

I am getting the token just fine, but on making a call I get the above error.

Here is a test I have created.

class TestApi
{
    private const string baseAddress = "http://localhost:50485";

    private const string baseApiAddress = baseAddress + "/api/DojoDbApi";
    async Task<string> GetToken(string userName, string password)
    {
        var keyValues = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("username", userName),
            new KeyValuePair<string, string>("password", password),
            new KeyValuePair<string, string>("grant_type", "password")
        };
        var request = new HttpRequestMessage(HttpMethod.Post, "/oauth/token") { Content = new FormUrlEncodedContent(keyValues) };
        var client = new HttpClient { MaxResponseContentBufferSize = 256000, BaseAddress = new Uri(baseAddress) };

        var response = await client.SendAsync(request).ConfigureAwait(false);
        var content = await response.Content.ReadAsStringAsync();
        JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(content);
        var accessToken = jwtDynamic.Value<string>("access_token");
        Debug.WriteLine(accessToken);

        return accessToken;
    }
    public async Task<string> GetHello(string userName, string password)
    {


        var accessToken = await GetToken(userName, password);
        var client = new HttpClient { MaxResponseContentBufferSize = 256000, BaseAddress = new Uri(baseApiAddress) };
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            // Add the Authorization header with the AccessToken.
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var response = await client.GetAsync(new Uri(baseApiAddress + "/Hello"));
            var s = await response.Content.ReadAsStringAsync();
            Debug.WriteLine(s);
            return s;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(@"              ERROR {0}", ex.Message);
            return ex.Message;
        }
    }

}

What really confuses me is I can access the API quite happily using a Delphi application.

Dave Craggs
  • 27
  • 1
  • 6

1 Answers1

0

Have been discussing this with other developers (in ChesterDevs meetup).

This is something to do with cookies.

If you append ?AspxAutoDetectCookieSupport=1 yo the call it works.

If you change cookieless in web config to "UseCookies" it then works normally.

How to remove AspxAutoDetectCookieSupport=1

Dave Craggs
  • 27
  • 1
  • 6