9 OAuth 2.0 Token Expiration
Maciek Czarnik edited this page 2018-08-17 11:43:47 +02:00

Expires In Definition

The OAuth 2.0 standard, RFC 6749, defines the expires_in field as the number of seconds to expiration.

Manage failure

It is important to be able to detect the difference between generic errors and errors due to an expired token.

If and only if the token is expired, use a refresh token or start a new flow to obtain a new valid token

For the bearer tokens, used by OAuthSwift framework, an expired token will result in the following HTTP response for oauth provider that follow the rfc:

HTTP/1.1 401 Unauthorized 
WWW-Authenticate: Bearer realm="example", 
    error="invalid_token", 
    error_description="The access token expired"

You must check error code 401 and error is invalid_token

Special case for facebook

HTTP/1.1 400 Bad Request
WWW-Authenticate: OAuth "Facebook Platform" "invalid_token" 
    "Error validating access token: Session has expired 
    at unix time 1334415600. The current unix time is 1334822619.

or Error 467 Invalid access token https://developers.facebook.com/docs/graph-api/using-graph-api/v2.3#errors

With OAuthSwift

oauth.client.get(
  "www.example.com",
  success: { data, response in
    
  }, 
  failure: { error in
    if case .tokenExpired = error {
       // reconnect, `renewAccessToken`(oauth 2)     
    } 
  }
)

You can also use startAuthorizedRequest on OAuth2Swift instead of "client" functions, renew token will be done automatically, and this is a good example