OAuth Bearer Access Token sliding expiration

痴心易碎 提交于 2019-12-03 08:17:26

WARNING! Here is the solution that NO ONE SHOULD USE if you're not 100% sure that your application guarantees (which is impossible) that Access Token can not be compomised (for instance, XSS vulnerability allows to steal Access Token). In this solution once Access Token leaked it can be used to indefinitely prolong the access. OAuth Refresh Tokens solve exactly this problem, limiting access in case of compromising Access Token with very short amount of time, usually about 15 minutes.

[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)
        };
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!