flutterdartbearer-tokenopenapi-generatordio

Use Bearer token with Openapi generator generated dart-dio API client


I have generated dart-dio API client with Openapi generator. I use it to login and obtain Bearer token. Then I call this:

openapi.setBearerAuth('Authorization', 'Bearer: $token');

I am not sure what values exactly should I pass here - that might be the problem. When I use API call for secured endpoint, authorization header is not sent which leads to 401 error.

openapi
.getSomethingApi
          .apiSomethingGet();

But it works when I specify the headers:

openapi
.getSomethingApi
          .apiSomethingGet(headers: {'Authorization': 'Bearer: $token'});

Did I misunderstand using authorization in Openapi generator generated dart-dio code or is there any other mistake I made?


Solution

  • I faced same issue as well, I think the interceptors are not initialized correctly, I end up do like below, put the code in the constructor when initializing the api instance

    _apiInstance = openapi.Openapi(
            basePathOverride: "your url",
            interceptors: [
              InterceptorsWrapper(onRequest: (options, handler) {
                options.headers['Authorization'] = 'Bearer $token';
                return handler.next(options);
              })
            ]);
    
    

    the onRequest method will be trigger in each request, so in the events that the token changed or updated, it will get the latest token