问题
I have configured two applications
in Azure AD. One is a Web API called app-A
and another is a Web API called app-B
.
how to I generate a token at
app-A
using client credentials token and pass that token toapp-B
?
回答1:
If I understand your question correct you want to forward Authorization token from one Web API service to another Web API?
This is how I did it:
- Create a session context that exists within the request context. This is done by using Unity and
HierarchicalLifetimeManager
. - Extract all headers from the request at
app-a
and put it into the session context - Using the
HttpClient
to insert the cookies before callingapp-b
.
If you want to, you could also just extract the token only instead of all cookies.
SessionContext
public class SessionContext
{
public string Token { get; private set; }
public CookieHeaderValue Cookies { get; private set; }
public void SetToken(string token)
{
if(Token != null)
throw new InvalidOperationException("Token is already set in this session.");
Token = token;
}
public void SetCookies(CookieHeaderValue cookies)
{
if (Cookies != null)
throw new InvalidOperationException("Cookies is already set in this session.");
Cookies = cookies;
}
}
CookieFetcher
/// <summary> ActionFilter to extract all cookie and add it to the <see cref="SessionContext"/>. </summary>
public class CookieFetcherAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var cookies = actionContext.Request.Headers.GetCookies().SingleOrDefault();
if (cookies == null)
return;
var sessionContext = actionContext.Request.GetDependencyScope().GetService<SessionContext>();
sessionContext.SetCookies(cookies);
}
}
Unity config
// Gets a new TokenProvider per request
container.RegisterType<SessionContext>(new HierarchicalLifetimeManager());
Client
public class Client
{
private CookieHeaderValue Cookies => sessionContext.Cookies;
public Client(SessionContext sessionContext)
{
this.sessionContext = sessionContext;
}
private HttpClient CreateHttpClient()
{
// If cookie/sessionId based authentication is used.
if (Cookies != null)
{
handler.CookieContainer = ConvertToCookieContainer(Cookies, baseUri.GetRootHostName());
handler.UseCookies = true;
}
var client = new HttpClient(handler, true);
client.BaseAddress = baseUri;
return client;
}
private static CookieContainer ConvertToCookieContainer(CookieHeaderValue cookies, string cookiePath)
{
var container = new CookieContainer();
foreach (var cookie in cookies.Cookies)
{
container.Add(new Cookie(cookie.Name, cookie.Value, "/", cookiePath));
}
return container;
}
}
来源:https://stackoverflow.com/questions/39915533/how-to-pass-authorization-token-from-one-webapi-to-other-webapi