更改 OWIN .expiration 和 .issued 日期的 DateTime 格式

Change DateTime format of OWIN .expiration and .issued dates

我在创建 .NET Web API 入门模板时使用了 "Individual User Accounts" 身份验证选项(如所述 here). The token is being correctly generated, however the ".issued" and ".expires" property are in a non-ISO date format. How do I format them with DateTime.UtcNow.ToString("o") 所以它符合 ISO 8601 标准?

{
  "access_token": "xxx",
  "token_type": "bearer",
  "expires_in": 1199,
  "userName": "foo@bar.com",
  "Id": "55ab2c33-6c44-4181-a24f-2b1ce044d981",
  ".issued": "Thu, 13 Aug 2015 23:08:11 GMT",
  ".expires": "Thu, 13 Aug 2015 23:28:11 GMT"
}

该模板使用自定义 OAuthAuthorizationServerProvider 并提供一个钩子来向传出令牌添加额外的属性('Id' 和 'userName' 是我的道具),但我没有查看更改现有属性的任何方法。

我确实注意到在 TokenEndpoint 的覆盖中,我得到一个 OAuthTokenEndpointContext,它有一个带有 .issued 和 .expired 键的属性字典。但是,尝试更改这些值没有任何效果。

在此先致谢。

AuthenticationProperties class 在 Microsoft.Owin.dll 的 Microsoft.Owin.Security 命名空间中定义。

IssuedUtc 属性 的 setter 做了以下事情(对于 ExpiresUtc 是类似的):

this._dictionary[".issued"] = value.Value.ToString("r", (IFormatProvider) CultureInfo.InvariantCulture);

如您所见,当设置 IssuedUtc 时,字典的 .issued 字段也被设置,并且 "r" format.

您可以尝试在TokenEndPoint方法中进行如下操作:

foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
    if (property.Key == ".issued")
    {
        context.AdditionalResponseParameters.Add(property.Key, context.Properties.IssuedUtc.Value.ToString("o", (IFormatProvider) CultureInfo.InvariantCulture));
    }
    else if (property.Key == ".expires")
    {
        context.AdditionalResponseParameters.Add(property.Key, context.Properties.ExpiresUtc.Value.ToString("o", (IFormatProvider) CultureInfo.InvariantCulture));
    }
    else
    {
        context.AdditionalResponseParameters.Add(property.Key, property.Value);
    }
}

希望对您有所帮助。