问题
What should I look into to find out / track down a issue like this:
We have an Angular App calling a .Net Core Web API, with CORS enabled, and it authenticate through Azure AD, getting a Bearer token. With the Bearer token, the API calls fail with 401 Unauthorized from time to time, other times, 200. Yet I put the same Bearer Token into any REST client and API calls always work.
Greatly appreciate any input.
Some more Context/Analysis:
- API works fine with other applications. So if the issue is on the server side, it is not an often executed part of the code. The issue could be in the client side Angular code.
This Angular app is the only app use CORS. This obviously is something I'm looking into.
Local Development Server(Webpack dev server) and deployment server(IIS) for this Angular app are different, yet produce the same result, so it might not be a server config issue.
- Comparing a 200 response with 401 request, I see Bearer token working on both.
- Comparing a 200 response with 401 response, I see header CORS working on both.
- Since it gives 401, and doesn't seem to actually arrive within the Web API, it is something related to authentication. Yet I don't know much about this process at all. Any insight?
回答1:
I figured it out. Race condition. Bearer token is not available there yet when it try to retrieve it. By the time I manually do API call in REST client, the token is available. Only if I have some subsequent API calls regardless of the first one, I would have identify this issue faster.
A simple timeout would demonstration that it works.
We will optimize the Bearer token storage and some cache management for a permanent solution.
来源:https://stackoverflow.com/questions/45927261/401-with-a-valid-bear-token-what-could-go-wrong