从.NET中的HttpResponseMessage中提取和解析WWW-Authenticate头

时间:2017-08-04 23:18:56

标签: .net http azure-active-directory microsoft-graph

我正在使用Azure AD构建应用程序来调用Microsoft Graph。在某些需要提升访问权限的请求中,图表在我需要在后续请求中使用的claims标头内发出HTTP 403错误,并带有特殊的WWW-Authenticate参数。

在.NET中,如何提取API生成的WWW-Authenticate标头以响应HttpResponseMessage类中的Forbidden(HTTP 403)?

此外,解析此标头以提取某些数据的最佳方法是什么?例如,响应以逗号分隔,但在我需要的数据块中也包含逗号。

2 个答案:

答案 0 :(得分:1)

为了提取参数,您可以使用以下代码提取WWW-Authenticate标题:

HttpResponseMessage graphResponse = await httpClient.SendAsync(request);
graphResponse.Headers.WwwAuthenticate.ToString();

这将提供整个标题。要不提取声明参数,您可以通过WWW-Authenticate解析,标题,然后解析空格。 HTTP的RFC没有提供明确的指导,因此它基于单个服务。对于此特定错误,通过逗号和空格分割或通过查找claims是合适的。

答案 1 :(得分:0)

您可以在Headers属性response.Headers.WwwAuthenticate

中访问它

从那里你可以遍历价值观。该标准已在代码中处理。您只需要管理特定于系统的自定义详细信息。

if (response.StatusCode == System.Net.HttpStatusCode.Forbidden) {
    var wwwAuthenticate = response.Headers.WwwAuthenticate;
    foreach (var auth in wwwAuthenticate) {
        var scheme = auth.Scheme;
        var parameter = auth.Parameter;
        //Handle the data as needed
    }
}

AuthenticationHeaderValue.cs source code中为Parameter属性

引用评论
// We simplify parameters by just considering them one string. The caller is responsible for correctly parsing
// the string.
// The reason is that we can't determine the format of parameters. According to Errata 1959 in RFC 2617 
// parameters can be "token", "quoted-string", or "#auth-param" where "auth-param" is defined as 
// "token "=" ( token | quoted-string )". E.g. take the following BASIC example:
// Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
// Due to Base64 encoding we have two final "=". The value is neither a token nor a quoted-string, so it must
// be an auth-param according to the RFC definition. But that's also incorrect: auth-param means that we 
// consider the value before the first "=" as "name" and the final "=" as "value".