我有一个Web API 2应用程序,它使用Asp.Net Identity进行身份验证和授权。我还有一个自定义的消息处理程序来进行额外的自定义检查以完成身份验证(以及解析连接到多租户数据存储上的正确模式所需的一些API数据)。
这是我的消息处理程序的工作代码:
public class AuthenticationHeadersHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Headers.Contains("Authorization"))
{
// Authenticate
var auth = request.GetOwinContext().Authentication.AuthenticateAsync(OAuthDefaults.AuthenticationType);
// Get user ID from token
identityId = auth.Result.Identity.GetUserId();
// Please note, the oAuth token would have successfully authenticated by now
// ... Do some custom authentication and data gathering
if (failedCheck)
{
// If user fails checks, I would like to force Asp.Net Identity to
// return 401 not authorized here, or flag the request as not authorized
}
}
}
}
考虑到上面的代码,即使通过初始身份验证,如何将请求手动标记为未经授权?
答案 0 :(得分:1)
我认为这应该有效:
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Headers.Contains("Authorization"))
{
// Authenticate
var auth = request.GetOwinContext().Authentication.AuthenticateAsync(OAuthDefaults.AuthenticationType);
// Get user ID from token
identityId = auth.Result.Identity.GetUserId();
// Please note, the oAuth token would have successfully authenticated by now
// ... Do some custom authentication and data gathering
if (failedCheck)
{
// Return 401 not authorized here.
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
}
// If we got here send an HTTP status of 200
return new HttpResponsMessage(HttpStatusCode.OK);
}