android – Authorization in Flutter using token


In a typical scenario, tokens are generated by a backend server after validating the user’s credentials. However, since you don’t have a backend server and you’re not allowed to use any external services, you’ll have to simulate this process locally.

1). Here’s a simplified flow of how you can implement this:

When a user registers, store their credentials (username and password) securely in local storage. You can use packages like flutter_secure_storage for this.

2). Generate a “token” for the user. This can be any unique string. In a real-world scenario, this token would be a JWT (JSON Web Token) or similar, but for your case, it could be as simple as a UUID.

3). Store this token in local storage, associated with the user’s credentials.

4). When a user logs in, check their entered credentials against the stored credentials. If they match, retrieve the associated token from storage.

5). Use this token to “authorize” the user for subsequent actions within the app. You can store the token in memory while the app is running, and check for its presence to determine if the user is “authorized”.

Here’s a very basic example of how you might implement this in code:

    import 'dart:math';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

final storage = FlutterSecureStorage();

void register(String username, String password) async {
  // Store the user's credentials securely
  await storage.write(key: 'username', value: username);
  await storage.write(key: 'password', value: password);

  // Generate a "token" for the user (in this case, a random number)
  String token = Random().nextInt(1000000).toString();

  // Store the token
  await storage.write(key: 'token', value: token);
}

Future<String> login(String username, String password) async {
  // Retrieve the stored credentials
  String storedUsername = await storage.read(key: 'username');
  String storedPassword = await storage.read(key: 'password');

  // If the entered credentials match the stored ones, retrieve and return the token
  if (username == storedUsername && password == storedPassword) {
    String token = await storage.read(key: 'token');
    return token;
  } else {
    return null;
  }
}

Remember, this is a very simplified example and is not suitable for a real-world app. In a real app, you would need to use a secure backend server to handle authentication and token generation.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img