警告!如果您不能 100% 确定您的应用程序保证(这是不可能的)访问令牌不能被组合(例如,XSS 漏洞允许窃取访问令牌),那么这是任何人都不应使用的解决方案。在此解决方案中,一旦访问令牌泄露,它可用于无限期延长访问权限。OAuth Refresh Tokens 正好解决了这个问题,在很短的时间内(通常是 15 分钟左右)破坏访问令牌的情况下限制访问。
[Authorize]
public class RefreshTokenController : ApiController
{
[HttpGet]
public HttpResponseMessage ReissueToken()
{
// just use old identity
var identity = ((ClaimsPrincipal)User).Identity as ClaimsIdentity;
var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
DateTimeOffset currentUtc = new SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.AddMinutes(30);
string token = Startup.OAuthBearerAuthOptions.AccessTokenFormat.Protect(ticket);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<object>(new
{
accessToken = token,
expiresIn = (int)((ticket.Properties.ExpiresUtc.Value - ticket.Properties.IssuedUtc.Value).TotalSeconds),
}, Configuration.Formatters.JsonFormatter)
};
}
}