/// <summary> /// Exchanges the authorization code for a authorization token from the remote provider. /// </summary> /// <param name="context">The <see cref="OAuthCodeExchangeContext"/>.</param> /// <returns>The response <see cref="OAuthTokenResponse"/>.</returns> protected virtual async Task <OAuthTokenResponse> ExchangeCodeAsync(OAuthCodeExchangeContext context) { var tokenRequestParameters = new Dictionary <string, string>() { { "client_id", Options.ClientId }, { "redirect_uri", context.RedirectUri }, { "client_secret", Options.ClientSecret }, { "code", context.Code }, { "grant_type", "authorization_code" }, }; // PKCE https://tools.ietf.org/html/rfc7636#section-4.5, see BuildChallengeUrl if (context.Properties.Items.TryGetValue(OAuthConstants.CodeVerifierKey, out var codeVerifier)) { tokenRequestParameters.Add(OAuthConstants.CodeVerifierKey, codeVerifier !); context.Properties.Items.Remove(OAuthConstants.CodeVerifierKey); } var requestContent = new FormUrlEncodedContent(tokenRequestParameters !); var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); requestMessage.Content = requestContent; requestMessage.Version = Backchannel.DefaultRequestVersion; var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted); var body = await response.Content.ReadAsStringAsync(); return(response.IsSuccessStatusCode switch { true => OAuthTokenResponse.Success(JsonDocument.Parse(body)), false => PrepareFailedOAuthTokenReponse(response, body) });
public async void CreateTicketAsync_SendsTokenInfoRequest_ReturnsValidTokenInfo() { var handler = new TestMessageHandler(); var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new StringContent(TestHelpers.GetValidTokenInfoRequestResponse()) }; handler.Response = response; var client = new HttpClient(handler); var opts = new CloudFoundryOAuthOptions() { Backchannel = client }; var testHandler = GetTestHandler(opts); var identity = new ClaimsIdentity(); var payload = JsonDocument.Parse(TestHelpers.GetValidTokenInfoRequestResponse()); var tokens = OAuthTokenResponse.Success(payload); var resp = await testHandler.TestCreateTicketAsync(identity, new AuthenticationProperties(), tokens); Assert.NotNull(handler.LastRequest); Assert.Equal(HttpMethod.Post, handler.LastRequest.Method); Assert.Equal(opts.TokenInfoUrl.ToLowerInvariant(), handler.LastRequest.RequestUri.ToString().ToLowerInvariant()); Assert.Equal("testssouser", identity.Name); Assert.Equal(4, identity.Claims.Count()); identity.HasClaim(ClaimTypes.Email, "*****@*****.**"); identity.HasClaim(ClaimTypes.NameIdentifier, "13bb6841-e4d6-4a9a-876c-9ef13aa61cc7"); identity.HasClaim(ClaimTypes.Name, "testssouser"); identity.HasClaim("openid", string.Empty); }
async protected override Task <OAuthTokenResponse> ExchangeCodeAsync(String code, String redirectUri) { base.Request.Query.TryGetValue("state", out var value); base.Request.Query.TryGetValue("scope", out var scope); var tokenRequestParameters = new Dictionary <string, string>() { ["client_id"] = Options.ClientId, ["redirect_uri"] = redirectUri, ["client_secret"] = Options.ClientSecret, ["code"] = code, ["grant_type"] = "authorization_code", ["state"] = value, ["scope"] = scope, }; var requestContent = new FormUrlEncodedContent(tokenRequestParameters); var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.twitchtv.v5+json")); requestMessage.Content = requestContent; var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted); if (response.IsSuccessStatusCode) { var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Success(payload)); } else { var error = "OAuth token endpoint failure: " + await Display(response); return(OAuthTokenResponse.Failed(new Exception(error))); } }
/// <summary> /// 通过Authorization Code获取Access Token。 /// 重写改方法,QQ这一步用的是Get请求,base中用的是Post /// </summary> protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri) { var parameters = new Dictionary <string, string> { { "grant_type", "authorization_code" }, { "client_id", Options.ClientId }, { "client_secret", Options.ClientSecret }, { "code", code }, { "redirect_uri", redirectUri } }; var endpoint = QueryHelpers.AddQueryString(Options.TokenEndpoint, parameters); var response = await Backchannel.GetAsync(endpoint, Context.RequestAborted); if (response.IsSuccessStatusCode) { var payload = JObject.Parse(ConvertToJson(await response.Content.ReadAsStringAsync())); return(OAuthTokenResponse.Success(payload)); } else { return(OAuthTokenResponse.Failed(new Exception("获取QQ Connect Access Token出错。"))); } }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] OAuthCodeExchangeContext context) { using var request = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint) { Content = new FormUrlEncodedContent(new Dictionary <string, string> { ["client_id"] = Options.ClientId, ["redirect_uri"] = context.RedirectUri, ["client_secret"] = Options.ClientSecret, ["code"] = context.Code, ["grant_type"] = "authorization_code" }) }; using var response = await Backchannel.SendAsync(request, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving an access token: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } // Note: StackExchange's token endpoint doesn't return JSON but uses application/x-www-form-urlencoded. // Since OAuthTokenResponse expects a JSON payload, a response is manually created using the returned values. var content = QueryHelpers.ParseQuery(await response.Content.ReadAsStringAsync()); var copy = await CopyPayloadAsync(content); return(OAuthTokenResponse.Success(copy)); }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri) { var tokenRequestParameters = new Dictionary <string, string>() { { "client_id", Options.ClientId }, { "redirect_uri", redirectUri }, { "client_secret", Options.ClientSecret }, { "code", code }, { "grant_type", "authorization_code" }, }; var requestContent = new FormUrlEncodedContent(tokenRequestParameters); var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); requestMessage.Content = requestContent; var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted); if (response.IsSuccessStatusCode) { //이부분을 추가해주지 않으면 euc-kr 인코딩을 지원하지 않는다며 에러가 발생함. //Naver만 해당.. var result = await response.Content.ReadAsByteArrayAsync(); var payload = JObject.Parse(Encoding.UTF8.GetString(result)); return(OAuthTokenResponse.Success(payload)); } const string error = "OAuth token endpoint failure: "; return(OAuthTokenResponse.Failed(new Exception(error))); }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri) { var address = QueryHelpers.AddQueryString(Options.TokenEndpoint, new Dictionary <string, string> { ["app_id"] = Options.ClientId, ["app_secret"] = Options.ClientSecret, ["code"] = code, ["redirect_uri"] = redirectUri }); var request = new HttpRequestMessage(HttpMethod.Get, address); var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving the user profile: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); throw new HttpRequestException("An error occurred while retrieving the user profile."); } var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Success(payload)); }
private EHealthOAuthTokenResponse(JObject response) { var data = response.Value <JObject>("data"); AccessToken = data?.Value <string>("value"); TokenType = data?.Value <string>("name"); ExpiresIn = data?.Value <string>("expires_at"); Id = data?.Value <string>("id"); UserId = data?.Value <string>("user_id"); var details = data?.Value <JObject>("details"); RefreshToken = details?.Value <string>("refresh_token"); Scope = details?.Value <string>("scope"); Response = OAuthTokenResponse.Success(data ?? response); Response.AccessToken = Response.AccessToken ?? AccessToken; Response.TokenType = Response.TokenType ?? TokenType; Response.ExpiresIn = Response.ExpiresIn ?? ExpiresIn; Response.RefreshToken = Response.RefreshToken ?? RefreshToken; AccessToken = Response.AccessToken; TokenType = Response.TokenType; ExpiresIn = Response.ExpiresIn; RefreshToken = Response.RefreshToken; }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] OAuthCodeExchangeContext context) { var tokenRequestParameters = new Dictionary <string, string> { ["grant_type"] = "authorization_code", ["code"] = context.Code, ["redirect_uri"] = context.RedirectUri, ["client_id"] = Options.ClientId, ["client_secret"] = Options.ClientSecret, }; // PKCE https://tools.ietf.org/html/rfc7636#section-4.5, see BuildChallengeUrl if (context.Properties.Items.TryGetValue(OAuthConstants.CodeVerifierKey, out var codeVerifier)) { tokenRequestParameters.Add(OAuthConstants.CodeVerifierKey, codeVerifier !); context.Properties.Items.Remove(OAuthConstants.CodeVerifierKey); } using var request = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Content = new FormUrlEncodedContent(tokenRequestParameters); using var response = await Backchannel.SendAsync(request, Context.RequestAborted); if (!response.IsSuccessStatusCode) { await Log.ExchangeCodeErrorAsync(Logger, response, Context.RequestAborted); return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Context.RequestAborted)); return(OAuthTokenResponse.Success(payload)); }
protected async Task <OAuthTokenResponse> RefreshCodeAsync(string code) { var tokenRequestParameters = new Dictionary <string, string> { { "client_id", Options.ClientId }, { "refresh_token", code }, { "client_secret", Options.ClientSecret }, { "grant_type", "refresh_token" } }; var requestContent = new FormUrlEncodedContent(tokenRequestParameters); var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); requestMessage.Content = requestContent; var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted).ConfigureAwait(false); if (response.IsSuccessStatusCode) { var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var _ = Options.CallbackPath; return(OAuthTokenResponse.Success(payload)); } var error = "OAuth token endpoint failure: " + await Display(response).ConfigureAwait(false); return(OAuthTokenResponse.Failed(new Exception(error))); }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri) { HttpResponseMessage async = await this.Backchannel.GetAsync(this.Options.TokenEndpoint + (object)new QueryBuilder() { { "appid", this.Options.AppId }, { "secret", this.Options.AppSecret }, { "code", code }, { "grant_type", "authorization_code" }, { "redirect_uri", redirectUri } }, this.Context.RequestAborted); async.EnsureSuccessStatusCode(); return(OAuthTokenResponse.Success(JObject.Parse(await async.Content.ReadAsStringAsync()))); }
/// <summary> /// 通过Code获取Access Token(这是第二步) /// </summary> protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(OAuthCodeExchangeContext context) { var parameters = new Dictionary <string, string> { { "appid", Options.ClientId }, { "secret", Options.ClientSecret }, { "code", context.Code }, { "grant_type", "authorization_code" } }; _logger.LogDebug("code换取access_token"); var endpoint = QueryHelpers.AddQueryString(Options.TokenEndpoint, parameters); _logger.LogDebug(endpoint); var response = await Backchannel.GetAsync(endpoint, Context.RequestAborted); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); _logger.LogDebug(result); var payload = JsonDocument.Parse(result); if (payload.RootElement.TryGetProperty("errcode", out JsonElement errcode)) { return(OAuthTokenResponse.Failed(new Exception($"获取微信AccessToken出错。{errcode}"))); } return(OAuthTokenResponse.Success(payload)); } else { return(OAuthTokenResponse.Failed(new Exception("获取微信AccessToken出错。"))); } }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(OAuthCodeExchangeContext context) { using var request = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); var parameters = new Dictionary <string, string> { ["grant_type"] = "authorization_code", ["redirect_uri"] = Options.RederectUrl, ["code"] = context.Code, ["client_id"] = Options.ClientId, ["client_secret"] = Options.ClientSecret }; request.Content = new FormUrlEncodedContent(parameters !); using var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } var httpContent = await response.Content.ReadAsStringAsync(); var tokenInfo = JsonConvert.DeserializeObject <dynamic>(httpContent); tokenInfo["subject"] = context.Code; var payload = JsonDocument.Parse(JsonConvert.SerializeObject(tokenInfo)); return(OAuthTokenResponse.Success(payload)); }
protected virtual async Task <OAuthTokenResponse> ExchangeCodeAsync(string code) { var tokenRequestParameters = new Dictionary <string, string>() { { "client_id", AgentOptions.ClientId }, { "redirect_uri", CallbackUri }, { "client_secret", AgentOptions.ClientSecret }, { "code", code }, { "grant_type", "authorization_code" }, }; var requestContent = new FormUrlEncodedContent(tokenRequestParameters); var requestMessage = new HttpRequestMessage(HttpMethod.Post, AgentOptions.TokenEndpoint); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); requestMessage.Content = requestContent; var response = await AgentOptions.Backchannel.SendAsync(requestMessage); if (response.IsSuccessStatusCode) { var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Success(payload)); } else { var error = "OAuth token endpoint failure: " + await Display(response); return(OAuthTokenResponse.Failed(new Exception(error))); } }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri) { var tokenRequestParameters = new Dictionary <string, string>() { { "client_id", Options.ClientId }, { "redirect_uri", redirectUri }, { "client_secret", Options.ClientSecret }, { "code", code }, { "grant_type", "authorization_code" }, }; var endpoint = QueryHelpers.AddQueryString(Options.TokenEndpoint, tokenRequestParameters); var requestMessage = new HttpRequestMessage(HttpMethod.Get, endpoint); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted); //var response = await Backchannel.GetAsync(endpoint, Context.RequestAborted); if (response.IsSuccessStatusCode) { var payload = await ConvertContentToJObject(response); return(OAuthTokenResponse.Success(payload)); } else { var error = "OAuth token endpoint failure: " + await Display(response); return(OAuthTokenResponse.Failed(new Exception(error))); } }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(OAuthCodeExchangeContext context) { string code = context.Code; string redirectUri = context.RedirectUri; #endif Dictionary <string, string> parameters = new Dictionary <string, string> { { "grant_type", "authorization_code" }, { "client_id", Options.ClientId }, { "client_secret", Options.ClientSecret }, { "code", code }, { "redirect_uri", redirectUri } }; string endpoint = QueryHelpers.AddQueryString(Options.TokenEndpoint, parameters); HttpResponseMessage response = await Backchannel.GetAsync(endpoint, Context.RequestAborted); if (!response.IsSuccessStatusCode) { return(OAuthTokenResponse.Failed(new Exception("获取QQ Connect Access Token出错。"))); } #if NETSTANDARD JObject payload = JObject.Parse(企鹅的返回不拘一格传入这里统一转换为JSON(await response.Content.ReadAsStringAsync())); return(OAuthTokenResponse.Success(payload)); #else string json = 企鹅的返回不拘一格传入这里统一转换为JSON(await response.Content.ReadAsStringAsync()); JsonDocument document = JsonDocument.Parse(json); return(OAuthTokenResponse.Success(document)); #endif }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] string code, [NotNull] string redirectUri) { var address = QueryHelpers.AddQueryString(Options.TokenEndpoint, new Dictionary <string, string>() { ["client_id"] = Options.ClientId, ["client_secret"] = Options.ClientSecret, ["redirect_uri"] = redirectUri, ["code"] = code, ["grant_type"] = "authorization_code", }); var request = new HttpRequestMessage(HttpMethod.Get, address); var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving an access token: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } var payload = JObject.FromObject(QueryHelpers.ParseQuery(await response.Content.ReadAsStringAsync()) .ToDictionary(pair => pair.Key, k => k.Value.ToString())); return(OAuthTokenResponse.Success(payload)); }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] OAuthCodeExchangeContext context) { var tokenRequestParameters = new Dictionary <string, string?> { ["app_id"] = Options.ClientId, ["app_secret"] = Options.ClientSecret, ["code"] = context.Code, ["redirect_uri"] = context.RedirectUri, }; // PKCE https://tools.ietf.org/html/rfc7636#section-4.5, see BuildChallengeUrl if (context.Properties.Items.TryGetValue(OAuthConstants.CodeVerifierKey, out var codeVerifier)) { tokenRequestParameters.Add(OAuthConstants.CodeVerifierKey, codeVerifier !); context.Properties.Items.Remove(OAuthConstants.CodeVerifierKey); } var address = QueryHelpers.AddQueryString(Options.TokenEndpoint, tokenRequestParameters); using var request = new HttpRequestMessage(HttpMethod.Get, address); using var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { await Log.ExchangeCodeErrorAsync(Logger, response, Context.RequestAborted); throw new HttpRequestException("An error occurred while retrieving the user profile."); } var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Context.RequestAborted)); return(OAuthTokenResponse.Success(payload)); }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] OAuthCodeExchangeContext context) { using var request = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var parameters = new Dictionary <string, string> { ["grant_type"] = "authorization_code", ["code"] = context.Code, ["redirect_uri"] = context.RedirectUri, ["client_id"] = Options.ClientId, ["client_secret"] = Options.ClientSecret }; request.Content = new FormUrlEncodedContent(parameters !); using var response = await Backchannel.SendAsync(request, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving an access token: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync(Context.RequestAborted)); return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Context.RequestAborted)); return(OAuthTokenResponse.Success(payload)); }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] OAuthCodeExchangeContext context) { using var request = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = CreateAuthorizationHeader(); var parameters = new Dictionary <string, string> { ["grant_type"] = "authorization_code", ["redirect_uri"] = context.RedirectUri, ["code"] = context.Code }; request.Content = new FormUrlEncodedContent(parameters !); using var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { await Log.ExchangeCodeErrorAsync(Logger, response, Context.RequestAborted); return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Context.RequestAborted)); return(OAuthTokenResponse.Success(payload)); }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] OAuthCodeExchangeContext context) { // See https://wiki.connect.qq.com/%E4%BD%BF%E7%94%A8authorization_code%E8%8E%B7%E5%8F%96access_token for details string address = QueryHelpers.AddQueryString(Options.TokenEndpoint, new Dictionary <string, string?>(6) { ["client_id"] = Options.ClientId, ["client_secret"] = Options.ClientSecret, ["redirect_uri"] = context.RedirectUri, ["code"] = context.Code, ["grant_type"] = "authorization_code", ["fmt"] = "json" // Return JSON instead of x-www-form-urlencoded which is default due to historical reasons }); using var request = new HttpRequestMessage(HttpMethod.Get, address); using var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { await Log.ExchangeCodeErrorAsync(Logger, response, Context.RequestAborted); return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } using var stream = await response.Content.ReadAsStreamAsync(Context.RequestAborted); var payload = JsonDocument.Parse(stream); return(OAuthTokenResponse.Success(payload)); }
/// <summary> /// 获取访问令牌 /// </summary> /// <param name="code">授权码</param> /// <param name="redirectUri">回调地址</param> protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri) { var dic = new Dictionary <string, string> { { "client_id", Options.ClientId }, { "redirect_uri", redirectUri }, { "client_secret", Options.ClientSecret }, { "grant_type", "authorization_code" }, { "code", code } }; if (Options.TokenType != TokenType.None) { dic.Add("token_type", Options.TokenType.GetDescription()); } var query = new FormUrlEncodedContent(dic); var message = new HttpRequestMessage(HttpMethod.Get, Options.TokenEndpoint + $"?{await query.ReadAsStringAsync()}"); message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await Backchannel.SendAsync(message, Context.RequestAborted); response.EnsureSuccessStatusCode(); // Replace("&&&START&&&", "") return(OAuthTokenResponse.Success(JObject.Parse((await response.Content.ReadAsStringAsync()).Remove(0, 11)))); }
protected async override Task <OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri) { var tokenRequestParameters = new Dictionary <string, string>() { { "redirect_uri", redirectUri }, { "code", code }, { "grant_type", "authorization_code" }, }; var requestContent = new FormUrlEncodedContent(tokenRequestParameters); var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); requestMessage.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Options.ClientId}:{Options.ClientSecret}"))); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); requestMessage.Content = requestContent; var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted); if (response.IsSuccessStatusCode) { var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Success(payload)); } else { var error = "OAuth token endpoint failure: " + await Display(response); return(OAuthTokenResponse.Failed(new Exception(error))); } }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(OAuthCodeExchangeContext context) { var tokenRequestParameters = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("appid", Options.ClientId), new KeyValuePair <string, string>("secret", Options.ClientSecret), new KeyValuePair <string, string>("code", context.Code), new KeyValuePair <string, string>("grant_type", "authorization_code"), }; var urlEncodedContent = new FormUrlEncodedContent(tokenRequestParameters); var response = await Backchannel.PostAsync(Options.TokenEndpoint, urlEncodedContent, Context.RequestAborted); //var response = await Backchannel.SendAsync(new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint) //{ // Headers = { // Accept = { // new MediaTypeWithQualityHeaderValue("application/json") // } // }, // Content = urlEncodedContent //}, Context.RequestAborted); return(response.IsSuccessStatusCode ? OAuthTokenResponse.Success(JsonDocument.Parse(await response.Content.ReadAsStringAsync())) : OAuthTokenResponse.Failed(new Exception("OAuth token failure"))); }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri) { _logger?.LogDebug("ExchangeCodeAsync({code}, {redirectUri})", code, redirectUri); var options = Options.BaseOptions(); options.CallbackUrl = redirectUri; var tEx = new TokenExchanger(options, GetHttpClient()); HttpResponseMessage response = await tEx.ExchangeCodeForToken(code, Options.TokenEndpoint, Context.RequestAborted).ConfigureAwait(false); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); _logger?.LogDebug("ExchangeCodeAsync() received json: {json}", result); var payload = JObject.Parse(result); var tokenResponse = OAuthTokenResponse.Success(payload); return(tokenResponse); } else { var error = "OAuth token endpoint failure: " + await Display(response).ConfigureAwait(false); return(OAuthTokenResponse.Failed(new Exception(error))); } }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(OAuthCodeExchangeContext context) { using var request = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Content = new FormUrlEncodedContent(new Dictionary <string, string> { ["redirect_uri"] = context.RedirectUri, ["client_assertion"] = Options.ClientSecret, ["client_assertion_type"] = AzureDevOpsAuthenticationDefaults.ClientAssertionType, ["assertion"] = context.Code, ["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer", }); using var response = await Backchannel.SendAsync(request, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving an access token: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", response.StatusCode, response.Headers.ToString(), await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } var content = await response.Content.ReadAsStringAsync(); var payload = JsonDocument.Parse(content); return(OAuthTokenResponse.Success(payload)); }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] string code, [NotNull] string redirectUri) { var credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Options.ClientId}:{Options.ClientSecret}")); var request = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Basic", credentials); request.Content = new FormUrlEncodedContent(new Dictionary <string, string> { ["grant_type"] = "authorization_code", ["redirect_uri"] = redirectUri, ["code"] = code }); var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving an access token: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Success(payload)); }
/// <summary> /// Requests a new access token based on a given OAuth refresh token. /// </summary> /// <param name="refreshToken"> /// The refresh token issued to the client. /// </param> /// <returns> /// A <see cref="Task"/> that returns the OAuth token endpoint response. /// </returns> public async Task <OAuthTokenResponse> RefreshAccessTokenAsync(string refreshToken) { var tokenRequestParameters = new Dictionary <string, string> { { "grant_type", "refresh_token" }, { "refresh_token", refreshToken }, { "client_id", clientId }, { "client_secret", clientSecret }, { "scope", "user:read:email" } }; var requestContent = new FormUrlEncodedContent(tokenRequestParameters); var requestMessage = new HttpRequestMessage(HttpMethod.Post, TokenEndpoint); requestMessage.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); requestMessage.Content = requestContent; var response = await httpClient.SendAsync(requestMessage); if (response.IsSuccessStatusCode) { var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Success(payload)); } else { var error = await GetExceptionAsync(response); return(OAuthTokenResponse.Failed(error)); } }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri) { var request = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); request.Content = new FormUrlEncodedContent(new Dictionary <string, string> { ["redirect_uri"] = redirectUri, ["client_assertion"] = Options.ClientSecret, ["assertion"] = code, ["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer", ["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" }); var response = await Backchannel.SendAsync(request, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving an access token: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Success(payload)); }
protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] OAuthCodeExchangeContext context) { using var request = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); var parameters = new Dictionary <string, string> { ["redirect_uri"] = context.RedirectUri, ["client_assertion"] = Options.ClientSecret, ["assertion"] = context.Code, ["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer", ["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" }; request.Content = new FormUrlEncodedContent(parameters !); using var response = await Backchannel.SendAsync(request, Context.RequestAborted); if (!response.IsSuccessStatusCode) { await Log.ExchangeCodeErrorAsync(Logger, response, Context.RequestAborted); return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Context.RequestAborted)); return(OAuthTokenResponse.Success(payload)); }