supertokens/supertokens-flutter

getAccessToken does not work

Closed this issue · 5 comments

Hi,

I keep getting a 401 with my API, so I checked the respective variables once.
The function getAccessToken doesn't seem to work, as it returns null even though a session exists.

The code:

      var hasSession = await SuperTokens.doesSessionExist();
      print('hasSession');
      print(hasSession);
      var accessToken = await SuperTokens.getAccessToken();
      print('accessToken');
      print(accessToken);

Result:

I/flutter (17793): hasSession
I/flutter (17793): true
I/flutter (17793): accessToken
I/flutter (17793): null

Thanks for your work!

Hi @renehauck,

Can you post the config you set when initialising SuperTokens? Both on the frontend and backend if possible

I have now looked a little deeper into the code and I have seen in the utilities.dart file that a key called st-storage-item-st-access-token(composed of the prefix st-storage-item and name="st-access-token") is queried.

image

However, if I now look at the code

SharedPreferences instance = await SharedPreferences.getInstance();
var keys = instance.getKeys();

then this key is not included.

image

Sure, here's the BE code:

{
      appInfo: {
        // Learn more about this on https://supertokens.com/docs/thirdpartyemailpassword/appinfo
        appName: '****',
        apiDomain: '****',
        websiteDomain: '****',
        apiBasePath: '/api',
        websiteBasePath: '/auth',
      },
      supertokens: {
        connectionURI: '****',
      },
      recipeList: [
        Dashboard.init({
          apiKey: '****',
        }),
        // EmailPassword.init({
        // }),
        Passwordless.init({
          flowType: 'USER_INPUT_CODE',
          contactMethod: 'EMAIL',
          emailDelivery: {
            override: (originalImplementation) => ({
              ...originalImplementation,
              sendEmail: async (input) => {
               ....
                 
              },
            }),
          },
          override: {
            apis: (originalImplementation) => {
              return {
                ...originalImplementation,
                createCodePOST: async function (input) {
                  ....
                    return originalImplementation.createCodePOST(input);
                  } catch (error) {
                    Logger.error(error, 'Passwordless.createCodePOST');
                    throw error;
                  }
                },
              };
            },
          },
        }),
        Session.init({
          antiCsrf: 'NONE',
          override: {
            functions: (originalImplementation) => ({
              ...originalImplementation,
              createNewSession: async function (input) {
                try {
                  ...
                  const targetCmsUser = cmsUsers.data[0];
                  input.accessTokenPayload = {
                    ...input.accessTokenPayload,
                    cmsId: targetCmsUser.id,
                    email: authUser.email,
                    mainStoreCmsId: targetCmsUser.attributes.store.data.id,
                  };
                  const session = await originalImplementation.createNewSession(
                    input
                  );
                  return session;
                } catch (error) {
                  Logger.error(error, 'Session.createNewSession');
                  throw error;
                }
              },
            })
          },

flutter:

import 'dart:convert';
import 'package:supertokens_flutter/supertokens.dart';
import 'package:supertokens_flutter/http.dart' as http;
import '../../config.dart';
import 'login_response.dart';

class Auth {
  static init() {
    SuperTokens.init(
      apiDomain: AppConfig.apiUrl,
      apiBasePath: AppConfig.apiBasePath,
    );
  }

  /// login
  static Future<LoginResponse> login(String email) async {
    Uri uri = Uri.parse("${AppConfig.apiDomain}/signinup/code");
    var resp = await http.post(uri, body: {
      "email": email
    }, headers: {
      "rid": "passwordless",
    });
    if (resp.statusCode.toString() != "200") {
      // TODO ERROR HANDLING
      throw Exception(resp.body);
    }
    var decodedJson = json.decode(resp.body);
    var loginResponse = LoginResponse.fromJson(decodedJson);
    return loginResponse;
  }

  /// verify
  static Future<CodeVerifyResponse> verify(
      String deviceId, String preAuthSessionId, String userInputCode) async {
    Uri uri = Uri.parse("${AppConfig.apiDomain}/signinup/code/consume");
    var resp = await http.post(uri, body: {
      "userInputCode": userInputCode,
      "deviceId": deviceId,
      "preAuthSessionId": preAuthSessionId,
    }, headers: {
      "rid": "passwordless",
    });
    var decodedJson = json.decode(resp.body);
    var loginResponse = CodeVerifyResponse.fromJson(decodedJson);
    return loginResponse;
  }
}

What version of supertokens-node are you using in your backend?

currently supertokens-node": "^12.1.1", I will try to update

oh man, that fixed it. Thanks for the help, you guys are awesome!