Reputation: 159
I'm developing an OAuth based Web API application. How do I set the header as token I received from OAuth request by using authentication filter?
Reference link: Setting Authorization Header of HttpClient
I'm trying to check all type of methods but it's not working for me:
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
context.Request.Headers.Add("Bearer", "Your Oauth token");
My API call source code is:
[BasicAuthenticator]
[HttpGet]
[Authorize]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
and I'm getting the response:
{"Message":"Authorization has been denied for this request."}
My token generated code is as below:
public class BasicAuthenticator : Attribute, IAuthenticationFilter
{
public bool AllowMultiple { get; set; }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
var req = context.Request;
var reqHeader = context.Request.Headers;
if (!reqHeader.Contains("Authorization"))
{
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>( "grant_type", "password" ),
new KeyValuePair<string, string>( "username", "xxxx" ),
new KeyValuePair<string, string> ( "Password", "xxxx" )
};
var content = new FormUrlEncodedContent(pairs);
var client1 = new HttpClient();
var response = client1.PostAsync("http://localhost:56672/" + "Token", content).Result;
var responseBody = response.Content.ReadAsStringAsync();
var obj = JObject.Parse(responseBody.Result);
var tokenVal = (string)obj["access_token"];
client1.DefaultRequestHeaders.Clear();
client1.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenVal);
}
return Task.FromResult(0);
}
}
Upvotes: 0
Views: 1436
Reputation: 36
You need to define the Active auth scheme on your API. Try replacing [Authorize]
with [Authorize(ActiveAuthenticationSchemes = "Bearer")]
.
Upvotes: 0