TF-606 Implement refresh token when access token expired
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
|
||||
import 'package:flutter_appauth/flutter_appauth.dart';
|
||||
import 'package:model/model.dart';
|
||||
|
||||
extension TokenResponseExtension on TokenResponse {
|
||||
|
||||
TokenOIDC toTokenOIDC() {
|
||||
return TokenOIDC(
|
||||
accessToken ?? '',
|
||||
TokenId(idToken ?? ''),
|
||||
refreshToken ?? '',
|
||||
expiredTime: accessTokenExpirationDateTime ?? DateTime.now());
|
||||
}
|
||||
}
|
||||
@@ -25,4 +25,9 @@ class AccountCacheManager {
|
||||
log('AccountCacheManager::setSelectedAccount(): $_accountCacheClient');
|
||||
return _accountCacheClient.insertItem(account.id, account.toCache());
|
||||
}
|
||||
|
||||
Future<void> deleteSelectedAccount(String accountId) {
|
||||
log('AccountCacheManager::deleteSelectedAccount(): $accountId');
|
||||
return _accountCacheClient.deleteItem(accountId);
|
||||
}
|
||||
}
|
||||
@@ -26,8 +26,8 @@ class TokenOidcCacheManager {
|
||||
await _tokenOidcCacheClient.clearAllData();
|
||||
}
|
||||
log('TokenOidcCacheManager::persistOneTokenOidc(): key: ${tokenOIDC.tokenId.uuid}');
|
||||
log('TokenOidcCacheManager::persistOneTokenOidc(): key\'s hash: ${tokenOIDC.tokenId.hashCode.toString()}');
|
||||
log('TokenOidcCacheManager::persistOneTokenOidc(): key\'s hash: ${tokenOIDC.tokenIdHash}');
|
||||
log('TokenOidcCacheManager::persistOneTokenOidc(): token: ${tokenOIDC.token}');
|
||||
await _tokenOidcCacheClient.insertItem(tokenOIDC.tokenId.hashCode.toString(), tokenOIDC.toTokenOidcCache());
|
||||
await _tokenOidcCacheClient.insertItem(tokenOIDC.tokenIdHash, tokenOIDC.toTokenOidcCache());
|
||||
}
|
||||
}
|
||||
@@ -1,32 +1,141 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:core/utils/app_logger.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:model/model.dart';
|
||||
import 'package:model/account/account.dart';
|
||||
import 'package:model/account/authentication_type.dart';
|
||||
import 'package:model/oidc/oidc_configuration.dart';
|
||||
import 'package:model/oidc/token.dart';
|
||||
import 'package:model/oidc/token_oidc.dart';
|
||||
import 'package:tmail_ui_user/features/login/data/local/account_cache_manager.dart';
|
||||
import 'package:tmail_ui_user/features/login/data/local/token_oidc_cache_manager.dart';
|
||||
import 'package:tmail_ui_user/features/login/data/network/oidc_http_client.dart';
|
||||
|
||||
class AuthorizationInterceptors extends InterceptorsWrapper {
|
||||
String? _authorization;
|
||||
Token? _token;
|
||||
|
||||
void changeAuthorization(String? userName, String? password) {
|
||||
final Dio _dio;
|
||||
final OIDCHttpClient _oidcHttpClient;
|
||||
final TokenOidcCacheManager _tokenOidcCacheManager;
|
||||
final AccountCacheManager _accountCacheManager;
|
||||
|
||||
AuthenticationType _authenticationType = AuthenticationType.none;
|
||||
OIDCConfiguration? _configOIDC;
|
||||
Token? _token;
|
||||
String? _authorization;
|
||||
|
||||
AuthorizationInterceptors(
|
||||
this._dio,
|
||||
this._oidcHttpClient,
|
||||
this._tokenOidcCacheManager,
|
||||
this._accountCacheManager
|
||||
);
|
||||
|
||||
void setBasicAuthorization(String? userName, String? password) {
|
||||
_authorization = base64Encode(utf8.encode('$userName:$password'));
|
||||
_authenticationType = AuthenticationType.basic;
|
||||
}
|
||||
|
||||
void setToken(Token? newToken) {
|
||||
void setTokenAndAuthorityOidc({Token? newToken, OIDCConfiguration? newConfig}) {
|
||||
_token = newToken;
|
||||
_configOIDC = newConfig;
|
||||
_authenticationType = AuthenticationType.oidc;
|
||||
log('AuthorizationInterceptors::setToken(): newToken: $newToken');
|
||||
log('AuthorizationInterceptors::setToken(): tokenId: ${newToken?.tokenIdHash}');
|
||||
log('AuthorizationInterceptors::setToken(): EXPIRE_DATE: ${newToken?.expiredTime?.toIso8601String()}');
|
||||
}
|
||||
|
||||
void _updateNewToken(Token newToken) {
|
||||
_token = newToken;
|
||||
}
|
||||
|
||||
@override
|
||||
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
|
||||
if (_authorization != null) {
|
||||
options.headers[HttpHeaders.authorizationHeader] = _getAuthorizationAsBasicHeader(_authorization);
|
||||
} else if (_token != null && _token?.isTokenValid() == true) {
|
||||
options.headers[HttpHeaders.authorizationHeader] = _getTokenAsBearerHeader(_token!.token);
|
||||
switch(_authenticationType) {
|
||||
case AuthenticationType.basic:
|
||||
if (_authorization != null) {
|
||||
options.headers[HttpHeaders.authorizationHeader] = _getAuthorizationAsBasicHeader(_authorization);
|
||||
}
|
||||
break;
|
||||
case AuthenticationType.oidc:
|
||||
if (_token != null && _token?.isTokenValid() == true) {
|
||||
options.headers[HttpHeaders.authorizationHeader] = _getTokenAsBearerHeader(_token!.token);
|
||||
}
|
||||
break;
|
||||
case AuthenticationType.none:
|
||||
break;
|
||||
}
|
||||
super.onRequest(options, handler);
|
||||
}
|
||||
|
||||
@override
|
||||
void onError(DioError err, ErrorInterceptorHandler handler) async {
|
||||
final requestOptions = err.requestOptions;
|
||||
log('AuthorizationInterceptors::onError(): $err');
|
||||
if ((_isTokenExpired() || err.response?.statusCode == 401) &&
|
||||
_isAuthenticationOidcValid()) {
|
||||
try {
|
||||
final newToken = await _oidcHttpClient.refreshingTokensOIDC(
|
||||
_configOIDC!.clientId,
|
||||
_configOIDC!.redirectUrl,
|
||||
_configOIDC!.discoveryUrl,
|
||||
_configOIDC!.scopes,
|
||||
_token!.refreshToken);
|
||||
|
||||
await Future.wait([
|
||||
_tokenOidcCacheManager.persistOneTokenOidc(newToken),
|
||||
_accountCacheManager.deleteSelectedAccount(_token!.tokenIdHash),
|
||||
_accountCacheManager.setSelectedAccount(Account(
|
||||
newToken.tokenIdHash,
|
||||
AuthenticationType.oidc,
|
||||
isSelected: true)),
|
||||
]);
|
||||
|
||||
log('AuthorizationInterceptors::onError(): refreshToken: $newToken');
|
||||
log('AuthorizationInterceptors::setToken(): refreshTokenId: ${newToken.tokenIdHash}');
|
||||
|
||||
_updateNewToken(newToken.toToken());
|
||||
|
||||
requestOptions.headers[HttpHeaders.authorizationHeader] =
|
||||
_getTokenAsBearerHeader(newToken.token);
|
||||
|
||||
final response = await _dio.fetch(requestOptions);
|
||||
return handler.resolve(response);
|
||||
} catch(e) {
|
||||
log('AuthorizationInterceptors::onError(): $e');
|
||||
super.onError(err, handler);
|
||||
}
|
||||
} else {
|
||||
super.onError(err, handler);
|
||||
}
|
||||
}
|
||||
|
||||
bool _isTokenExpired() {
|
||||
if (_token?.isExpired == true) {
|
||||
log('AuthorizationInterceptors::_isTokenExpired(): TOKE_EXPIRED');
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool _isAuthenticationOidcValid() {
|
||||
if (_authenticationType == AuthenticationType.oidc &&
|
||||
_configOIDC != null &&
|
||||
_token != null) {
|
||||
log('AuthorizationInterceptors::_isAuthenticationOidcValid()');
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
String _getAuthorizationAsBasicHeader(String? authorization) => 'Basic $authorization';
|
||||
|
||||
String _getTokenAsBearerHeader(String token) => 'Bearer $token';
|
||||
|
||||
void clear() {
|
||||
_authorization = null;
|
||||
_token = null;
|
||||
_configOIDC = null;
|
||||
_authenticationType = AuthenticationType.none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:core/core.dart';
|
||||
import 'package:core/data/model/query/query_parameter.dart';
|
||||
import 'package:core/data/network/dio_client.dart';
|
||||
import 'package:core/utils/app_logger.dart';
|
||||
import 'package:flutter_appauth/flutter_appauth.dart';
|
||||
import 'package:model/model.dart';
|
||||
import 'package:model/oidc/oidc_configuration.dart';
|
||||
import 'package:model/oidc/request/oidc_request.dart';
|
||||
import 'package:model/oidc/response/oidc_response.dart';
|
||||
import 'package:model/oidc/token_oidc.dart';
|
||||
import 'package:tmail_ui_user/features/login/data/extensions/authentication_token_extension.dart';
|
||||
import 'package:tmail_ui_user/features/login/data/extensions/service_path_extension.dart';
|
||||
import 'package:tmail_ui_user/features/login/data/extensions/token_response_extension.dart';
|
||||
import 'package:tmail_ui_user/features/login/data/network/config/oidc_constant.dart';
|
||||
import 'package:tmail_ui_user/features/login/data/network/endpoint.dart';
|
||||
import 'package:tmail_ui_user/features/login/data/network/oidc_error.dart';
|
||||
import 'package:tmail_ui_user/features/login/domain/exceptions/authentication_exception.dart';
|
||||
|
||||
class OIDCHttpClient {
|
||||
|
||||
@@ -48,20 +55,47 @@ class OIDCHttpClient {
|
||||
}
|
||||
|
||||
Future<TokenOIDC> getTokenOIDC(String clientId, String redirectUrl, String discoveryUrl, List<String> scopes) async {
|
||||
final tokenResponse = await _appAuth.authorizeAndExchangeCode(AuthorizationTokenRequest(
|
||||
final authorizationTokenResponse = await _appAuth.authorizeAndExchangeCode(AuthorizationTokenRequest(
|
||||
clientId,
|
||||
redirectUrl,
|
||||
discoveryUrl: discoveryUrl,
|
||||
scopes: scopes,
|
||||
preferEphemeralSession: true));
|
||||
|
||||
log('OIDCHttpClient::getTokenOIDC(): token: ${tokenResponse?.accessToken}');
|
||||
log('OIDCHttpClient::getTokenOIDC(): token: ${authorizationTokenResponse?.accessToken}');
|
||||
|
||||
if (authorizationTokenResponse != null) {
|
||||
final tokenOIDC = authorizationTokenResponse.toTokenOIDC();
|
||||
if (tokenOIDC.isTokenValid()) {
|
||||
return tokenOIDC;
|
||||
} else {
|
||||
throw AccessTokenInvalidException();
|
||||
}
|
||||
} else {
|
||||
throw NotFoundAccessTokenException();
|
||||
}
|
||||
}
|
||||
|
||||
Future<TokenOIDC> refreshingTokensOIDC(String clientId, String redirectUrl,
|
||||
String discoveryUrl, List<String> scopes, String refreshToken) async {
|
||||
final tokenResponse = await _appAuth.token(TokenRequest(
|
||||
clientId,
|
||||
redirectUrl,
|
||||
discoveryUrl: discoveryUrl,
|
||||
refreshToken: refreshToken,
|
||||
scopes: scopes));
|
||||
|
||||
log('OIDCHttpClient::refreshingTokensOIDC(): refreshToken: ${tokenResponse?.accessToken}');
|
||||
|
||||
if (tokenResponse != null) {
|
||||
final tokenOIDC = tokenResponse.toTokenOIDC();
|
||||
return tokenOIDC.isTokenValid() ? tokenOIDC : TokenOIDC.empty();
|
||||
if (tokenOIDC.isTokenValid()) {
|
||||
return tokenOIDC;
|
||||
} else {
|
||||
throw AccessTokenInvalidException();
|
||||
}
|
||||
} else {
|
||||
return TokenOIDC.empty();
|
||||
throw NotFoundAccessTokenException();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user