OAuth Bearer Access Token sliding expiration

前端 未结 1 915
予麋鹿
予麋鹿 2021-02-10 05:07

Let\'s suppose that we\'re using OAuth Bearer tokens to secure our API. There is NuGet package with OWIN middleware that will do it for us: https://www.nuget.org/packages/Micros

1条回答
  •  有刺的猬
    2021-02-10 05:19

    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(new
                {
                    accessToken = token,
                    expiresIn = (int)((ticket.Properties.ExpiresUtc.Value - ticket.Properties.IssuedUtc.Value).TotalSeconds),
                }, Configuration.Formatters.JsonFormatter)
            };
        }
    }
    
        

    0 讨论(0)
    提交回复
    热议问题