For some reason the Axios is returning 401, let me send all config that I am using. When using Swagger and Postman is working fine.
- I have one Authentication in my Web Api responsible to generate the token and send it to the client, the client is saving it at sessionStorage.
- When I calling the API passing the Bearer Token, I am getting the 401 error.
This is the Axios call:
getPatients: async (token: string): Promise<PatientDTO[]> => {
try {
const response: AxiosResponse<PatientDTO[]> = await axios.get(
`${API_BASE_URL}/patient`,
{
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
}
);
const patients = response.data.map((patient) => ({
...patient,
}));
return patients;
} catch (error) {
console.log("Error fetching patients:", error);
throw error;
}
},
This is the ApiConfig, as you can see I am AllowAnyHeaders,
services.AddCors(opt =>
{
opt.AddPolicy("CorsPolicy", policy =>
{
policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
});
});
.AddAuthentication(item =>
{
item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
item.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = false,
IssuerSigningKey = new SymmetricSecurityKey
(Encoding.UTF8.GetBytes(config["Jwt:Key"]))
};
});
Error: