2017-05-25 27 views
1

我正在使用Identity Server 4的.net核心。我有一個Web API,以及一個訪問api上的安全端點的MVC應用程序。這是在安裝到IdentityServer快速入門很相似:如何在IdentityServer 4中使用'refresh_token'?

https://github.com/IdentityServer/IdentityServer4.Samples/tree/release/Quickstarts/6_AspNetIdentity

我發現我的access_tokens即將到期,我想了解如何重新談判refresh_tokens

舉個例子下面的代碼(從快速啓動here截取):

public async Task<IActionResult> CallApiUsingUserAccessToken() 
    { 
     var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token"); 

     var client = new HttpClient(); 
     client.SetBearerToken(accessToken); 
     var content = await client.GetStringAsync("http://localhost:5001/identity"); 

     ViewBag.Json = JArray.Parse(content).ToString(); 
     return View("json"); 
    } 

如果access_token已經期滿,它將失敗,401響應。是否有一個內置的機制可以使用refresh_token重新協商access_token

回答

2

系統中沒有內置刷新access_token。但是,您可以使用IdentityModel程序包請求帶有refresh_token的新access_token

Client有一個屬性AllowOfflineAccess你應該在IdentityServer中設置爲true。請注意,這不是而是適用於隱式/客戶端憑據流。

  • 始終刷新在進行調用受保護資源
  • 檢查當前access_token即將通過檢查其壽命到期的ACCESS_TOKEN之前,並要求新access_tokenrefresh_token(個人喜好)
  • 等待API返回401廣告請求新access_tokenrefresh_token

在此之前的代碼,你可以檢查access_token壽命和/或請求新access_token

var discoveryResponse = await DiscoveryClient.GetAsync("IdentityServer url"); 
if (discoveryResponse.IsError) 
{ 
    throw new Exception(discoveryResponse.Error); 
} 

var tokenClient = new TokenClient(discoveryResponse.TokenEndpoint, "ClientId", "ClientSecret"); 
// This will request a new access_token and a new refresh token. 
var tokenResponse = await tokenClient.RequestRefreshTokenAsync(await httpContext.Authentication.GetTokenAsync("refresh_token")); 

if (tokenResponse.IsError) 
{ 
    // Handle error. 
} 

var oldIdToken = await httpContext.Authentication.GetTokenAsync("id_token"); 

var tokens = new List<AuthenticationToken> 
{ 
    new AuthenticationToken 
    { 
     Name = OpenIdConnectParameterNames.IdToken, 
     Value = oldIdToken 
    }, 
    new AuthenticationToken 
    { 
     Name = OpenIdConnectParameterNames.AccessToken, 
     Value = tokenResult.AccessToken 
    }, 
    new AuthenticationToken 
    { 
     Name = OpenIdConnectParameterNames.RefreshToken, 
     Value = tokenResult.RefreshToken 
    } 
}; 

var expiresAt = DateTime.UtcNow.AddSeconds(tokenResult.ExpiresIn); 
tokens.Add(new AuthenticationToken 
{ 
    Name = "expires_at", 
    Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) 
}); 

// Sign in the user with a new refresh_token and new access_token. 
var info = await httpContext.Authentication.GetAuthenticateInfoAsync("Cookies"); 
info.Properties.StoreTokens(tokens); 
await httpContext.Authentication.SignInAsync("Cookies", info.Principal, info.Properties); 

來自並略作修改之前把這個包代碼服務:Source

+0

大。謝謝。這工作。 –

相關問題