首页 文章

如何在代表flow的Azure AD中使用cookie来获取访问令牌到另一个资源

提问于
浏览
0

我有两个使用相同azure活动目录的应用程序 . App A和App B.

App 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,
            }        

        });

我通过获取令牌来获取对应用程序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"]);

我也使用cookies登录到应用程序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);

现在我的问题类似于我的访问令牌即将到期的其他问题,但我对应用程序a的登录cookie仍然有效,因此用户似乎记录正常,尽管他们在缓存中没有令牌 .

我已经跟着其他问题,看了我的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>();

这里的问题是我不知道如何将此令牌恢复到adal AuthenticationContext使用的默认TokenStore . 我们需要更深入的代码:

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

有没有一种方法可以让新的资源访问令牌返回到用户App B api调用的令牌库中,而没有有效的令牌/刷新令牌“代表用户”流程?

1 回答

  • 4

    如果丢失了访问令牌和刷新令牌,则必须将用户重定向到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;
        }
    }
    

    因此,如果在静默令牌获取失败的情况下抛出异常,只需吞下错误并将结果更改为401,这会触发OpenIdConnect中间件将用户发送到Azure AD .

    既然你有 AutomaticAuthenticate=true ,就应该这样做 .

相关问题