我在Azure AD中配置了两个applications
。一个是名为app-A
的Web API,另一个是名为app-B
的Web API。
如何使用客户端凭据令牌在
app-A
生成令牌 并将该令牌传递给app-B
?
答案 0 :(得分:1)
如果我理解您的问题是否正确,您希望将授权令牌从一个Web API服务转发到另一个Web API?
我就这样做了:
HierarchicalLifetimeManager
。app-a
处的请求中提取所有标头,并将其放入会话上下文HttpClient
之前使用app-b
插入Cookie。如果您愿意,您也可以只提取令牌而不是所有Cookie。
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配置
// Gets a new TokenProvider per request
container.RegisterType<SessionContext>(new HierarchicalLifetimeManager());
<强>客户端强>
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;
}
}