【发布时间】:2019-01-16 09:48:35
【问题描述】:
我正在从事两个项目。一种是使用 ASP.NET MVC,另一种是使用 ASP.NET WebAPI。我们的客户端想要实现负载均衡,但他们担心一旦完成,它可能会影响登录功能,因为用户的身份验证令牌可能不会在服务器之间共享。我被指派研究这个问题。谁能告诉我是否可以在服务器之间同步和共享用户的登录状态和身份验证令牌以实现负载平衡?如果是这样,怎么做?这是ASP.NET WebAPI项目中登录功能的代码。
public async Task<IHttpActionResult> Login(LoginModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Invoke the "token" OWIN service to perform the login (POST /api/token)
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("client_id", APP_CLIENT_ID),
new KeyValuePair<string, string>("username", model.Username),
new KeyValuePair<string, string>("password", model.Password)
};
var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams);
var baseUrl = apiConfiguration.Host;
var getTokenUrl = $"{baseUrl}/token";
var tokenServiceResponse = await httpClient.PostAsync(getTokenUrl, requestParamsFormUrlEncoded);
if (!tokenServiceResponse.IsSuccessStatusCode)
{
// Log response
if (tokenServiceResponse.StatusCode == HttpStatusCode.NotFound)
{
log.ErrorFormat("Can not get token from url: {0}", getTokenUrl);
return BadRequest(SERVER_ERROR_MESSAGE);
}
else
{
string content = await tokenServiceResponse.Content.ReadAsStringAsync();
if (tokenServiceResponse.StatusCode == HttpStatusCode.InternalServerError)
{
log.Error(content);
return BadRequest(SERVER_ERROR_MESSAGE);
}
else
{
log.InfoFormat("Get token fail request fail | RESPONE - StatusCode: {0} - Reason: {1} - Content: {2}", tokenServiceResponse.StatusCode, tokenServiceResponse.ReasonPhrase, content);
return BadRequest(INVALID_USER_DATA_MESSAGE);
}
}
}
var result = ResponseMessage(tokenServiceResponse);
var user = await userManager.FindByNameAsync(model.Username);
if (user == null || user.IsDeleted)
{
log.InfoFormat("Invalid user data. Username: {0}", model.Username);
return BadRequest(INVALID_USER_DATA_MESSAGE);
}
else if (user.AccountBlocked == true)
{
log.InfoFormat("The account {0} is blocked", model.Username);
return BadRequest(ACCOUNT_IS_BLOCKED_MESSAGE);
}
var userId = user.Id;
accountNotificationService.LogIn(userId, result.Response.IsSuccessStatusCode, APP_CLIENT_ID);
return result;
}
这是 ASP.NET MVC 项目中登录功能的代码。
public async Task<IHttpActionResult> Login(LoginModel model)
{
if (model == null)
{
return this.BadRequest("Invalid user data");
}
// Invoke the "token" OWIN service to perform the login (POST /api/token)
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("client_id", APP_CLIENT_ID),
new KeyValuePair<string, string>("username", model.Username),
new KeyValuePair<string, string>("password", model.Password)
};
try
{
var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams);
var tokenServiceResponse = await new HttpClient().PostAsync(
string.Format("{0}/Token", Config.Application.Host), requestParamsFormUrlEncoded);
var result = this.ResponseMessage(tokenServiceResponse);
if (!result.Response.IsSuccessStatusCode)
{
return this.BadRequest("Credentials are incorrect");
}
var user = result.Response.IsSuccessStatusCode ? await accountService.FindUser(model.Username, model.Password) : null;
if (user == null)
{
return this.BadRequest("Credentials are invalid");
}
else if (user.IsDeleted)
{
return this.BadRequest("This user does not exists");
}
if (user.AccountBlocked == true)
{
return this.BadRequest("This account is blocked");
}
notificationService.LogIn(user?.Id, result.Response.IsSuccessStatusCode, APP_CLIENT_ID);
return result;
}
catch (Exception ex)
{
ErrorLogging.LogError(ex, "Error in Login");
return BasicResponse(new ResultModel
{
Success = false,
ResponseCode = System.Net.HttpStatusCode.InternalServerError,
Message = Constants.ErrorMessageCategory.General
});
}
}
【问题讨论】:
-
This post 会有所帮助。阅读答案s 和 cmets。呵呵..
标签: c# asp.net-mvc asp.net-web-api load-balancing