Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 426
jsfrz Avatar asked Nov 06 '25 12:11

jsfrz


1 Answers

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

like image 84
Ismi Ammar Avatar answered Nov 08 '25 10:11

Ismi Ammar