多くの人がこの実装に同意しない可能性があることは知っていますが、トークンへの JavaScript アクセスを防ぐために、http 専用コンテナー内に jwt を格納しようとしています。ユーザーが認証されると、.NET アプリケーションは Identity Server から Jwt を取得します。次に、http のみの Cookie を作成し、その中に jwt を保存して、承認のために API に送信します。
この Cookie を API に送信する方法と、API を取得して Cookie 内の jwt にアクセスし、Identity Server を使用して認証する方法を知りたいと思いました (Identity Server のイントロスペクション エンドポイントを使用して、 jwt は有効です)。
現在、RestSharp を使用してアプリケーションからリクエストを送信しようとしています。
var oClient = new RestClient("http://localhost:52298/stockcontrol/availablestock");
var oContainer = new CookieContainer();
var oRequest = new RestRequest();
oRequest.Method = Method.GET;
var oCookie = new Cookie("Jwt", sJwt) { HttpOnly = true, Expires = DateTime.Now.AddMinutes(10), Domain = "test" };
oContainer.Add(oCookie);
oClient.CookieContainer = oContainer;
var oResponse = oClient.Execute(oRequest);
これは、API で jwt を認証するために使用しようとしているコードです。
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
Provider = new CookieAuthenticationProvider()
{
OnValidateIdentity = async context =>
{
if (context?.Identity?.IsAuthenticated ?? false)
{
var accessToken = context?.Identity?.Claims?.FirstOrDefault(x => x.Type == "access_token")?.Value;
if (accessToken == null)
{
context?.RejectIdentity();
}
else
{
var client = new IntrospectionClient(
sISUrl + "connect/introspect",
sISClientName,
sISClientSecret); // auth as scope, not client!
var validationResult = await client.SendAsync(new IntrospectionRequest()
{
Token = accessToken
});
if (validationResult.IsError || !validationResult.IsActive)
{
context?.RejectIdentity();
}
}
}
}
}
});