2015-07-28 17 views
6

Ho recentemente installato IdentityServer v3 e sta funzionando come un sogno, tuttavia ho problemi con il middleware OWIN.Aggiornare i token utilizzando il middleware owin e IdentityServer v3

Vorrei utilizzare il flusso ibrido in modo da poter aggiornare i token nel back-end senza che l'utente debba reindirizzare nuovamente a IdentityServer per ottenere un nuovo token di accesso ogni 5 minuti (che è anche dispari visto che ha un durata di 1 ora sul server).

Sto usando la seguente configurazione all'avvio e sto ottenendo i token bene, ma non sembra mai provare ad aggiornare il token di accesso una volta scaduto. Ho bisogno di qualche logica personalizzata da qualche parte per aggiornare i miei token?

 app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions 
     { 
      ClientId = clientId, 
      ClientSecret = clientSecret, //Not sure what this does? 

      Authority = "https://auth.example.com", 

      RedirectUri = "http://website.example.com", 
      PostLogoutRedirectUri = "http://website.example.com", 

      ResponseType = "code id_token token", 
      Scope = "openid profile email write read offline_access", 

      SignInAsAuthenticationType = "Cookies", 

      Notifications = new OpenIdConnectAuthenticationNotifications 
      { 
       AuthorizationCodeReceived = async n => 
       { 
        // filter "protocol" claims 
        var claims = new List<Claim>(from c in n.AuthenticationTicket.Identity.Claims 
               where c.Type != "iss" && 
                 c.Type != "aud" && 
                 c.Type != "nbf" && 
                 c.Type != "exp" && 
                 c.Type != "iat" && 
                 c.Type != "nonce" && 
                 c.Type != "c_hash" && 
                 c.Type != "at_hash" 
               select c); 

        // get userinfo data 
        var userInfoClient = new UserInfoClient(
         new Uri(n.Options.Authority + "/connect/userinfo"), 
         n.ProtocolMessage.AccessToken); 

        var userInfo = await userInfoClient.GetAsync(); 
        userInfo.Claims.ToList().ForEach(ui => claims.Add(new Claim(ui.Item1, ui.Item2))); 

        // get access and refresh token 
        var tokenClient = new OAuth2Client(
         new Uri(n.Options.Authority + "/connect/token"), 
         clientId, 
         clientSecret); 

        var response = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri); 

        claims.Add(new Claim("access_token", response.AccessToken)); 
        claims.Add(new Claim("expires_at", DateTime.UtcNow.AddSeconds(response.ExpiresIn).ToLocalTime().ToString(CultureInfo.InvariantCulture))); 
        claims.Add(new Claim("refresh_token", response.RefreshToken)); 
        claims.Add(new Claim("id_token", n.ProtocolMessage.IdToken)); 

        //Does this help? 
        n.AuthenticationTicket.Properties.AllowRefresh = true; 

        n.AuthenticationTicket = new AuthenticationTicket(
         new ClaimsIdentity(
          claims.Distinct(new ClaimComparer()), 
          n.AuthenticationTicket.Identity.AuthenticationType), 
         n.AuthenticationTicket.Properties); 
       }, 

       RedirectToIdentityProvider = async n => 
       { 
        // if signing out, add the id_token_hint 
        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) 
        { 
         var id = n.OwinContext.Authentication.User.FindFirst("id_token"); 

         if (id != null) 
         { 
          var idTokenHint = id.Value; 
          n.ProtocolMessage.IdTokenHint = idTokenHint; 
         } 
        } 
       } 
      } 
     }); 

Sto anche utilizzando la seguente nel mio ApiClient (RestSharp), che parla al mio api risorsa

public class MyTokenAuthenticator : IAuthenticator 
{ 
    public void Authenticate(IRestClient client, IRestRequest request) 
    { 
     var tokenClaim = ClaimsPrincipal.Current.Claims.FirstOrDefault(c => c.Type.Equals("access_token")); 

     if (tokenClaim != null && !String.IsNullOrWhiteSpace(tokenClaim.Value)) 
      request.AddHeader("Authorization", String.Format("Bearer {0}", tokenClaim.Value)); 
    } 
} 

risposta

1

sono stato in grado di ottenere un token di aggiornamento e quindi utilizzarlo per ottenere un nuovo accesso token: Ho seguito una logica simile alla tua per ottenere un token. ho creato il seguente metodo che ho chiamato ogni volta che avevo bisogno di un token:

private static async Task CheckAndPossiblyRefreshToken(ClaimsIdentity id) 
    { 
     var clientName = "Myhybridclient"; 
     // check if the access token hasn't expired. 
     if (DateTime.Now.ToLocalTime() >= 
      (DateTime.Parse(id.FindFirst("expires_at").Value))) 
     { 
      // expired. Get a new one. 
      var tokenEndpointClient = new OAuth2Client(
       new Uri(Constants.TokenEndpoint), 
       clientName, 
       "secret"); 

      var tokenEndpointResponse = 
       await tokenEndpointClient 
       .RequestRefreshTokenAsync(id.FindFirst("refresh_token").Value); 

      if (!tokenEndpointResponse.IsError) 
      { 
       // replace the claims with the new values - this means creating a 
       // new identity!        
       var result = from claim in id.Claims 
          where claim.Type != "access_token" && claim.Type != "refresh_token" && 
            claim.Type != "expires_at" 
          select claim; 

       var claims = result.ToList(); 

       claims.Add(new Claim("access_token", tokenEndpointResponse.AccessToken)); 
       claims.Add(new Claim("expires_at", 
          DateTime.Now.AddSeconds(tokenEndpointResponse.ExpiresIn) 
          .ToLocalTime().ToString())); 
       claims.Add(new Claim("refresh_token", tokenEndpointResponse.RefreshToken)); 

       var newIdentity = new ClaimsIdentity(claims, "Cookies"); 
       var wrapper = new HttpRequestWrapper(HttpContext.Current.Request); 
       wrapper.GetOwinContext().Authentication.SignIn(newIdentity); 
      } 
      else 
      { 
       // log, ... 
       throw new Exception("An error has occurred"); 
      } 
     } 
    } 
+1

A mio parere aspettando ora locale è più grande o uguale accesso in tempo token di scadenza non è la migliore idea. Immagina una situazione in cui questa condizione considererà AccessToken valido solo pochi millisecondi prima della scadenza. Se invierai tale AccessToken ad altri servizi, potrebbe essere rifiutato perché è scaduto nel frattempo. Quando aggiungi il reclamo "expires_at" potresti anche aggiungere qualcosa come "refresh_at" come mezzo intervallo tra ora e valore "expires_at". Tale soluzione permetterebbe di assicurarsi che il token di accesso non scada prima che tu possa usarlo. – Gilmor

+0

Di solito permetto, attraverso la configurazione, I minuti per verificare se il token è scaduto: ad esempio se il token scade in meno di 1 minuto, andrò avanti e lo aggiornerò. – jahansha

Problemi correlati