<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adel Djeziri on Medium]]></title>
        <description><![CDATA[Stories by Adel Djeziri on Medium]]></description>
        <link>https://medium.com/@adel.djeziri.42.46?source=rss-88e24c9053f1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*eRcB8Jg2T5PqJERW</url>
            <title>Stories by Adel Djeziri on Medium</title>
            <link>https://medium.com/@adel.djeziri.42.46?source=rss-88e24c9053f1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:48:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adel.djeziri.42.46/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Authentication in Flutter with Clean Architecture and BLoC]]></title>
            <link>https://medium.com/@adel.djeziri.42.46/authentication-in-flutter-with-clean-architecture-and-bloc-3df2532e6910?source=rss-88e24c9053f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3df2532e6910</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[dios]]></category>
            <dc:creator><![CDATA[Adel Djeziri]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 15:31:21 GMT</pubDate>
            <atom:updated>2026-09-03T15:31:21.286Z</atom:updated>
            <content:encoded><![CDATA[<p>Authentication is one of the most important features in a modern mobile application. It is responsible for identifying users, protecting private resources, managing sessions, and controlling access to different parts of the application.</p><p>In Flutter, authentication can become difficult to maintain when UI code, API calls, token management, and business logic are mixed together.</p><p>A better approach is to combine <strong>Clean Architecture</strong> with <strong>BLoC</strong>.</p><p>This article explains how to design an authentication system using:</p><ul><li>Flutter</li><li>BLoC</li><li>Clean Architecture</li><li>Repository Pattern</li><li>Use Cases</li><li>REST API</li><li>JWT</li><li>Secure local storage</li></ul><h3>1. What is Authentication?</h3><p>Authentication answers one fundamental question:</p><blockquote><em>“Who is this user?”</em></blockquote><p>For example, a user provides:</p><pre>Email<br>Password</pre><p>The application sends these credentials to the backend.</p><p>If they are valid, the backend returns an authentication token.</p><pre>Flutter App<br>    │<br>    │ email + password<br>    ▼<br>Backend API<br>    │<br>    │ verify credentials<br>    ▼<br>Database<br>    │<br>    │ user found<br>    ▼<br>Backend<br>    │<br>    │ JWT<br>    ▼<br>Flutter App</pre><p>The Flutter application then stores the token and uses it when communicating with protected endpoints.</p><h3>2. Authentication vs Authorization</h3><p>These two concepts are often confused.</p><h3>Authentication</h3><p>Authentication determines <strong>who you are</strong>.</p><p>Example:</p><pre>Login with:<br>email = adel@example.com<br>password = ********</pre><p>The server verifies your identity.</p><h3>Authorization</h3><p>Authorization determines <strong>what you are allowed to do</strong>.</p><p>For example:</p><pre>Customer → Create order<br>Driver   → Accept delivery<br>Admin    → Manage users</pre><p>Therefore:</p><pre>Authentication<br>      ↓<br>Who are you?<br>      ↓<br>Authorization<br>      ↓<br>What can you do?</pre><h3>3. Why Clean Architecture?</h3><p>Without architecture, authentication code can quickly become something like:</p><pre>class LoginPage extends StatefulWidget {<br>  // UI</pre><pre>  Future&lt;void&gt; login() async {<br>    final response = await dio.post(<br>      &#39;/login&#39;,<br>      data: {<br>        &#39;email&#39;: email,<br>        &#39;password&#39;: password,<br>      },<br>    );</pre><pre>    // save token<br>    // parse user<br>    // navigate<br>    // handle errors<br>  }<br>}</pre><p>This works initially, but it creates several problems.</p><p>The UI now knows about:</p><ul><li>HTTP</li><li>API endpoints</li><li>JSON</li><li>token storage</li><li>authentication logic</li><li>navigation</li><li>error handling</li></ul><p>Clean Architecture separates these responsibilities.</p><p>The resulting flow becomes:</p><pre>Page<br> ↓<br>BLoC<br> ↓<br>Use Case<br> ↓<br>Repository<br> ↓<br>Data Source<br> ↓<br>API</pre><p>Each layer has a specific responsibility.</p><h3>4. Recommended Authentication Structure</h3><p>A feature-based structure works well:</p><pre>lib/<br>│<br>├── core/<br>│   ├── error/<br>│   ├── network/<br>│   ├── storage/<br>│   ├── routes/<br>│   └── utils/<br>│<br>└── features/<br>    │<br>    └── auth/<br>        │<br>        ├── data/<br>        │   ├── datasources/<br>        │   │   ├── auth_remote_datasource.dart<br>        │   │   └── auth_local_datasource.dart<br>        │   │<br>        │   ├── models/<br>        │   │   └── user_model.dart<br>        │   │<br>        │   └── repositories/<br>        │       └── auth_repository_impl.dart<br>        │<br>        ├── domain/<br>        │   ├── entities/<br>        │   │   └── user_entity.dart<br>        │   │<br>        │   ├── repositories/<br>        │   │   └── auth_repository.dart<br>        │   │<br>        │   └── usecases/<br>        │       ├── login.dart<br>        │       ├── register.dart<br>        │       ├── logout.dart<br>        │       └── get_current_user.dart<br>        │<br>        └── presentation/<br>            ├── bloc/<br>            │   ├── auth_bloc.dart<br>            │   ├── auth_event.dart<br>            │   └── auth_state.dart<br>            │<br>            ├── pages/<br>            │   ├── login_page.dart<br>            │   └── register_page.dart<br>            │<br>            └── widgets/</pre><h3>5. Domain Layer</h3><p>The domain layer contains the application’s business rules.</p><p>It should not depend on:</p><pre>Flutter<br>Dio<br>Firebase<br>HTTP<br>SharedPreferences<br>SecureStorage</pre><p>The domain should remain independent.</p><h3>User Entity</h3><p>The entity represents the user from a business perspective.</p><pre>class UserEntity {<br>  final int id;<br>  final String username;<br>  final String email;<br>  final String fullName;</pre><pre>  const UserEntity({<br>    required this.id,<br>    required this.username,<br>    required this.email,<br>    required this.fullName,<br>  });<br>}</pre><p>The entity doesn’t care where the user comes from.</p><p>It could come from:</p><pre>REST API<br>GraphQL<br>Firebase<br>Local database<br>Mock data</pre><h3>6. Repository Contract</h3><p>The domain defines what authentication can do.</p><pre>abstract class AuthRepository {<br>  Future&lt;Either&lt;Failure, UserEntity&gt;&gt; login({<br>    required String identifier,<br>    required String password,<br>  });</pre><pre>  Future&lt;Either&lt;Failure, UserEntity&gt;&gt; register({<br>    required String username,<br>    required String email,<br>    required String password,<br>    required String fullName,<br>  });</pre><pre>  Future&lt;Either&lt;Failure, void&gt;&gt; logout();</pre><pre>  Future&lt;Either&lt;Failure, UserEntity?&gt;&gt; getCurrentUser();<br>}</pre><p>Notice something important.</p><p>The domain doesn’t say:</p><pre>Dio<br>POST<br>/api/auth/login<br>JSON<br>HTTP 200</pre><p>It only defines the required behavior.</p><h3>7. Use Cases</h3><p>Use cases represent actions that the application can perform.</p><p>For authentication, typical use cases are:</p><pre>Login<br>Register<br>Logout<br>Get Current User<br>Refresh Token<br>Verify Email<br>Reset Password<br>Change Password</pre><p>For example:</p><pre>class LoginUseCase {<br>  final AuthRepository repository;</pre><pre>  LoginUseCase(this.repository);</pre><pre>  Future&lt;Either&lt;Failure, UserEntity&gt;&gt; call(<br>    LoginParams params,<br>  ) {<br>    return repository.login(<br>      identifier: params.identifier,<br>      password: params.password,<br>    );<br>  }<br>}</pre><p>The parameters can be separated into their own class:</p><pre>class LoginParams {<br>  final String identifier;<br>  final String password;</pre><pre>  const LoginParams({<br>    required this.identifier,<br>    required this.password,<br>  });<br>}</pre><p>Now the BLoC doesn’t need to know how login is implemented.</p><h3>8. Data Layer</h3><p>The data layer is responsible for communicating with external systems.</p><p>For example:</p><pre>API<br>Database<br>Local Storage<br>Firebase</pre><p>The data layer normally contains:</p><pre>Models<br>Data Sources<br>Repository Implementations</pre><h3>9. User Model</h3><p>The model converts API data into an application representation.</p><p>Suppose the backend returns:</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;username&quot;: &quot;adel&quot;,<br>  &quot;email&quot;: &quot;adel@example.com&quot;,<br>  &quot;fullName&quot;: &quot;Adel Djeziri&quot;<br>}</pre><p>The model can be:</p><pre>class UserModel extends UserEntity {<br>  const UserModel({<br>    required super.id,<br>    required super.username,<br>    required super.email,<br>    required super.fullName,<br>  });</pre><pre>  factory UserModel.fromJson(Map&lt;String, dynamic&gt; json) {<br>    return UserModel(<br>      id: json[&#39;id&#39;],<br>      username: json[&#39;username&#39;],<br>      email: json[&#39;email&#39;],<br>      fullName: json[&#39;fullName&#39;],<br>    );<br>  }<br>}</pre><p>Now JSON parsing remains inside the data layer.</p><h3>10. Remote Data Source</h3><p>The remote data source communicates with the backend.</p><p>For example:</p><pre>abstract class AuthRemoteDataSource {<br>  Future&lt;UserModel&gt; login({<br>    required String identifier,<br>    required String password,<br>  });</pre><pre>  Future&lt;UserModel&gt; register({<br>    required String username,<br>    required String email,<br>    required String password,<br>    required String fullName,<br>  });</pre><pre>  Future&lt;void&gt; logout();<br>}</pre><p>Implementation:</p><pre>class AuthRemoteDataSourceImpl<br>    implements AuthRemoteDataSource {<br>  final Dio dio;</pre><pre>  AuthRemoteDataSourceImpl(this.dio);</pre><pre>  @override<br>  Future&lt;UserModel&gt; login({<br>    required String identifier,<br>    required String password,<br>  }) async {<br>    final response = await dio.post(<br>      &#39;/auth/login&#39;,<br>      data: {<br>        &#39;identifier&#39;: identifier,<br>        &#39;password&#39;: password,<br>      },<br>    );</pre><pre>    return UserModel.fromJson(response.data[&#39;user&#39;]);<br>  }<br>}</pre><p>The API implementation stays here.</p><h3>11. Repository Implementation</h3><p>The repository connects the domain with the data layer.</p><pre>class AuthRepositoryImpl implements AuthRepository {<br>  final AuthRemoteDataSource remoteDataSource;</pre><pre>  AuthRepositoryImpl(this.remoteDataSource);</pre><pre>  @override<br>  Future&lt;Either&lt;Failure, UserEntity&gt;&gt; login({<br>    required String identifier,<br>    required String password,<br>  }) async {<br>    try {<br>      final user = await remoteDataSource.login(<br>        identifier: identifier,<br>        password: password,<br>      );</pre><pre>      return Right(user);<br>    } catch (e) {<br>      return Left(<br>        ServerFailure(<br>          message: &#39;Login failed&#39;,<br>        ),<br>      );<br>    }<br>  }<br>}</pre><p>The repository decides how external data becomes domain data.</p><h3>12. Token Management</h3><p>After successful login, the backend commonly returns a token.</p><p>For example:</p><pre>{<br>  &quot;user&quot;: {<br>    &quot;id&quot;: 1,<br>    &quot;username&quot;: &quot;adel&quot;<br>  },<br>  &quot;accessToken&quot;: &quot;eyJhbGciOiJIUzI1Ni...&quot;<br>}</pre><p>The token should not be stored directly in the UI.</p><p>A storage abstraction is better:</p><pre>abstract class TokenStorage {<br>  Future&lt;void&gt; saveToken(String token);</pre><pre>  Future&lt;String?&gt; getToken();</pre><pre>  Future&lt;void&gt; deleteToken();<br>}</pre><p>The implementation can use secure storage.</p><pre>class TokenStorageImpl implements TokenStorage {<br>  final FlutterSecureStorage storage;</pre><pre>  TokenStorageImpl(this.storage);</pre><pre>  static const tokenKey = &#39;access_token&#39;;</pre><pre>  @override<br>  Future&lt;void&gt; saveToken(String token) {<br>    return storage.write(<br>      key: tokenKey,<br>      value: token,<br>    );<br>  }</pre><pre>  @override<br>  Future&lt;String?&gt; getToken() {<br>    return storage.read(key: tokenKey);<br>  }</pre><pre>  @override<br>  Future&lt;void&gt; deleteToken() {<br>    return storage.delete(key: tokenKey);<br>  }<br>}</pre><p>This keeps storage implementation outside the domain.</p><h3>13. BLoC</h3><p>BLoC manages authentication state for the UI.</p><p>Typical events:</p><pre>abstract class AuthEvent {}</pre><pre>class LoginRequested extends AuthEvent {<br>  final String identifier;<br>  final String password;</pre><pre>  LoginRequested({<br>    required this.identifier,<br>    required this.password,<br>  });<br>}</pre><pre>class LogoutRequested extends AuthEvent {}</pre><pre>class CheckAuthRequested extends AuthEvent {}</pre><p>States:</p><pre>abstract class AuthState {}</pre><pre>class AuthInitial extends AuthState {}</pre><pre>class AuthLoading extends AuthState {}</pre><pre>class AuthAuthenticated extends AuthState {<br>  final UserEntity user;</pre><pre>  AuthAuthenticated(this.user);<br>}</pre><pre>class AuthUnauthenticated extends AuthState {}</pre><pre>class AuthError extends AuthState {<br>  final String message;</pre><pre>  AuthError(this.message);<br>}</pre><h3>14. Auth BLoC</h3><p>The BLoC receives events and executes use cases.</p><pre>class AuthBloc extends Bloc&lt;AuthEvent, AuthState&gt; {<br>  final LoginUseCase login;<br>  final LogoutUseCase logout;<br>  final GetCurrentUserUseCase getCurrentUser;</pre><pre>  AuthBloc({<br>    required this.login,<br>    required this.logout,<br>    required this.getCurrentUser,<br>  }) : super(AuthInitial()) {<br>    on&lt;LoginRequested&gt;(_onLoginRequested);<br>    on&lt;LogoutRequested&gt;(_onLogoutRequested);<br>    on&lt;CheckAuthRequested&gt;(_onCheckAuthRequested);<br>  }</pre><pre>  Future&lt;void&gt; _onLoginRequested(<br>    LoginRequested event,<br>    Emitter&lt;AuthState&gt; emit,<br>  ) async {<br>    emit(AuthLoading());</pre><pre>    final result = await login(<br>      LoginParams(<br>        identifier: event.identifier,<br>        password: event.password,<br>      ),<br>    );</pre><pre>    result.fold(<br>      (failure) {<br>        emit(AuthError(failure.message));<br>      },<br>      (user) {<br>        emit(AuthAuthenticated(user));<br>      },<br>    );<br>  }<br>}</pre><p>The BLoC doesn’t know about:</p><pre>Dio<br>HTTP<br>JSON<br>API URL<br>Database</pre><p>That’s exactly what we want.</p><h3>15. UI</h3><p>The login page only interacts with the BLoC.</p><pre>context.read&lt;AuthBloc&gt;().add(<br>  LoginRequested(<br>    identifier: emailController.text,<br>    password: passwordController.text,<br>  ),<br>);</pre><p>Then:</p><pre>BlocConsumer&lt;AuthBloc, AuthState&gt;(<br>  listener: (context, state) {<br>    if (state is AuthAuthenticated) {<br>      context.go(&#39;/home&#39;);<br>    }</pre><pre>    if (state is AuthError) {<br>      ScaffoldMessenger.of(context).showSnackBar(<br>        SnackBar(<br>          content: Text(state.message),<br>        ),<br>      );<br>    }<br>  },<br>  builder: (context, state) {<br>    if (state is AuthLoading) {<br>      return const CircularProgressIndicator();<br>    }</pre><pre>    return LoginForm();<br>  },<br>);</pre><p>The UI’s responsibility is simply:</p><pre>Display UI<br>     ↓<br>Send events<br>     ↓<br>React to states</pre><h3>16. Complete Authentication Flow</h3><p>The complete architecture looks like this:</p><pre>PRESENTATION<br>                      │<br>                      ▼<br>                 LoginPage<br>                      │<br>                      ▼<br>                  AuthBloc<br>                      │<br>                      ▼<br>                  LoginUseCase<br>                      │<br>                      ▼<br>              AuthRepository<br>                      ▲<br>                      │<br>             AuthRepositoryImpl<br>                      │<br>                      ▼<br>            AuthRemoteDataSource<br>                      │<br>                      ▼<br>                    Dio<br>                      │<br>                      ▼<br>                 Backend API<br>                      │<br>                      ▼<br>                  Database</pre><p>After successful authentication:</p><pre>Backend<br>   │<br>   │ JWT<br>   ▼<br>Repository<br>   │<br>   ▼<br>TokenStorage<br>   │<br>   ▼<br>Secure Storage</pre><h3>17. Application Startup</h3><p>Authentication doesn’t only happen when the user presses Login.</p><p>When the application starts, you need to determine whether the user already has a valid session.</p><p>For example:</p><pre>Splash<br>  ↓<br>Check stored token<br>  ↓<br>Token exists?<br> ┌───────────────┐<br> │               │<br>No              Yes<br> │               │<br> ▼               ▼<br>Login       Validate session<br>                 │<br>          ┌──────┴──────┐<br>          │             │<br>        Valid         Invalid<br>          │             │<br>          ▼             ▼<br>        Home           Login</pre><p>A dedicated use case is useful:</p><pre>class GetCurrentUserUseCase {<br>  final AuthRepository repository;</pre><pre>  GetCurrentUserUseCase(this.repository);</pre><pre>  Future&lt;Either&lt;Failure, UserEntity?&gt;&gt; call() {<br>    return repository.getCurrentUser();<br>  }<br>}</pre><p>This prevents authentication initialization logic from being placed inside the splash page.</p><h3>18. Dio Interceptor</h3><p>Once the user is authenticated, protected requests usually need:</p><pre>Authorization: Bearer &lt;token&gt;</pre><p>Instead of manually adding the token to every request, use a Dio interceptor.</p><pre>class AuthInterceptor extends Interceptor {<br>  final TokenStorage tokenStorage;</pre><pre>  AuthInterceptor(this.tokenStorage);</pre><pre>  @override<br>  Future&lt;void&gt; onRequest(<br>    RequestOptions options,<br>    RequestInterceptorHandler handler,<br>  ) async {<br>    final token = await tokenStorage.getToken();</pre><pre>    if (token != null &amp;&amp; token.isNotEmpty) {<br>      options.headers[&#39;Authorization&#39;] =<br>          &#39;Bearer $token&#39;;<br>    }</pre><pre>    handler.next(options);<br>  }<br>}</pre><p>Now:</p><pre>dio.get(&#39;/profile&#39;);</pre><p>automatically becomes:</p><pre>GET /profile<br>Authorization: Bearer eyJ...</pre><h3>19. Refresh Tokens</h3><p>For production applications, access tokens are often short-lived.</p><p>For example:</p><pre>Access Token<br>   ↓<br>expires after 15 minutes</pre><p>A refresh token can be used to obtain a new access token.</p><p>The flow becomes:</p><pre>Request<br>  ↓<br>Access Token<br>  ↓<br>401 Unauthorized<br>  ↓<br>Refresh Token<br>  ↓<br>New Access Token<br>  ↓<br>Retry Request</pre><p>This logic belongs primarily in the networking/authentication infrastructure rather than inside individual UI widgets.</p><h3>20. Logout</h3><p>Logout should not simply navigate to the login page.</p><p>A proper logout process can be:</p><pre>Logout Event<br>     ↓<br>LogoutUseCase<br>     ↓<br>AuthRepository<br>     ↓<br>Clear local token<br>     ↓<br>Optional backend logout/revoke<br>     ↓<br>AuthUnauthenticated<br>     ↓<br>Login</pre><p>For example:</p><pre>class LogoutUseCase {<br>  final AuthRepository repository;</pre><pre>  LogoutUseCase(this.repository);</pre><pre>  Future&lt;Either&lt;Failure, void&gt;&gt; call() {<br>    return repository.logout();<br>  }<br>}</pre><h3>21. Authentication States</h3><p>Avoid creating too many unrelated boolean variables such as:</p><pre>bool isLoading;<br>bool hasError;<br>bool isLoggedIn;<br>bool isLoggingOut;<br>bool hasToken;</pre><p>This can lead to contradictory states.</p><p>For example:</p><pre>isLoading = true<br>isLoggedIn = true<br>hasError = true</pre><p>Instead, represent meaningful states:</p><pre>AuthInitial<br>AuthLoading<br>AuthAuthenticated<br>AuthUnauthenticated<br>AuthError</pre><p>The state becomes the source of truth for the UI.</p><h3>22. Dependency Injection</h3><p>Clean Architecture works especially well with dependency injection.</p><p>For example:</p><pre>Dio<br> ↓<br>AuthRemoteDataSource<br> ↓<br>AuthRepository<br> ↓<br>LoginUseCase<br> ↓<br>AuthBloc</pre><p>Using GetIt:</p><pre>getIt.registerLazySingleton&lt;Dio&gt;(<br>  () =&gt; Dio(),<br>);</pre><pre>getIt.registerLazySingleton&lt;AuthRemoteDataSource&gt;(<br>  () =&gt; AuthRemoteDataSourceImpl(<br>    getIt&lt;Dio&gt;(),<br>  ),<br>);</pre><pre>getIt.registerLazySingleton&lt;AuthRepository&gt;(<br>  () =&gt; AuthRepositoryImpl(<br>    getIt&lt;AuthRemoteDataSource&gt;(),<br>  ),<br>);</pre><pre>getIt.registerLazySingleton&lt;LoginUseCase&gt;(<br>  () =&gt; LoginUseCase(<br>    getIt&lt;AuthRepository&gt;(),<br>  ),<br>);</pre><pre>getIt.registerFactory&lt;AuthBloc&gt;(<br>  () =&gt; AuthBloc(<br>    login: getIt&lt;LoginUseCase&gt;(),<br>    logout: getIt&lt;LogoutUseCase&gt;(),<br>    getCurrentUser: getIt&lt;GetCurrentUserUseCase&gt;(),<br>  ),<br>);</pre><p>A useful rule is:</p><pre>Singleton<br>→ Services and repositories</pre><pre>Factory<br>→ BLoCs and short-lived objects</pre><p>This also helps avoid accidentally registering the same BLoC multiple times.</p><h3>23. Common Authentication Mistakes</h3><h3>Mistake 1 — API call directly from UI</h3><pre>onPressed: () async {<br>  await dio.post(&#39;/login&#39;);<br>}</pre><p>Avoid this.</p><p>Use:</p><pre>UI<br> ↓<br>BLoC<br> ↓<br>UseCase<br> ↓<br>Repository</pre><h3>Mistake 2 — Putting business logic inside BLoC</h3><p>BLoC should coordinate application state.</p><p>Don’t turn it into a massive class containing:</p><pre>API calls<br>JSON parsing<br>token storage<br>database queries<br>validation<br>business rules<br>navigation</pre><p>Keep those responsibilities separated.</p><h3>Mistake 3 — Putting Flutter dependencies in Domain</h3><p>Avoid:</p><pre>import &#39;package:flutter_secure_storage/flutter_secure_storage.dart&#39;;</pre><p>inside the domain layer.</p><p>The domain should remain framework-independent.</p><h3>Mistake 4 — Storing sensitive tokens carelessly</h3><p>Avoid storing authentication tokens in ordinary preferences when secure storage is appropriate.</p><p>Use a secure storage mechanism for sensitive credentials/tokens.</p><h3>Mistake 5 — Treating JWT as proof of everything</h3><p>A JWT is a credential, not a reason to trust arbitrary client-provided authorization data.</p><p>The backend must validate the token and enforce authorization on protected endpoints.</p><h3>24. Testing</h3><p>Clean Architecture makes authentication easier to test.</p><p>You can test the use case without Flutter.</p><pre>test(<br>  &#39;should login user successfully&#39;,<br>  () async {<br>    final result = await loginUseCase(<br>      LoginParams(<br>        identifier: &#39;adel&#39;,<br>        password: &#39;123456&#39;,<br>      ),<br>    );</pre><pre>    expect(result, isA&lt;Right&gt;());<br>  },<br>);</pre><p>You can separately test:</p><pre>RemoteDataSource<br>Repository<br>UseCase<br>BLoC</pre><p>For example:</p><pre>AuthBloc Test<br>     ↓<br>Mock LoginUseCase<br>     ↓<br>Success<br>     ↓<br>AuthAuthenticated</pre><p>The test doesn’t need a real API.</p><h3>25. Final Architecture</h3><p>A production authentication feature can therefore look like:</p><pre>FLUTTER<br>                            │<br>                            ▼<br>                     ┌─────────────┐<br>                     │ Login Page  │<br>                     └──────┬──────┘<br>                            │<br>                            ▼<br>                     ┌─────────────┐<br>                     │   AuthBloc  │<br>                     └──────┬──────┘<br>                            │<br>                            ▼<br>                     ┌─────────────┐<br>                     │  Use Cases  │<br>                     └──────┬──────┘<br>                            │<br>                            ▼<br>                     ┌─────────────┐<br>                     │ Repository  │<br>                     │  Interface  │<br>                     └──────┬──────┘<br>                            ▲<br>                            │<br>                     ┌──────┴──────┐<br>                     │ Repository  │<br>                     │     Impl    │<br>                     └──────┬──────┘<br>                            │<br>                     ┌──────▼──────┐<br>                     │ Data Source │<br>                     └──────┬──────┘<br>                            │<br>                            ▼<br>                          Dio<br>                            │<br>                            ▼<br>                       Backend API<br>                            │<br>                            ▼<br>                        Database</pre><p>The main principle is simple:</p><blockquote><strong><em>BLoC manages state, Use Cases execute business actions, Repositories abstract data access, and Data Sources communicate with external systems.</em></strong></blockquote><p>This separation makes authentication easier to <strong>maintain, test, debug, and scale</strong> as the application grows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3df2532e6910" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>