【发布时间】:2021-01-03 12:52:08
【问题描述】:
我有一个 ASP.NET Core Web 应用程序,它访问一个 Web 服务端点,然后该 Web 服务向我的应用程序发送请求。
当我点击那个 web 服务端点时,我会收到一个带有字符串值和到期时间的 web 令牌。我将它保存在 HttpContext 中以供以后使用。
当网络服务向我的应用程序发送请求时,它发送的令牌与我收到的相同。
我需要确保验证令牌与我最初在第一次请求时收到的令牌相同。
我不想将此令牌存储在我的数据库中,因为显然我必须搜索令牌列表,并且我可以使用不同的令牌,并且只要它存在于数据库中,这将起作用。
我已尝试将令牌存储在HttpContext.Items
但是,根据服务对我的应用程序的请求,令牌消失了。这些项目没有令牌,因为我怀疑它是不同的Httpcontext。
在 ASP .NET Framework 上,我可以将其存储为
HttpContext.Application["WebServiceToken"] = token;
但是,我在 ASP .NET Core 上找不到这样的替代方案。
public async Task<IActionResult> Index()
{
if (serviceTokenService.TokenAlreadyExists())
{
return ArrivalsFromDatabase();
}
var exampleDate = new DateTime(2016, 3, 10);
var callback = Url.Action("ReceiveArrivalInfoFromService", "Home", null, Request.Scheme);
bool success = false;
var token = await this.serviceTokenService.GetServiceToken(configuration["WebServiceUrl"], exampleDate, callback);
if (!String.IsNullOrEmpty(token.Token))
{
this.serviceTokenService.SavesToken(token);
success = true;
}
if (!success)
{
return View("Error");
}
return ArrivalsFromDatabase();
}
public async Task<IActionResult> ReceiveArrivalInfoFromService()
{
var serviceToken = serviceTokenService.ReadToken();
var isTokenValid = serviceTokenService.ValidateToken(Request, serviceToken);
if (isTokenValid)
{
var arrivals = serviceTokenService.CollectArrivals(Request);
await arrivalService.AddRangeAsync(arrivals);
}
这是我的 Servicetoken 服务,也是我的令牌方法所在。
public class ServiceTokenService : IServiceTokenService
{
private readonly IHttpContextAccessor httpContextAccessor;
public ServiceTokenService(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
public void SavesToken(ServiceToken token)
{
httpContextAccessor.HttpContext.Items["ServiceToken"] = token;
}
public ServiceToken ReadToken()
{
if (httpContextAccessor.HttpContext.Items["ServiceToken"] != null)
{
return httpContextAccessor.HttpContext.Items["ServiceToken"] as ServiceToken;
}
return null;
}
}
在 ReadToken 上它返回 null。之前收到的令牌丢失了,因为它在 HttpContext.items 中不存在。
【问题讨论】:
-
您使用的是什么类型的令牌?
-
具有 Guid 字符串和到期日期的自定义项
-
您可以始终将令牌存储为会话或 cookie,然后使用一些中间件将令牌添加到每个请求中。
标签: c# asp.net-core asp.net-web-api token httpcontext