[英]How to pass Authorization token from one webapi to other webapi?
I have configured two applications
in Azure AD. 我已经在Azure AD中配置了两个
applications
。 One is a Web API called app-A
and another is a Web API called app-B
. 一个是称为
app-A
的Web API,另一个是称为app-B
的Web API。
how to I generate a token at
app-A
using client credentials token and pass that token toapp-B
?如何使用客户端凭据令牌在
app-A
处生成令牌并将该令牌传递给app-B
?
If I understand your question correct you want to forward Authorization token from one Web API service to another Web API? 如果我的问题理解正确,那么您要将授权令牌从一个Web API服务转发到另一个Web API?
This is how I did it: 这是我的方法:
HierarchicalLifetimeManager
. HierarchicalLifetimeManager
。 app-a
and put it into the session context app-a
的请求中提取所有标头,并将其放入会话上下文中 HttpClient
to insert the cookies before calling app-b
. app-b
之前,使用HttpClient
插入cookie。 If you want to, you could also just extract the token only instead of all cookies. 如果需要,也可以只提取令牌而不是提取所有cookie。
SessionContext 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 Cookie提取器
/// <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 Unity配置
// 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.