如何使用身份验证过滤器将标头设置为令牌请求OAuth?

时间:2017-04-28 14:39:23

标签: c# asp.net-web-api oauth

我正在开发基于OAuth的Web API应用程序。 如何使用身份验证过滤器将标头设置为从OAuth请求收到的标记?

参考链接: Setting Authorization Header of HttpClient

我正在尝试检查所有类型的方法,但它对我不起作用:

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");

context.Request.Headers.Add("Bearer", "Your Oauth token");

我的API调用源代码是:

[BasicAuthenticator]
[HttpGet]   
[Authorize]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

我收到了回复:

  

{“消息”:“此请求已拒绝授权。”}

我的令牌生成代码如下:

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);
    }
}

1 个答案:

答案 0 :(得分:0)

您需要在API上定义Active auth方案。尝试将[Authorize]替换为[Authorize(ActiveAuthenticationSchemes = "Bearer")]