Last active
July 23, 2017 12:13
-
-
Save gognjanovski/0f538ec686eecda43f14d8a57c763441 to your computer and use it in GitHub Desktop.
Renew access token method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Com.Example.Controllers | |
{ | |
[Authorize] | |
public class HomeController : Controller | |
{ | |
public HomeController() | |
{ | |
} | |
//Use Refresh Token to generate new Access Token | |
public async Task<AccessTokenVM> GetNewAccessToken() { | |
var client = new DiscoveryClient("http://localhost:5000"); | |
var disco = await client.GetAsync(); | |
if (disco.IsError) throw new Exception(disco.Error); | |
//Connect to token endpoint (Security Server) | |
var tokenClient = new TokenClient(disco.TokenEndpoint, "<clientId>", "<clientSecret>"); | |
//Get Refresh Token | |
var rt = await HttpContext.Authentication.GetTokenAsync("refresh_token"); | |
//Get new Access Token | |
var tokenResult = await tokenClient.RequestRefreshTokenAsync(rt); | |
if (!tokenResult.IsError) | |
{ | |
var old_id_token = await HttpContext.Authentication.GetTokenAsync("id_token"); | |
var new_access_token = tokenResult.AccessToken; | |
var new_refresh_token = tokenResult.RefreshToken; | |
//Store the tokens | |
var tokens = new List<AuthenticationToken>(); | |
tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.IdToken, Value = old_id_token }); | |
tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.AccessToken, Value = new_access_token }); | |
tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.RefreshToken, Value = new_refresh_token }); | |
var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn); | |
tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) }); | |
var info = await HttpContext.Authentication.GetAuthenticateInfoAsync("Cookies"); | |
info.Properties.StoreTokens(tokens); | |
await HttpContext.Authentication.SignInAsync("Cookies", info.Principal, info.Properties); | |
return new AccessTokenVM { Success = true, AccessToken = new_access_token, ExpiresAt = expiresAt}; | |
} | |
return new AccessTokenVM { Success = false, Error = tokenResult.Error }; | |
} | |
//Return the initial SPA (single page application) view | |
public async Task<ActionResult> Index() | |
{ | |
... | |
} | |
[HttpPost] | |
public async Task LogOff() | |
{ | |
... | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment