无效或过期令牌返回错误

use*_*652 12 .net c# oauth oauth-2.0 owin

我正在尝试使用Owin实施OAuth承载认证.传递无效或过期的令牌时,默认实现是将其记录为警告,并且不要设置标识.但是,我希望在这种情况下拒绝整个请求并出现错误.但是我该怎么做呢?

在深入研究代码之后,我发现在提供的代码没有解析任何故障单时(如默认实现),OAuthBearerAuthenticationHandler它将使用回退机制解析令牌AuthenticationTokenProvider.当令牌无法解析为任何故障单或过期时,此处理程序将记录警告.

但我无法找到任何地方来插入我自己的逻辑,以便当令牌无效或过期时会发生什么.理论上我可以自己检查一下AuthenticationTokenProvider,但是我必须重新实现逻辑(=复制它)来创建和读取令牌.这似乎也不合适,因为这个类似乎只负责创建和解析令牌.我也没有看到插入我自己的实现OAuthBearerAuthenticationHandler的方法OAuthBearerAuthenticationMiddleware.

显然,我最好和最干净的镜头将是重新实现整个中间件,但这似乎也非常矫枉过正.

我有什么看法?我怎么会继续这个最好的?

编辑:

为了澄清.我知道,如果不设置身份,请求将在稍后的Web API中被401 Unauthorized拒绝.但我个人认为这是一种非常糟糕的风格,在没有任何通知的情况下默默地吞下一个错误的访问令牌.这样你就不会知道你的令牌是垃圾,你只是知道你没有被授权.

jle*_*eon 8

我有一个类似的问题,我认为答案是迟到但有人会来这里遇到类似的问题:

我使用这个nuget包进行验证身份验证,但我认为任何方法都可以提供帮助:https://www.nuget.org/packages/WebApi.AuthenticationFilter .您可以在此站点阅读其文档https://github.com/mbenford/WebApi-AuthenticationFilter

AuthenticationFilter.cs

public class AuthenticationFilter : AuthenticationFilterAttribute{
public override void OnAuthentication(HttpAuthenticationContext context)
{
    System.Net.Http.Formatting.MediaTypeFormatter jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter();
    var ci = context.Principal.Identity as ClaimsIdentity;

    //First of all we are going to check that the request has the required Authorization header. If not set the Error
    var authHeader = context.Request.Headers.Authorization;
    //Change "Bearer" for the needed schema
    if (authHeader == null || authHeader.Scheme != "Bearer")
    {
        context.ErrorResult = context.ErrorResult = new AuthenticationFailureResult("unauthorized", context.Request,
            new { Error = new { Code = 401, Message = "Request require authorization" } });
    }
    //If the token has expired the property "IsAuthenticated" would be False, then set the error
    else if (!ci.IsAuthenticated)
    {
        context.ErrorResult = new AuthenticationFailureResult("unauthorized", context.Request,
            new { Error = new { Code = 401, Message = "The Token has expired" } });
    }
}}
Run Code Online (Sandbox Code Playgroud)

AuthenticationFailureResult.cs

public class AuthenticationFailureResult : IHttpActionResult{
private object ResponseMessage;
public AuthenticationFailureResult(string reasonPhrase, HttpRequestMessage request, object responseMessage)
{
    ReasonPhrase = reasonPhrase;
    Request = request;
    ResponseMessage = responseMessage;
}

public string ReasonPhrase { get; private set; }

public HttpRequestMessage Request { get; private set; }

public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
    return Task.FromResult(Execute());
}

private HttpResponseMessage Execute()
{
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
    System.Net.Http.Formatting.MediaTypeFormatter jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter();
    response.Content = new System.Net.Http.ObjectContent<object>(ResponseMessage, jsonFormatter);
    response.RequestMessage = Request;
    response.ReasonPhrase = ReasonPhrase;
    return response;
}}
Run Code Online (Sandbox Code Playgroud)

回复示例:

{"Error":{"Code":401,"Message":"Request require authorization"}}

{"Error":{"Code":401,"Message":"The Token has expired"}}
Run Code Online (Sandbox Code Playgroud)

字体和灵感文档:

//github.com/mbenford/WebApi-AuthenticationFilter

//www.asp.net/web-api/overview/security/authentication-filters


Bro*_*len 0

如果身份验证失败(意味着令牌已过期),那么该层不会设置用户,正如您所说。由授权层(稍后)拒绝呼叫。因此,对于您的场景,您的 Web API 需要拒绝匿名调用者的访问。使用[Authorize]授权过滤器属性。

  • 我从来没有争论过,我知道身份验证和授权是两个不同的事情。但我只是想拒绝带有错误的 **无效** 身份验证尝试,而不是默默地吞下它们。如果我不能正确地做出反应,那么记录警告(就像实现所做的那样)也是毫无意义的。 (5认同)