使用 OWIN 和 IIS 主机在 Web Api 操作方法中生成访问令牌

Generate Access Token In Web Api action method using OWIN and IIS host

我正在尝试根据以下代码在 Web Api 操作方法中生成令牌:

private JObject GeneratePaymentTokenResponse(string email, bool rememberMe)
    {
        //var tokenExpiration = rememberMe ? TimeSpan.FromDays(14) : TimeSpan.FromMinutes(30);

        var tokenExpiration = rememberMe ? TimeSpan.FromMinutes(30) : TimeSpan.FromMinutes(5);

        ClaimsIdentity identity = new ClaimsIdentity("CustomType", ClaimTypes.Email, ClaimTypes.Role);

        identity.AddClaim(new Claim(ClaimTypes.Email, email));

        var props = new AuthenticationProperties()
        {
            IssuedUtc = DateTime.UtcNow,
            ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration)
        };

        var ticket = new AuthenticationTicket(identity, props);

        var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

        JObject tokenResponse = new JObject(
                                    new JProperty("email", email),
                                    new JProperty("customToken", accessToken),
                                    new JProperty("expiresIn", tokenExpiration.TotalSeconds),
                                    new JProperty("issuedUtc", ticket.Properties.IssuedUtc),
                                    new JProperty("expiresUtc", ticket.Properties.ExpiresUtc)
    );

        return tokenResponse;
    }

OAuthBeaerOptions 对象来自 Startup class,如下所示:

public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }

OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
// Token Consumption (Resource Server)
app.UseOAuthBearerAuthentication(OAuthBearerOptions);

现在当我尝试传递一个有效的访问令牌时但已经过期并调用AccessTokenFormat.Unprotect作为下面的代码

 Microsoft.Owin.Security.AuthenticationTicket ticket = Startup.OAuthBearerOptions.AccessTokenFormat.Unprotect(paymentToken);

        if ((ticket == null) || (!ticket.Identity.IsAuthenticated))
        {
            actionContext.Response = CreateForbiddenResponse(actionContext);
            return Task.FromResult<object>(null);
        }

我收到了一张有效的票,ticket.Identity.IsAuthenticated 的值为 true 即使该令牌已过期。

目前我正在使用 Microsoft.Owin.Security 程序集

的最新版本 (3.0.1)

如果能提供有关如何设置此令牌到期日期的任何线索,我将不胜感激?

I'm receiving a valid ticket and the value of ticket.Identity.IsAuthenticated is true even that token is expired.

这完全是故意的:Unprotect 将 return 一张有效 ClaimsIdentity 的票,即使它已过期。由于 ClaimsIdentity.IsAuthenticated 仅确保 ClaimsIdentity.AuthenticationType 属性 不为空,因此这不是确保票证未过期的可靠方法。

实际上,由您来确定票证是否仍然有效,并且 return 必要时出错(这正是承载中间件在接收访问令牌时在内部所做的事情:https://github.com/jchannon/katanaproject/blob/master/src/Microsoft.Owin.Security.OAuth/OAuthBearerAuthenticationHandler.cs#L68-L73 )

if (ticket.Properties.ExpiresUtc.HasValue &&
    ticket.Properties.ExpiresUtc.Value < DateTimeOffset.Now)
{
    return Task.FromResult<object>(null);
}