認可コードフローの目的は、アクセストークンの認証コードを交換することです。この交換は、実際のアクセストークンがクライアントユーザーに公開されないように、ページを提供するサーバーと承認サーバーとの間で行われます。アクセストークンの保存方法? (Oauth 2、Auth code flow)
アクセストークンを取得したら、ページサーバーはそのトークンをどのように格納する必要がありますか?私はこのコードの一部が存在するPluralsightの例から学んでいた:これはクッキーに保存されたアクセストークンがある場合、各要求はチェックするようになります
public static HttpClient GetClient()
{
HttpClient client = new HttpClient();
var accessToken = RequestAccessTokenAuthorizationCode();
client.SetBearerToken(accessToken);
client.BaseAddress = new Uri(IdentityConstants.API);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
private static string RequestAccessTokenAuthorizationCode()
{
// did we store the token before?
var cookie = HttpContext.Current.Request.Cookies.Get("ClientMVCCookie.AuthCode");
if (cookie != null && cookie["access_token"] != null && !string.IsNullOrEmpty(cookie["access_token"]))
{
return cookie["access_token"];
}
// no token found - request one
// we'll pass through the URI we want to return to as state
var state = HttpContext.Current.Request.Url.OriginalString;
var authorizeRequest = new IdentityModel.Client.AuthorizeRequest(
IdentityConstants.AuthEndoint);
var url = authorizeRequest.CreateAuthorizeUrl(IdentityConstants.MVCClientSecret, "code", "management secret",
IdentityConstants.MVCAuthCodeCallback, state);
HttpContext.Current.Response.Redirect(url);
return null;
}
}
。そうでなければ、フローが開始される。コールバックは次のようになります。
public class CallbackController : Controller
{
// GET: STSCallback
public async Task<ActionResult> Index()
{
// get the authorization code from the query string
var authCode = Request.QueryString["code"];
// with the auth code, we can request an access token.
var client = new TokenClient(
IdentityConstants.TokenEndoint,
"mvc_client_auth_code",
IdentityConstants.MVCClientSecretAuthCode);
var tokenResponse = await client.RequestAuthorizationCodeAsync(
authCode,
IdentityConstants.MVCAuthCodeCallback);
// we save the token in a cookie for use later on
var cookie = Response.Cookies["ClientMVCCookie.AuthCode"];
cookie.Expires = DateTime.Now.AddMinutes(1);
cookie["access_token"] = tokenResponse.AccessToken;
// get the state (uri to return to)
var state = Request.QueryString["state"];
// redirect to the URI saved in state
return Redirect(state);
}
}
アクセス許可トークンをCookieに格納しても、認証コードフロー全体の目的を逸脱しませんか。クッキーはクライアントブラウザに送信され、クライアントに公開されますか?何か不足していますか?これは、トークンを格納する正しい方法ではなく、どのように格納する必要がありますか?
私はその部分を完全に理解しています。私は質問に含まれている例が正しいかどうか尋ねていた。この例では、ASP.NET MVCサーバーでCookieを使用しています。私は、トークンを含むこのクッキーが、トークンを公開するブラウザに渡されると考えました(それは?)。 – BodzioSamolot
このコードは説明なしに分析するのは難しいです。認証サーバーの一部ですか?クライアント? –
これは、mvcサーバー側のアプリケーションです。コールバックコントローラは、アクセストークンの認証サーバーと認証コードを交換します。次に、トークンをクッキーに含めます。これは私が見つけた例です。トークンをブラウザに公開することはできません。これがなぜクッキーに保存されるのか私を甘やかす理由です。それは、それがブラウザへのその後の要求と共に移動することを意味しないのですか? – BodzioSamolot