In Postman I can automatically save variables the from response body.
For example:
First I send login request and as response I get accessToken
and refreshToken
variables.
Then by Postman test scripts I save these variables:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("access_token", jsonData.accessToken);
postman.setEnvironmentVariable("refresh_token", jsonData.refreshToken);
These variables automatically updates themselves in next request:
The question is how I can do the same in Swagger UI?
The problem is that by default in Swagger UI every time I need to write refresh token by hand:
@CodingMytra tanks to your comment I found a solution.
By adding these UseRequestInterceptor
and UseResponseInterceptor
options, accessToken
and refreshToken
variables automatically updates themselves.
app.UseSwaggerUI(swaggerUiOptions =>
{
var responseInterceptor = @"(res) =>
{
if(res.obj.accessToken)
{
console.log(res.obj.accessToken);
const token = res.obj.accessToken;
localStorage.setItem('token', token);
};
if(res.obj.refreshToken)
{
console.log(res.obj.refreshToken);
const refresh_token = res.obj.refreshToken;
localStorage.setItem('refresh_token', refresh_token);
};
return res;
}";
var requestInterceptor = @"(req) =>
{
req.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token');
req.headers['RefreshToken'] = localStorage.getItem('refresh_token');
return req;
}";
swaggerUiOptions.UseResponseInterceptor(Regex.Replace(responseInterceptor, @"\s+", " "));
swaggerUiOptions.UseRequestInterceptor(Regex.Replace(requestInterceptor, @"\s+", " "));
});