最近同事用iOS App调用Open API时遇到一个问题:在access token过期后,用refresh token刷新access token时,服务器响应"invalid_grant"错误;而在access token没有过期的情况下,能正常刷新access token。
先查看了一下OAuth规范中的“Refreshing an Expired Access Token”流程图,以确认客户端的操作流程有没有问题。
问题发生在上图中的(G)操作步骤。iOS App就是按上图的流程进行操作的——在调用Open API时,如果服务器响应access token无效,就用refresh token刷新access token,客户端的操作流程一点问题没有。
于是将问题锁定在服务端。打点写日志,发现refresh token刷新access token时服务端先调用了IAuthenticationTokenProvider.ReceiveAsync(),然后调用了IOAuthAuthorizationServerProvider.GrantRefreshToken()方法。对应于我们的实现就是CNBlogsRefreshTokenProvider.ReceiveAsync()与CNBlogsAuthorizationServerProvider.GrantRefreshToken()。
查看ReceiveAsync()方法的实现代码:
public override async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
var refreshToken = await _refreshTokenService.Get(context.Token);
if (refreshToken != null)
{
context.DeserializeTicket(refreshToken.ProtectedTicket); await _refreshTokenService.Remove(context.Token);
}
}
从上面的代码可以得知,用refresh token刷新access token,实际就是将存储在数据库中的ProtectedTicket反序列为包含access token的ticket,然后根据这个ticket生成access token返回给客户端。而refreshToken.ProtectedTicket是在生成refresh token时由包含access token的ticket序列化生成的,refresh token无法刷新access token,问题很可能就出在它身上。
于是查看生成refresh token部分的代码——CNBlogsRefreshTokenProvider(继承自AuthenticationTokenProvider)的CreateAsync()方法:
var refreshToken = new RefreshToken()
{
Id = refreshTokenId,
ClientId = new Guid(clientId),
UserName = context.Ticket.Identity.Name
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.AddSeconds(Convert.ToDouble(refreshTokenLifeTime)),
ProtectedTicket = context.SerializeTicket()
};
context.Ticket.Properties.IssuedUtc = refreshToken.IssuedUtc;
context.Ticket.Properties.ExpiresUtc = refreshToken.ExpiresUtc;
当时一看代码,立马恍然大悟。应该是先设置IssuedUtc与ExpiresUtc,然后再SerializeTicket();实际被写成了先SerializeTicket(),后设置IssuedUtc与ExpiresUtc。结果造成refreshToken.ProtectedTicket的过期时间不正确,从而无法刷新access token。
解决方法很简单,只需将context.SerializeTicket()移至设置Ticket的IssuedUtc与ExpiresUtc的代码之后:
var refreshToken = new RefreshToken()
{
Id = refreshTokenId,
ClientId = new Guid(clientId),
UserName = context.Ticket.Identity.Name
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.AddSeconds(Convert.ToDouble(refreshTokenLifeTime)),
};
context.Ticket.Properties.IssuedUtc = refreshToken.IssuedUtc;
context.Ticket.Properties.ExpiresUtc = refreshToken.ExpiresUtc;
refreshToken.ProtectedTicket = context.SerializeTicket();
|