hapi-auth-jwt2:将自定义属性添加到错误响应

hapi-auth-jwt2: Add custom attribute to error response

在 hapi-auth-jw2 中,是否可以在错误响应中添加一个属性,例如当令牌无效时。因为我需要向响应添加 code 属性,但是当我尝试向 errorFunc 中的错误添加属性时,它没有添加属性。

errorFunc: (err) => {
   err.code = 'token-invalid';
   return err;
}

我认为不可能将属性 code 直接添加到响应对象,因为库调用 Boom 到 return 错误。

然而,由于无效令牌可能会导致 401 Unauthorized,您可以根据 optional parameters to contain whatever custom attributes you want. Take a look at Boom's docs on this response for further information, here.

扩展回调 err
errorFunc: (err) => 
{
    err.message = 'foo bar'; // optional
    err.schema = 'error';
    err.attributes = {code: 'token-invalid'};

    return err;
}

这将产生类似于

的响应
"payload": {
    "statusCode": 401,
        "error": "Unauthorized",
        "message": "foo bar",
        "attributes": {
            "error": "foo bar",
            "code": 'invalid-token' // <---- your custom value
        }
},
"headers" {
    "WWW-Authenticate": "error code=\"token-invalid\", error=\"foo bar\""
}