Home > Software engineering >  How to add User Token from Flutter to Django Rest Framework to avoid Forbidden access
How to add User Token from Flutter to Django Rest Framework to avoid Forbidden access

Time:11-10

In my flutter project I have created an api_service.dart which sends username and password and returns back with the Token authorization.

I am currently not able to send the authorization Token in the header to allow fetching information from dj-rest-auth/user and I am getting Forbidden: /api/dj-rest-auth/user/

Here is the api_service.dart:

class APIService {
  static var client = http.Client();

  static Future<bool> login(
    LoginRequestModel model,
  ) async {
    Map<String, String> requestHeaders = {
      'Content-Type': 'application/json',
    };

    var url = Uri.parse(
      Config.apiURL   Config.loginAPI,
    );
    print(url);

    var response = await client.post(
      url,
      headers: requestHeaders,
      body: jsonEncode(model.toJson()),
    );
    print(response.body);

    if (response.statusCode == 200) {
      await SharedService.setLoginDetails(
        loginResponseJson(
          response.body,
        ),
      );
      print(response.body);

      return true;
    } else {
      return false;
    }
  }

Here is the function to call the user details:

Future<User> fetchUser() async {
  final response = await http.get("url");
  Map<String, String> requestHeaders = {
    'Content-Type': 'application/json',
    'Authorization': loginResponseJson(response.body),
  };

  if (response.statusCode == 200) {

    return User.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Failed to load User');
  }
}

I am receiving the following error:

error: The element type 'LoginResponseModel' can't be assigned to the map value type 'String'.

the loginResponseJson(response.body):

{"key":"............."}

My Question:

What is the best way to add the token to the header to allow user authentication to fetch data from Django Rest Framework. How can I fix this error?

CodePudding user response:

Maybe you want to store access token into SharedPreferences first. Then, for every request, you fetch this token from store and add to header. Currently, I use chopper for https generator as:

class AuthenticatedClient extends http.BaseClient {
  final http.Client _inner;
  final FlutterSecureStorage secureStorage;

  AuthenticatedClient(this._inner, {required this.secureStorage});

  @override
  Future<http.StreamedResponse> send(
    http.BaseRequest request,
  ) async {
    if (request.headers["Content-Type"] != null) {
      request.headers["Content-Type"] = "application/json";
    }

    final token = await secureStorage.read(key: PrefKeys.accessToken);
    if (token != null) {
      request.headers['Authorization'] = 'Bearer $token';
    }

    return _inner.send(request);
  }
}

CodePudding user response:

Make sure that your Authorization header has a valid structure

Map<String, String> requestHeaders = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer ${your_token}',

};

  • Related