I\'ve followed the Quickstart in the documentation page and have a working configuration of three services (IdentityServer, one Api service, one ASPNET MVC application) usin
As an option to RenewTokens method from MVC Client example, I made one filter that makes the job automatically, when the token is about 10 minutes or less to expire.
public class TokenFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var expat = filterContext.HttpContext.Authentication.GetTokenAsync("expires_at").Result;
var dataExp = DateTime.Parse(expat, null, DateTimeStyles.RoundtripKind);
if ((dataExp - DateTime.Now).TotalMinutes < 10)
{
var disco = DiscoveryClient.GetAsync("http://localhost:5000/").Result;
if (disco.IsError) throw new Exception(disco.Error);
var tokenClient = new TokenClient(disco.TokenEndpoint, "clientId",
"clientSecret");
var rt = filterContext.HttpContext.Authentication.GetTokenAsync("refresh_token").Result;
var tokenResult = tokenClient.RequestRefreshTokenAsync(rt).Result;
if (!tokenResult.IsError)
{
var oldIdToken = filterContext.HttpContext.Authentication.GetTokenAsync("id_token").Result;
var newAccessToken = tokenResult.AccessToken;
var newRefreshToken = tokenResult.RefreshToken;
var tokens = new List
{
new AuthenticationToken {Name = OpenIdConnectParameterNames.IdToken, Value = oldIdToken},
new AuthenticationToken
{
Name = OpenIdConnectParameterNames.AccessToken,
Value = newAccessToken
},
new AuthenticationToken
{
Name = OpenIdConnectParameterNames.RefreshToken,
Value = newRefreshToken
}
};
var expiresAt = DateTime.Now + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
tokens.Add(new AuthenticationToken
{
Name = "expires_at",
Value = expiresAt.ToString("o", CultureInfo.InvariantCulture)
});
var info = filterContext.HttpContext.Authentication.GetAuthenticateInfoAsync("Cookies").Result;
info.Properties.StoreTokens(tokens);
filterContext.HttpContext.Authentication.SignInAsync("Cookies", info.Principal, info.Properties);
}
}
}
}
Usage:
[Authorize]
[TokenFilter]
public class HomeController : Controller
{}