如何自定义OpenIddict产生的授权错误?

时间:2018-11-12 12:04:20

标签: asp.net-core openiddict

我在.NET Core 2 API中使用OpenIddict进行身份验证。客户端我依靠任何API错误来遵循自定义方案。但是,例如刷新令牌已过时,我似乎无法找出如何自定义发送回的错误。

从未达到 / token 端点,因此错误不在“我的控制”之下。

请求的结果是状态码400,带有以下JSON:

{"error":"invalid_grant","error_description":"The specified refresh token is no longer valid."}

我尝试使用自定义中间件来捕获所有状态代码(它确实这样做),但结果返回的是之前,我的自定义中间件的执行已完成。

如何正确自定义错误或拦截以进行更改?谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用OpenIddict的事件模型自定义令牌响应有效负载,然后再将它们写入响应流。这是一个示例:

MyApplyTokenResponseHandler.cs

public class MyApplyTokenResponseHandler : IOpenIddictServerEventHandler<OpenIddictServerEvents.ApplyTokenResponse>
{
    public Task<OpenIddictServerEventState> HandleAsync(OpenIddictServerEvents.ApplyTokenResponse notification)
    {
        var response = notification.Context.Response;
        if (string.Equals(response.Error, OpenIddictConstants.Errors.InvalidGrant, StringComparison.Ordinal) &&
           !string.IsNullOrEmpty(response.ErrorDescription))
        {
            response.ErrorDescription = "Your customized error";
        }

        return Task.FromResult(OpenIddictServerEventState.Unhandled);
    }
}

Startup.cs

services.AddOpenIddict()
    .AddCore(options =>
    {
        // ...
    })

    .AddServer(options =>
    {
        // ...
        options.AddEventHandler<MyApplyTokenResponseHandler>();
    })

    .AddValidation();

答案 1 :(得分:1)

  

/ token端点从未到达,因此错误不在“我的控制”之下。

实际上,已达到/token,并且grant_type的参数等于refresh_token但是刷新令牌过期时的拒绝逻辑未被我们处理。 这是源代码中的某种“硬编码”

if (token == null)
{
    context.Reject(
        error: OpenIddictConstants.Errors.InvalidGrant,
        description: context.Request.IsAuthorizationCodeGrantType() ?
            "The specified authorization code is no longer valid." :
            "The specified refresh token is no longer valid.");

    return;
}

if (options.UseRollingTokens || context.Request.IsAuthorizationCodeGrantType())
{
    if (!await TryRedeemTokenAsync(token))
    {
        context.Reject(
            error: OpenIddictConstants.Errors.InvalidGrant,
            description: context.Request.IsAuthorizationCodeGrantType() ?
                "The specified authorization code is no longer valid." :
                "The specified refresh token is no longer valid.");

        return;
    }
}

这里的context.Reject来自程序集AspNet.Security.OpenIdConnect.Server

有关更多详细信息,请参见source code on GitHub

  

我尝试使用自定义中间件来捕获所有状态代码(它确实这样做),但是在我的自定义中间件执行完成之前会返回结果。

我已经尝试过,并且我很确定我们可以使用定制的中间件来捕获所有状态代码。关键点是在next()调用之后检测状态代码:

app.Use(async(context , next )=>{

    // passby all other end points
    if(! context.Request.Path.StartsWithSegments("/connect/token")){
        await next();
        return;
    }

    // since we might want to detect the Response.Body, I add some stream here .
    // if you only want to detect the status code , there's no need to use these streams
    Stream originalStream = context.Response.Body;
    var hijackedStream = new MemoryStream();
    context.Response.Body = hijackedStream;
    hijackedStream.Seek(0,SeekOrigin.Begin);

    await next();

    // if status code not 400 , pass by
    if(context.Response.StatusCode != 400){
        await CopyStreamToResponseBody(context,hijackedStream,originalStream);
        return;
    }

    // read and custom the stream 
    hijackedStream.Seek(0,SeekOrigin.Begin);
    using (StreamReader sr = new StreamReader(hijackedStream))
    {
        var raw= sr.ReadToEnd();
        if(raw.Contains("The specified refresh token is no longer valid.")){
            // custom your own response
            context.Response.StatusCode = 401;
            // ...
            //context.Response.Body = ... /
        }else{
            await CopyStreamToResponseBody(context,hijackedStream,originalStream);
        }
    }
});

// helper to make the copy easy
private async Task CopyStreamToResponseBody(HttpContext context,Stream newStream, Stream originalStream){

    newStream.Seek(0,SeekOrigin.Begin);
    await newStream.CopyToAsync(originalStream);
    context.Response.ContentLength =originalStream.Length;
    context.Response.Body = originalStream;
}