azure - 如何代表流将 cookie 与 Azure AD 结合使用来获取其他资源的访问 token

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

我有两个应用程序使用相同的 Azure Active Directory。应用程序 A 和应用程序 B。

应用程序 A 使用

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {

            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            ClientId = Configuration["Authentication:AzureAd:ClientId"],
            Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
            ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"],
            CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],                      
            ResponseType = OpenIdConnectResponseType.CodeIdToken, 
            GetClaimsFromUserInfoEndpoint = true,
            SignInScheme = "Cookies",
            SaveTokens = true,                                                              
            Events = new OpenIdConnectEvents
            {
                OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
            }        

        });

我通过获取 token 来获取对应用程序 B api 服务资源的访问权限:

private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
    {         
        string userObjectId = (context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
        ClientCredential clientCred = new ClientCredential(Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]);
        AuthenticationContext authContext = new AuthenticationContext(Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]);
        AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
            context.ProtocolMessage.Code, new Uri(context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]), clientCred, Configuration["Authentication:AzureAd:GraphResourceId"]);

我还使用 cookie 登录应用程序 A:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationScheme = "Cookies",
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            SlidingExpiration = true,
            ExpireTimeSpan = TimeSpan.FromHours(1),
            Events = new CookieAuthenticationEvents()
            {
                OnSignedIn = OnSignedIn,
                OnSigningIn = OnSigningIn,
                OnValidatePrincipal = OnValidatePrincipal                    
            }
        });
/* Account Controller SignIn() */
return Challenge(
            new AuthenticationProperties {
                AllowRefresh = true,
                IsPersistent = true,                                      
                RedirectUri = "/" }, OpenIdConnectDefaults.AuthenticationScheme);

现在我的问题与其他问题类似,我的访问 token 即将过期,但我的应用程序 a 的登录 cookie 仍然有效,因此用户似乎登录正常,尽管他们在缓存中没有 token 。

我遵循了其他问题并查看了我的 Cookie 事件

 Task OnValidatePrincipal(CookieValidatePrincipalContext arg) {

     var http = new HttpClient();
                var uri = "https://login.microsoftonline.com/<tenant>/oauth2/token";
                var client_id = "<my_client_id>";
                var scope = "https://graph.microsoft.com/mail.read";
                var refresh_token = "<saved_refresh_token_in_cookie_if_SaveTokens = true>";
                var redirect_uri = "https://localhost:20352/";
                var grant_type = "refresh_token";
                var client_secret = "<client_secret_from_azure>";
                var body = new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>("client_id", client_id),
                            new KeyValuePair<string, string>("scope", scope),
                            new KeyValuePair<string, string>("refresh_token", refresh_token),
                            new KeyValuePair<string, string>("redirect_uri", redirect_uri),
                            new KeyValuePair<string, string>("grant_type", grant_type),
                            new KeyValuePair<string, string>("client_secret", client_secret)
                        };

                var content = new FormUrlEncodedContent(body);

                var result = http.PostAsync(uri, content).Result;
                var stringContent = result.Content.ReadAsStringAsync().Result;

                JObject jobject = JObject.Parse(stringContent);
                var token = jobject["access_token"].Value<string>();

这里的问题是我不知道如何将此 token 返回到 adal AuthenticationContext 使用的默认 TokenStore 中。我们有更深层次的代码需要从中提取:

_authenticationResult = await authContext.AcquireTokenSilentAsync(_authConfigOptions.AzureAd.WebserviceAppIdUri.ToString(), credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

有没有办法让我可以在没有有效 token /刷新 token “代表用户”流程的情况下,将新的资源访问 token 放回到 token 库中以供用户 App B api 调用?

最佳答案

如果丢失访问 token 和刷新 token ,则必须将用户重定向到 Azure AD 以再次进行身份验证。他们可能仍在那里进行身份验证,因此他们只是与授权代码一起重定向回您的应用程序。

在我的一个项目中,我制作了一个异常过滤器来执行以下操作:

public void OnException(ExceptionContext filterContext)
{
    //If the error is a silent token acquisition exception from ADAL..
    if(filterContext.Exception is AdalSilentTokenAcquisitionException)
    {
        //Instead of the usual procedure, return a 401 which triggers the OpenIdConnect middleware redirection
        filterContext.Result = new HttpUnauthorizedResult();
        filterContext.ExceptionHandled = true;
    }
}

因此,如果静默 token 获取失败引发异常,只需吞下错误并将结果更改为 401,这会触发 OpenIdConnect 中间件将用户发送到 Azure AD。

由于您有 AutomaticAuthenticate=true,它应该执行此操作。

关于azure - 如何代表流将 cookie 与 Azure AD 结合使用来获取其他资源的访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41765829/

相关文章:

django - 如何在 Azure Kubernetes 服务上向公众隐藏 Django Admin,同时通过后门保持访问

Azure 服务总线 1.1 无法启动

c# - Azure 队列客户端依赖项注入(inject)

asp.net - Azure Active Directory 回复 URL 重定向到根

openid - Google OpenID 登录 - x-has-session 如何工作?

azure - Azure Synapse 工作区中列出了重复的用户

c# - Asp.Net Core 3(Blazor 客户端)构建失败

.net - 如何在.net core的startup.cs中获取主机名

asp.net-core - 如何在 Swagger UI 中包含 X-XSRF-TOKEN header ?

ruby - 如何使用 omniauth-openid gem 使 OpenID 登录安全?