如何将授权令牌从一个webapi传递到其他webapi?

时间:2016-10-07 10:54:23

标签: azure asp.net-web-api asp.net-web-api2

我在Azure AD中配置了两个applications。一个是名为app-A的Web API,另一个是名为app-B的Web API。

  

如何使用客户端凭据令牌在app-A生成令牌   并将该令牌传递给app-B

1 个答案:

答案 0 :(得分:1)

如果我理解您的问题是否正确,您希望将授权令牌从一个Web API服务转发到另一个Web API?

我就这样做了:

  • 创建请求上下文中存在的会话上下文。这是通过使用Unity和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;
    }
}