我的 Asp Net Core 应用程序使用 IIS 托管在 Amazon EC2 上。我通过实现 IDashboardAuthorizationFilter 添加了 HangFire 授权。我的客户端应用程序是一个 Angular 应用程序。从我的控制器(Asp Net Core 端),我通过 Response.Redirect 在 cookie 中传递承载令牌到 Hangfire 仪表板 url。
在本地托管的应用程序上,它运行得非常好,我的授权过滤器实现中的 Authorize 方法在请求中传递了 cookie。此外,HangFire 仪表板显示在浏览器的同一选项卡中。
但是,在 prod/qa 环境中,有两个问题:
从客户端发送到我的控制器 API 的原始 GET 请求返回状态 302,随后对 hangfire url 的请求变为 GET 请求而不是重定向。它开始解析 html(hangfire)并在开发控制台中抛出错误。
我的 HangFire Dashboard Authorize 方法在重定向到 hangfire url 之前获取没有我在控制器 API 中设置的 cookie 的请求。
请看下面我的代码:
MyAuthorizationFilter.cs
public class MyAuthorizationFilter: IDashboardAuthorizationFilter {
public bool Authorize(DashboardContext context) {
try {
var httpContext = context.GetHttpContext();
// If it is a request for localhost, allow it straightaway
if (httpContext.Request.Host.ToUriComponent().Contains(Constants.Localhost)) {
return true;
}
string accessToken = httpContext.Request.Cookies[Constants.HangFireTokenKey];
LogHelper.ApiLog("Access Token: " + accessToken, LoggerLevel.DEBUG);
if (string.IsNullOrEmpty(accessToken)) {
return false;
}
ClaimsPrincipal claimsPrincipal = Utils.ValidateToken(accessToken);
LogHelper.ApiLog("Claims Principal Claims: " + JsonConvert.SerializeObject(claimsPrincipal.Claims), LoggerLevel.DEBUG);
LogHelper.ApiLog("Allowed users: " + JsonConvert.SerializeObject(this._allowedUsers));
if (claimsPrincipal != null) {
string userEmail = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == "email")?.Value;
if (this._allowedUsers.Contains(userEmail)) {
return true;
}
}
return false;
} catch (Exception){
LogHelper.ApiLog("HangFire Exception:" + e);
return false;
}
}
MyController.cs API
[HttpGet("hangfireDashboard")]
public void ShowHangFireDashboard() {
try {
string token = Request.Headers["Authorization"];
if (null != token) {
// Set our Bearer token as a cookie for Dashboard redirect
// Hangfire sends this cookie to Authorize method of DashBoardAuthorizationFilter
Response.Cookies.Append(Constants.HangFireTokenKey, token, new CookieOptions { Expires = DateTime.Now.AddMinutes(Constants.HangFireCookieExpiryTimeInMinutes) });
Response.Redirect(this._configuration["HangFire:DashboardUrl"]);
}
} catch (Exception) {
throw;
}
}
My Angular Client side function - GET request to my hangfireDashboard API
/**
* Send request for HangFire Dashboard
*/
showHangFireDashboard() {
const apiUrl = this._apiUrl + Global.route.hangfireDashboard;
return this._httpClient.get(apiUrl);
}
从我的客户端到我的服务器的初始 GET 请求
上述请求 (/hangFire) 的预览,应该作为重定向而不是 GET
[更新]:开发控制台显示错误,因为它必须解析作为对 Hangfire GET 请求的响应的 html 标记(应该是重定向而不是 GET)