-
Notifications
You must be signed in to change notification settings - Fork 0
feat(http): implement token refresh mechanism and JWT invalidation in new http feature #32
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
ff3fb7a
feat(auth): implement token refresh mechanism and JWT invalidation
marfavi 31f352a
feat(auth): add AuthCubitHandle to token refresh authenticator
marfavi b4b77ed
refactor(http): move http-related files to new http feature
marfavi 821ea80
refactor(auth): update documentation for AuthCubitHandle and AuthToke…
marfavi 3d15f53
fix(failures): correct variable name from statuscode to statusCode in…
marfavi c194510
fix typo in ServerFailure
marfavi a151fc2
Add more logging on refresh success/failure
marfavi 288dae7
add token_refresh_authenticator tests
marfavi 5cf9fcf
remove toString method from AuthTokens class
marfavi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| export 'package:cafe_analog_app/generated/api/client_index.dart'; | ||
| export 'package:cafe_analog_app/generated/api/coffeecard_api_v2.enums.swagger.dart'; | ||
| export 'package:cafe_analog_app/generated/api/coffeecard_api_v2.models.swagger.dart'; | ||
| export 'package:cafe_analog_app/generated/api/coffeecard_api_v2.swagger.dart'; | ||
|
|
||
| export 'make_http_client.dart'; | ||
| export 'network_request_executor.dart'; | ||
| export 'network_request_interceptor.dart'; | ||
| export 'token_refresh_authenticator.dart'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import 'package:cafe_analog_app/http/http.dart'; | ||
| import 'package:chopper/chopper.dart'; | ||
| import 'package:flutter/material.dart'; | ||
| import 'package:flutter_bloc/flutter_bloc.dart'; | ||
|
|
||
| const String _baseUrl = 'https://core.dev.analogio.dk'; | ||
|
|
||
| /// Creates and configures the [ChopperClient]s used for network requests. | ||
| ChopperClient makeHttpClient(BuildContext context) { | ||
| // Separate http client only used to refresh token requests. | ||
| // Calls done from this client won't trigger the authenticator | ||
| // (token refresh logic) or interceptor (injecting jwt token in auth header). | ||
| final tokenRefreshClient = ChopperClient( | ||
| baseUrl: Uri.parse(_baseUrl), | ||
| converter: $JsonSerializableConverter(), | ||
| services: [CoffeecardApiV2.create()], | ||
| ); | ||
|
|
||
| return ChopperClient( | ||
| baseUrl: Uri.parse(_baseUrl), | ||
| converter: $JsonSerializableConverter(), | ||
| services: [CoffeecardApiV1.create(), CoffeecardApiV2.create()], | ||
| interceptors: [NetworkRequestInterceptor(authTokenStore: context.read())], | ||
| authenticator: TokenRefreshAuthenticator( | ||
| authTokenRepository: context.read(), | ||
| tokenRefreshApi: tokenRefreshClient.getService<CoffeecardApiV2>(), | ||
| authCubitHandle: context.read(), | ||
| ), | ||
| ); | ||
| } | ||
2 changes: 1 addition & 1 deletion
2
lib/core/network_request_executor.dart → lib/http/network_request_executor.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
7 changes: 3 additions & 4 deletions
7
lib/core/network_request_interceptor.dart → lib/http/network_request_interceptor.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| import 'dart:async'; | ||
| import 'dart:developer'; | ||
|
|
||
| import 'package:cafe_analog_app/http/http.dart'; | ||
| import 'package:cafe_analog_app/login/bloc/auth_cubit_handle.dart'; | ||
| import 'package:cafe_analog_app/login/data/authentication_token_repository.dart'; | ||
| import 'package:cafe_analog_app/login/data/authentication_tokens.dart'; | ||
| import 'package:chopper/chopper.dart'; | ||
|
|
||
| class TokenRefreshAuthenticator extends Authenticator { | ||
| TokenRefreshAuthenticator({ | ||
| required AuthTokenRepository authTokenRepository, | ||
| required CoffeecardApiV2 tokenRefreshApi, | ||
| required AuthCubitHandle authCubitHandle, | ||
| }) : _authTokenRepository = authTokenRepository, | ||
| _tokenRefreshApi = tokenRefreshApi, | ||
| _authCubitHandle = authCubitHandle; | ||
|
|
||
| /// This header is added to requests that have already been retried after a | ||
| /// token refresh. Prevents infinite retry loops in case the new token is also | ||
| /// invalid for some reason. | ||
| static const _retryHeader = 'X-Auth-Retry'; | ||
|
|
||
| final AuthTokenRepository _authTokenRepository; | ||
| final CoffeecardApiV2 _tokenRefreshApi; | ||
| final AuthCubitHandle _authCubitHandle; | ||
| Completer<AuthTokens?>? _refreshCompleter; | ||
|
|
||
| @override | ||
| FutureOr<Request?> authenticate( | ||
| Request request, | ||
| Response<dynamic> response, [ | ||
| Request? _, | ||
| ]) async { | ||
| if (response.statusCode != 401) return null; | ||
| if (request.headers[_retryHeader] == 'true') return null; | ||
| if (request.url.path.endsWith('/api/v2/account/auth')) return null; | ||
|
|
||
| log( | ||
| 'Received 401 response for request: ${request.url}, ' | ||
| 'attempting to refresh tokens...\n' | ||
| '-- Headers: ${request.headers}', | ||
marfavi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ); | ||
|
|
||
| final refreshedTokens = await _refreshTokens(); | ||
| if (refreshedTokens == null) { | ||
| await _authCubitHandle.logOut(); | ||
| return null; | ||
| } | ||
|
|
||
| final updatedRequest = applyHeader( | ||
| request, | ||
| 'Authorization', | ||
| 'Bearer ${refreshedTokens.jwt}', | ||
| ); | ||
|
|
||
| return updatedRequest.copyWith( | ||
| headers: {...updatedRequest.headers, _retryHeader: 'true'}, | ||
| ); | ||
| } | ||
|
|
||
| Future<AuthTokens?> _refreshTokens() async { | ||
| if (_refreshCompleter != null) return _refreshCompleter!.future; | ||
|
|
||
| final completer = Completer<AuthTokens?>(); | ||
| _refreshCompleter = completer; | ||
marfavi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| try { | ||
| final tokensEither = await _authTokenRepository.getTokens().run(); | ||
| final existingTokens = tokensEither.match( | ||
| (_) => null, | ||
| (maybeTokens) => maybeTokens.match( | ||
| () => null, | ||
| (tokens) => tokens, | ||
| ), | ||
| ); | ||
|
|
||
| if (existingTokens == null) { | ||
| log('Token refresh aborted: no tokens found in storage.'); | ||
| completer.complete(null); | ||
| return completer.future; | ||
| } | ||
|
|
||
| final refreshResponse = await _tokenRefreshApi.accountAuthPost( | ||
| body: TokenLoginRequest(token: existingTokens.refreshToken), | ||
| ); | ||
| final responseBody = refreshResponse.body; | ||
|
|
||
| if (!refreshResponse.isSuccessful || responseBody == null) { | ||
| log( | ||
| 'Token refresh failed: server responded with ' | ||
| '${refreshResponse.statusCode}.', | ||
| ); | ||
| completer.complete(null); | ||
| return completer.future; | ||
| } | ||
|
|
||
| final newTokens = AuthTokens( | ||
| jwt: responseBody.jwt, | ||
| refreshToken: responseBody.refreshToken, | ||
| ); | ||
|
|
||
| final savedTokens = await _authTokenRepository | ||
| .saveTokens(newTokens) | ||
| .match((_) => null, (tokens) => tokens) | ||
| .run(); | ||
|
|
||
| if (savedTokens != null) { | ||
| log('Token refresh succeeded.'); | ||
| } else { | ||
| log('Token refresh succeeded but saving new tokens failed.'); | ||
| } | ||
| completer.complete(savedTokens); | ||
| return completer.future; | ||
marfavi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } on Exception catch (e) { | ||
| log('Token refresh failed with exception: $e.'); | ||
| completer.complete(null); | ||
| return completer.future; | ||
| } finally { | ||
| _refreshCompleter = null; | ||
| } | ||
| } | ||
| } | ||
marfavi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import 'dart:async'; | ||
|
|
||
| import 'package:cafe_analog_app/http/http.dart'; | ||
| import 'package:cafe_analog_app/login/bloc/authentication_cubit.dart'; | ||
| import 'package:chopper/chopper.dart'; | ||
| import 'package:flutter_bloc/flutter_bloc.dart'; | ||
marfavi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /// Breaks the dependency cycle between the HTTP layer and the auth cubit. | ||
| /// | ||
| /// [ChopperClient] (that contains [TokenRefreshAuthenticator]) is wired up in | ||
| /// a [RepositoryProvider] that runs before the [BlocProvider] for [AuthCubit]. | ||
| /// This means the authenticator is constructed before a cubit instance exists, | ||
| /// so it cannot receive the cubit directly. | ||
| /// | ||
| /// Instead, both are given this shared handle. Once the [BlocProvider] creates | ||
| /// [AuthCubit] it immediately calls [bind], after which any call to [logOut] | ||
| /// (e.g. when token refresh fails and the user must be signed out) is | ||
| /// forwarded to the live cubit. The internal [Completer] guarantees that | ||
| /// calls arriving before [bind] has run are safely queued rather than dropped. | ||
| class AuthCubitHandle { | ||
| final _completer = Completer<AuthCubit>(); | ||
| AuthCubit? _cubit; | ||
|
|
||
| void bind(AuthCubit cubit) { | ||
| _cubit = cubit; | ||
| if (!_completer.isCompleted) { | ||
| _completer.complete(cubit); | ||
| } | ||
| } | ||
marfavi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| Future<void> logOut() async { | ||
| final cubit = _cubit ?? await _completer.future; | ||
| await cubit.logOut(); | ||
| } | ||
| } | ||
marfavi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.