ASP.NET Web APIでOAuthを使用して、アプリケーションの呼び出し元にアクセストークンを返します。OAuth - 生成されたアクセストークンを読み取り、応答でクッキーを追加します。
OAuthAuthorizationServerProvider
からOAuthプロバイダクラスを継承し、ユーザがGrantResourceOwnerCredentials
関数内で認証されると、生成されたアクセストークンを読み取り、いくつかのsalt値を持つハッシュを作成してから、作成したハッシュをクッキーに追加します。
以下は、私のGrantResourceOwnerCredentials
機能の簡略化された定義です。
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType);
//Add claims required on client side.
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
//Generate the token behind the scene for given ticket
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
SetCsrfCookie(context);
}
private void SetCsrfCookie(OAuthGrantResourceOwnerCredentialsContext context)
{
var accessToken = "<READ THE GENERATED ACCESS TOKEN HERE>"; //<------ How?
if(string.IsNullOrEmpty(accessToken)) return;
var csrfToken = Helper.GetHash(accessToken);
context.Response.Cookies.Append("XSRF-TOKEN", csrfToken, new CookieOptions {HttpOnly = false});
}
私はここで2つの問題に直面しています。
- 最初は、上記のコードの
SetCsrfCookie
関数で生成されたアクセストークンを読み取る方法です。 - 生成されたCookieはクライアント側では受信されません。
は、私はいくつかのOwinMiddleware
継承されたクラスの応答を傍受するために、その可能性を知っているし、私は必要なCookieを生成し、応答に接続することができるかもしれませんが、最初に私はそれを試したことのない、第二に、それは良いオプションですいくつかの人々がOwinMiddleware
から派生することは良い習慣ではないことを示唆しているように、私のOAuthプロバイダクラスの中でこのケースを扱うことができます。