public async Task <IActionResult> Refresh(string token) { if (String.IsNullOrWhiteSpace(token) && _authOptions.AddJwtToSession) { token = HttpContext.Session.GetString("auth-jwt"); } if (String.IsNullOrWhiteSpace(token)) { _logger.LogInformation($"Token refresh failed. No token found in query params or session."); return(BadRequest()); } var jwt = new JwtSecurityToken(token); if (!String.IsNullOrWhiteSpace(_authOptions.JwtAudience) && !jwt.Audiences.FirstOrDefault().StartsWith(_authOptions.JwtAudience)) { _logger.LogInformation($"Token refresh failed. Token audience not valid."); return(BadRequest()); } var newToken = await _tokenRefreshHandler.HandleRefreshAsync(token); if (newToken != null && _authOptions.AddJwtToSession) { HttpContext.Session.SetString("auth-jwt", newToken); } return(Ok(newToken)); }
public void Setup(CookieAuthenticationOptions options) { options.AccessDeniedPath = new PathString($"/{_authOptions.AccessDeniedPath}"); options.Events = new CookieAuthenticationEvents { OnValidatePrincipal = async context => { string token = null; if (_authOptions.AddJwtCookie) { token = context.Request.Cookies["jwt"]; } if (_authOptions.AddJwtToSession) { token = context.HttpContext.Session.GetString("auth-jwt"); } if (_authOptions.AutomaticTokenRefresh) { // set token to newly received token token = await _tokenRefreshHandler.HandleRefreshAsync(token); } if (!string.IsNullOrWhiteSpace(token)) { if (_authOptions.AddJwtCookie) { context.Response.Cookies.Append("jwt", token); } if (_authOptions.AddJwtToSession) { context.HttpContext.Session.SetString("auth-jwt", token); } } }, OnRedirectToAccessDenied = context => { if (IsAjaxRequest(context.Request)) { context.Response.Headers["Location"] = context.RedirectUri; context.Response.StatusCode = 403; } else { context.Response.Redirect(new PathString($"/{_authOptions.AccessDeniedPath}")); } return(Task.FromResult <object>(null)); }, OnRedirectToLogin = context => { if (IsAjaxRequest(context.Request)) { context.Response.Headers["Location"] = context.RedirectUri; context.Response.StatusCode = 401; } else { var url = $"{_authOptions.ApiAuthUrl}?idp_url={_authOptions.ApiAuthIdpUrl}&sp_name={_authOptions.ApiAuthSpName}&sp_url={_authOptions.ApiAuthSpUrl}&client_redirect={_authOptions.ApplicationBaseUrl}/{_authOptions.TokenCallbackRoute}?returnUrl="; context.RedirectUri = Uri.EscapeUriString($"{url}{context.Request.Path}{context.Request.QueryString}"); context.Response.Redirect(context.RedirectUri); } context.HttpContext.Response.Cookies.Delete(CookieAuthenticationDefaults.CookiePrefix + AuthSchemes.CookieAuth); context.HttpContext.Response.Cookies.Delete(JWTTokenKeys.Cookie); return(Task.FromResult <object>(null)); }, }; }