Azure活动目录单租户单独的webapi应用程序访问

时间:2016-08-13 02:11:06

标签: azure asp.net-core azure-active-directory openid-connect

我有两个Azure Active Directory应用程序设置。

为简洁起见,App-AApp-B

A是一个webapp,在B发布到somedomain.azurewebsites.net时会在localhost上运行并公开webapi。

两者都设置为:

app.UseCookieAuthentication(new CookieAuthenticationOptions(){
    AutomaticAuthenticate = true,
    AutomaticChallenge = true
});

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    ClientId = Configuration["Authentication:AzureAd:ClientId"],
    Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
    CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],                
    TokenValidationParameters = new TokenValidationParameters{                    
        SaveSigninToken = true,
    },
    Events = new OpenIdConnectEvents{
        OnAuthenticationFailed = OnAuthenticationFailed,
        OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
        OnMessageReceived = OnMessageReceived,
        OnTicketReceived = OnTicketRecieved,
        OnTokenValidated = OnTokenValidated,
        OnUserInformationReceived = OnUserInformationReceived,
        OnTokenResponseReceived = OnTokenResponseRecieved,
        OnRemoteFailure = OnRemoteFailure
    }
});

现在App-B允许App-A的委派权限,反之亦然。我还将App-A的回复网址添加到App-Bhttp://localhost:5000/signin-oidc

App-A在尝试访问[Authorize]控制器时,他们必须登录并被路由到Microsoft的登录页面。现在,在此登录页面上,如何立即允许从第一次登录访问App-B web-api?我是否可以通过初始握手/登录方式以某种方式发送访问令牌,或者是进行另一次往返以收集类似于下方的某些令牌的正确方法?

如果我需要进行另一次往返,是否有一个最新的示例代码块?我似乎无法让代码片段起作用。

我发现的所有例子都是:

private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context){
    var code = context.Code;
    ClientCredential credential = new ClientCredential(clientId, appKey);
    string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
    string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
    AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantID), new EFADALTokenCache(signedInUserID));
    AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceID);

但我甚至不认为code是上下文中的财产? 我此时正在使用最新版本的netcore。

我的主要目标是使用从初次登录时以某种方式检索到的令牌对HttpClient端点进行App-B调用。

1 个答案:

答案 0 :(得分:0)

上下文对象已更改:

  context.ProtocolMessage.Code

代码流将自动将访问令牌存储在缓存中,您可以使用以下方法检索缓存:

  authContext.AcquireTokenSilentAsync

使用最新的.netcore更新了示例:

https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore/tree/master/WebApp-WebAPI-OpenIdConnect-DotNet