hobik
hobik

Reputation: 491

Flutter NodeJS Authorization Issue

I'm new flutter and nodejs.

I wrote the API with nodejs to save people to MongoDB database. So I successfully working with sign-login process users saved database.

But in the some point I want to change and update some data, for example user balance. So I write below function for the flutter:

  static Future<BalanceUpdateResponseModel> update(
      BalanceUpdateRequestModel model) async {
    // var loginDetails = await SharedService.loginDetails();

    Map<String, String> requestHeaders = {
      'Content-Type': 'application/json',
      // 'Authorization': 'Basic ${loginDetails!.data.token}'
    };
    var url = Uri.http(Config.apiURL, Config.updateBalanceAPI);
    print(url);
    var response = await client.post(
      url,
      headers: requestHeaders,
      body: jsonEncode(model.toJson()),
    );
    print(balanceResponseJson(response.body));
    return balanceResponseJson(response.body);
  }

But when I want to use this function I get unauthorized user. But before, user login and authorized.

I call the update function in below:

var loginDetails = await SharedService.loginDetails();
username = loginDetails?.data.username;
// password = loginDetails?.data.password;
email = loginDetails?.data.email;
balance = loginDetails?.data.balance;
print("before balance: ");
print(balance);
updatedBalance = (balance! - 5);

BalanceUpdateRequestModel model = BalanceUpdateRequestModel(
  username: username!,
  email: email!,
  balance: updatedBalance,
);
APIService.update(model).then((response) {
  if (response.data != null) {
    print("current balance");
    print(balance);
  }
});

Whe I try to send post update method with Postman after the authorized user, everything working correctly. But when I try to send post request with flutter I get unauthorized although user authorized.

I write service functions like in links https://github.com/SnippetCoders/flutter_nodejs_jwt_login_register/blob/main/services/user.services.js

How can I solve the problem ?

Upvotes: 0

Views: 86

Answers (1)

activout.se
activout.se

Reputation: 6106

Your Authorization header is commented out and specifies Basic authentication:

      // 'Authorization': 'Basic ${loginDetails!.data.token}'

But with tokens, it is usually Bearer authentication that is used:

      'Authorization': 'Bearer ${loginDetails!.data.token}'

Upvotes: 1

Related Questions