2017-01-20 2 views
0

Ich habe zwei Anwendungen, die dasselbe azure Active Directory verwenden. App A und App B.So verwenden Sie Cookies mit Azure AD im Auftrag von Flow, um ein Zugriffstoken auf eine andere Ressource zu erhalten

App A verwendet

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

     }); 

Und ich erwerben einen Zugriff auf Anwendung B api-Service-Ressourcen durch die Token erwerben mit:

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"]); 

Ich bin auch mit Hilfe von Cookies App A anmelden in mit:

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); 

Nun mein Problem zu anderen ähnlich ist, wo mein Zugriffstoken läuft ab, aber mein Anmelde-Cookie für App a ist immer noch gültig, so dass der Benutzer ordnungsgemäß angemeldet zu sein scheint, obwohl er kein Token im Cache hat.

Ich habe Anzug anderer Fragen gefolgt und sah zu meinem Plätzchen Fall

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>(); 

Problem hier ist, ich weiß nicht, wie diese Token TokenStor zurück in den Standard zu bekommen, dass die adal AuthenticationContext verwendet. Wir haben Code tiefer, die aus ziehen muss:

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

Gibt es eine Weise, die ich in den tokenstore Token zurück für Benutzer App B api Anrufe eine neue Ressource Zugriff bekommen, ohne ein gültiges Token/Aktualisierungs-Token ‚im Namen des Benutzerflusses?

+0

Ohne Zugriffstoken oder Aktualisierungstoken, nein. Sie müssen sie senden, um sich in Azure AD zu authentifizieren. Aber sollten Sie nicht ein Refresh-Token im Cache haben? Die letzten 14 Tage (IIRC), also ist es nicht notwendig, die Weiterleitung zu machen. – juunas

+0

Nun, ich versuche, das Szenario zu behandeln, in dem App ein Cookie authentifiziert, aber aus welchem ​​Grund auch immer Zugriff/Aktualisierungstoken für Ressource B ungültig oder bereinigt ist. So Redirect zu reauthorize zieht aus dem Cookie und ermöglicht eine Passthrough Signing sie in App A, ohne ein Zugriffs-Token. Ich muss dann den Cookie löschen und umleiten, um damit umzugehen? – cjsmith

Antwort

2

Wenn Sie das Zugriffstoken und das Aktualisierungstoken verlieren, müssen Sie den Benutzer zur erneuten Authentifizierung an Azure AD umleiten. Möglicherweise werden sie dort noch authentifiziert, sodass sie zusammen mit dem Autorisierungscode zurück in Ihre App geleitet werden.

In einem meiner Projekte, die ich eine Ausnahme Filter aus, das dies tut:

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; 
    } 
} 

Also, wenn die Ausnahme ausgelöst wird, wo stille Token Erwerb fehlschlägt, nur den Fehler schlucken und das Ergebnis in eine, 401 ändern, die löst die OpenIdConnect-Middleware aus, um den Benutzer an Azure AD zu senden.

Da Sie AutomaticAuthenticate=true haben, sollte es dies tun.

+0

HttpUnauthorizedResult sollte für ASP.NET Core MVC nicht autorisiert sein. – KorsG

Verwandte Themen