[OAuth2授权服务器]刷新令牌的过期时间需要与访问令牌不同吗?

[OAuth2 authorization server]refresh token's expire time need different with access token?

我正在通过这个 tutorial 学习 OAuth2,然后我发现刷新令牌的过期时间与访问令牌相同,这是正确的吗?

一般来说,这没有多大意义:refresh_token 的存在是为了让客户在当前的 access_token 过期时获得一个新的 access_token。如果到那时 refresh_token 也已过期,则客户无法对其进行任何操作,因此它是无用的。

有一个(或多或少)边缘情况,这在其中很有用:当资源服务器在过期前主动拒绝 access_token 时,客户端现在可以返回到授权服务器以获取新 access_token.

没错:内置于 OWIN/Katana 中的 OAuth2 授权服务器颁发的刷新令牌始终与访问令牌 具有相同的到期日期;即使您在调用 IOwinContext.Authentication.SignIn(identity, properties)

时在 AuthenticationProperties 中指定了明确的 ExpiresUtc 属性

https://github.com/yreynhout/katana-clone/blob/master/src/Microsoft.Owin.Security.OAuth/OAuthAuthorizationServerHandler.cs#L333

由于@Hans 提到的原因,这并不是很方便,但您可以在 AuthenticationTokenProvider.CreateAsync 中覆盖此行为(您用于 OAuthAuthorizationServerOptions.RefreshTokenProvider 的 class):

只需将 context.Ticket.Properties.ExpiresUtc 设置为您选择的到期日期,刷新令牌将发出不同的到期日期:

public class RefreshTokenProvider : AuthenticationTokenProvider {
    public override void Create(AuthenticationTokenCreateContext context) {
        context.Ticket.Properties.ExpiresUtc = // set the appropriate expiration date.

        context.SetToken(context.SerializeTicket());
    }
}

您还可以查看 AspNet.Security.OpenIdConnect.Server,它是 OWIN/Katana 提供的 OAuth2 授权服务器的一个分支,具有本机 RefreshTokenLifetimehttps://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/tree/dev

app.UseOpenIdConnectServer(options => {
    // Essential properties omitted for brevity.
    // See https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/tree/dev/samples/Mvc for more information.

    // RefreshTokenLifetime allows you to define a lifetime specific to refresh tokens,
    // which is totally independent of the lifetime used for access tokens.
    options.RefreshTokenLifetime = TimeSpan.FromDays(14);
});

如果需要帮助,请随时联系我。