/// <summary> /// Конструктор. /// </summary> /// <param name="address">Адресная строка.</param> public UrlBuilder(string address = null) { if (!string.IsNullOrWhiteSpace(address)) { var addressUri = new Uri(address, UriKind.RelativeOrAbsolute); string baseAddress = null; string queryText = null; if (addressUri.IsAbsoluteUri) { baseAddress = $"{addressUri.Scheme}://{addressUri.Host}:{addressUri.Port}{addressUri.LocalPath}"; queryText = addressUri.Query; } else if (Uri.TryCreate(BaseUri, address, out addressUri)) { baseAddress = addressUri.LocalPath; queryText = addressUri.Query; } _baseAddress = baseAddress; if (!string.IsNullOrEmpty(queryText)) { foreach (var item in WebHelpers.ParseForm(queryText.TrimStart('?'))) { if (item.Value != null && item.Value.Length > 0) { _query[item.Key] = item.Value[0]; } } } } }
private async Task <RequestToken> ObtainRequestTokenAsync(string consumerKey, string consumerSecret, string callBackUri, AuthenticationProperties properties) { _logger.WriteVerbose("ObtainRequestToken"); var nonce = Guid.NewGuid().ToString("N"); var authorizationParts = new SortedDictionary <string, string> { { "oauth_callback", callBackUri }, { "oauth_consumer_key", consumerKey }, { "oauth_nonce", nonce }, { "oauth_signature_method", "HMAC-SHA1" }, { "oauth_timestamp", GenerateTimeStamp() }, { "oauth_version", "1.0" } }; var canonicalizedRequestBuilder = new StringBuilder(); canonicalizedRequestBuilder.Append(HttpMethod.Post.Method); canonicalizedRequestBuilder.Append("&"); canonicalizedRequestBuilder.Append(Uri.EscapeDataString(RequestTokenEndpoint)); canonicalizedRequestBuilder.Append("&"); canonicalizedRequestBuilder.Append(Uri.EscapeDataString(GetParameters(authorizationParts))); var signature = ComputeSignature(consumerSecret, null, canonicalizedRequestBuilder.ToString()); authorizationParts.Add("oauth_signature", signature); var authorizationHeaderBuilder = new StringBuilder(); authorizationHeaderBuilder.Append("OAuth "); foreach (var authorizationPart in authorizationParts) { authorizationHeaderBuilder.AppendFormat("{0}=\"{1}\", ", authorizationPart.Key, Uri.EscapeDataString(authorizationPart.Value)); } authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2; var request = new HttpRequestMessage(HttpMethod.Post, RequestTokenEndpoint); request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString()); var response = await _httpClient.SendAsync(request, Request.CallCancelled); response.EnsureSuccessStatusCode(); var responseText = await response.Content.ReadAsStringAsync(); var responseParameters = WebHelpers.ParseForm(responseText); if (string.Equals(responseParameters["oauth_callback_confirmed"], "true", StringComparison.InvariantCulture)) { return(new RequestToken { Token = Uri.UnescapeDataString(responseParameters["oauth_token"]), TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]), CallbackConfirmed = true, Properties = properties }); } return(new RequestToken()); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var json = string.Empty; if (request.Method == HttpMethod.Post && request.RequestUri.AbsoluteUri.Equals("https://portalbase.com/oauth2/token")) { var formBody = WebHelpers.ParseForm(await request.Content.ReadAsStringAsync()); json = this.notifications.GenerateToken(formBody); } else if (request.Method == HttpMethod.Get && request.RequestUri.AbsoluteUri.Equals("https://portalbase.com/api/v1.1/m/profile")) { json = this.notifications.GetUserProfile(request.Headers.Authorization.Scheme, request.Headers.Authorization.Parameter); } var response = new HttpResponseMessage(HttpStatusCode.NotFound); if (!string.IsNullOrEmpty(json)) { response.StatusCode = HttpStatusCode.OK; response.Content = new StringContent(json, Encoding.UTF8, "application/json"); } return(response); }
private async Task <AccessToken> ObtainAccessTokenAsync(string consumerKey, string consumerSecret, RequestToken token, string verifier) { //https://dev.xing.com/docs/authentication _logger.WriteVerbose("ObtainAccessToken"); var nonce = Guid.NewGuid().ToString("N"); var authorizationParts = new SortedDictionary <string, string> { { "oauth_consumer_key", consumerKey }, { "oauth_nonce", nonce }, { "oauth_signature_method", "HMAC-SHA1" }, { "oauth_token", token.Token }, { "oauth_timestamp", GenerateTimeStamp() }, { "oauth_verifier", verifier }, { "oauth_version", "1.0" }, }; var parameterBuilder = new StringBuilder(); foreach (var authorizationKey in authorizationParts) { parameterBuilder.AppendFormat("{0}={1}&", Uri.EscapeDataString(authorizationKey.Key), Uri.EscapeDataString(authorizationKey.Value)); } parameterBuilder.Length--; var parameterString = parameterBuilder.ToString(); var canonicalizedRequestBuilder = new StringBuilder(); canonicalizedRequestBuilder.Append(HttpMethod.Post.Method); canonicalizedRequestBuilder.Append("&"); canonicalizedRequestBuilder.Append(Uri.EscapeDataString(AccessTokenEndpoint)); canonicalizedRequestBuilder.Append("&"); canonicalizedRequestBuilder.Append(Uri.EscapeDataString(parameterString)); var signature = ComputeSignature(consumerSecret, token.TokenSecret, canonicalizedRequestBuilder.ToString()); authorizationParts.Add("oauth_signature", signature); authorizationParts.Remove("oauth_verifier"); var authorizationHeaderBuilder = new StringBuilder(); authorizationHeaderBuilder.Append("OAuth "); foreach (var authorizationPart in authorizationParts) { authorizationHeaderBuilder.AppendFormat( "{0}=\"{1}\", ", authorizationPart.Key, Uri.EscapeDataString(authorizationPart.Value)); } authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2; var request = new HttpRequestMessage(HttpMethod.Post, AccessTokenEndpoint); request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString()); var formPairs = new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("oauth_verifier", verifier) }; request.Content = new FormUrlEncodedContent(formPairs); var response = await _httpClient.SendAsync(request, Request.CallCancelled); if (!response.IsSuccessStatusCode) { _logger.WriteError("AccessToken request failed with a status code of " + response.StatusCode); response.EnsureSuccessStatusCode(); // throw } var responseText = await response.Content.ReadAsStringAsync(); var responseParameters = WebHelpers.ParseForm(responseText); return(new AccessToken { Token = Uri.UnescapeDataString(responseParameters["oauth_token"]), TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]), UserId = Uri.UnescapeDataString(responseParameters["user_id"]), }); }
protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationProperties properties = null; try { string code = null; string state = null; IReadableStringCollection query = Request.Query; IList <string> values = query.GetValues("error"); if (values != null && values.Count >= 1) { _logger.WriteVerbose("Remote server returned an error: " + Request.QueryString); } values = query.GetValues("code"); if (values != null && values.Count == 1) { code = values[0]; } values = query.GetValues("state"); if (values != null && values.Count == 1) { state = values[0]; } properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(null); } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(properties, _logger)) { return(new AuthenticationTicket(null, properties)); } if (code == null) { // Null if the remote server returns an error. return(new AuthenticationTicket(null, properties)); } string requestPrefix = Request.Scheme + "://" + Request.Host; string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath; string tokenRequest = "grant_type=authorization_code" + "&code=" + Uri.EscapeDataString(code) + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + "&client_id=" + Uri.EscapeDataString(Options.AppId) + "&client_secret=" + Uri.EscapeDataString(Options.AppSecret); HttpResponseMessage tokenResponse = await _httpClient.GetAsync(Options.TokenEndpoint + "?" + tokenRequest, Request.CallCancelled); tokenResponse.EnsureSuccessStatusCode(); string text = await tokenResponse.Content.ReadAsStringAsync(); IFormCollection form = WebHelpers.ParseForm(text); string accessToken = form["access_token"]; string expires = form["expires"]; string graphAddress = Options.UserInformationEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken); if (Options.SendAppSecretProof) { graphAddress += "&appsecret_proof=" + GenerateAppSecretProof(accessToken); } HttpResponseMessage graphResponse = await _httpClient.GetAsync(graphAddress, Request.CallCancelled); graphResponse.EnsureSuccessStatusCode(); text = await graphResponse.Content.ReadAsStringAsync(); JObject user = JObject.Parse(text); var context = new FacebookAuthenticatedContext(Context, user, accessToken, expires); context.Identity = new ClaimsIdentity( Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); if (!string.IsNullOrEmpty(context.Id)) { context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.UserName)) { context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Email)) { context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Name)) { context.Identity.AddClaim(new Claim("urn:facebook:name", context.Name, XmlSchemaString, Options.AuthenticationType)); // Many Facebook accounts do not set the UserName field. Fall back to the Name field instead. if (string.IsNullOrEmpty(context.UserName)) { context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType)); } } if (!string.IsNullOrEmpty(context.Link)) { context.Identity.AddClaim(new Claim("urn:facebook:link", context.Link, XmlSchemaString, Options.AuthenticationType)); } context.Properties = properties; await Options.Provider.Authenticated(context); return(new AuthenticationTicket(context.Identity, context.Properties)); } catch (Exception ex) { _logger.WriteError("Authentication failed", ex); return(new AuthenticationTicket(null, properties)); } }
protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { var properties = (AuthenticationProperties)null; try { var accessToken = Request.Query["accessToken"]; var expires = Request.Query["expiresIn"]; string text; if (null == accessToken) { var code = (string)null; var state = (string)null; var query = Request.Query; var values = query.GetValues("error"); if (values != null && values.Count >= 1) { _logger.WriteVerbose("Remote server returned an error: " + Request.QueryString); } values = query.GetValues("code"); if (values != null && values.Count == 1) { code = values[0]; } values = query.GetValues("state"); if (values != null && values.Count == 1) { state = values[0]; } properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(null); } if (!ValidateCorrelationId(properties, _logger)) { return(new AuthenticationTicket(null, properties)); } if (code == null) { return(new AuthenticationTicket(null, properties)); } var requestPrefix = Request.Scheme + "://" + Request.Host; var redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath; var tokenRequest = "grant_type=authorization_code&code=" + Uri.EscapeDataString(code) + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + "&client_id=" + Uri.EscapeDataString(Options.AppId) + "&client_secret=" + Uri.EscapeDataString(Options.AppSecret); var tokenResponse = await _httpClient.GetAsync(Options.TokenEndpoint + "?" + tokenRequest, Request.CallCancelled); tokenResponse.EnsureSuccessStatusCode(); text = await tokenResponse.Content.ReadAsStringAsync(); var form = WebHelpers.ParseForm(text); accessToken = form["access_token"]; expires = form["expires"]; } else { properties = new AuthenticationProperties() { RedirectUri = "/Account/ExternalLoginCallback" }; } var graphAddress = Options.UserInformationEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken); if (Options.SendAppSecretProof) { graphAddress += "&appsecret_proof=" + GenerateAppSecretProof(accessToken); } var graphResponse = await _httpClient.GetAsync(graphAddress, Request.CallCancelled); graphResponse.EnsureSuccessStatusCode(); text = await graphResponse.Content.ReadAsStringAsync(); var user = JObject.Parse(text); var context = new FacebookAuthenticatedContext(Context, user, accessToken, expires) { Identity = new ClaimsIdentity(Options.AuthenticationType, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "http://schemas.microsoft.com/ws/2008/06/identity/claims/role") }; if (!string.IsNullOrEmpty(context.Id)) { context.Identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", context.Id, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.UserName)) { context.Identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", context.UserName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Email)) { context.Identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", context.Email, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Name)) { context.Identity.AddClaim(new Claim("urn:facebook:name", context.Name, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)); if (string.IsNullOrEmpty(context.UserName)) { context.Identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", context.Name, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)); } } if (!string.IsNullOrEmpty(context.Link)) { context.Identity.AddClaim(new Claim("urn:facebook:link", context.Link, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)); } context.Properties = properties; await Options.Provider.Authenticated(context); return(new AuthenticationTicket(context.Identity, context.Properties)); } catch (Exception ex) { _logger.WriteError("Authentication failed", ex); return(new AuthenticationTicket(null, properties)); } }
protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationProperties properties = null; try { string code = null; string state = null; IReadableStringCollection query = Request.Query; IList <string> values = query.GetValues("code"); if (values != null && values.Count == 1) { code = values[0]; } values = query.GetValues("state"); if (values != null && values.Count == 1) { state = values[0]; } properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(null); } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(properties, _logger)) { return(new AuthenticationTicket(null, properties)); } string requestPrefix = Request.Scheme + "://" + Request.Host; string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath; string tokenRequest = "client_id=" + Uri.EscapeDataString(Options.ClientId) + "&client_secret=" + Uri.EscapeDataString(Options.ClientSecret) + "&code=" + Uri.EscapeDataString(code) + "&redirect_uri=" + Uri.EscapeDataString(redirectUri); HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage tokenResponse = await _httpClient.PostAsync(TokenEndpoint + "?" + tokenRequest, _httpRequest.Content, Request.CallCancelled); tokenResponse.EnsureSuccessStatusCode(); string text = await tokenResponse.Content.ReadAsStringAsync(); IFormCollection form = WebHelpers.ParseForm(text); string accessToken = form["access_token"]; string expires = form["expires"]; HttpResponseMessage graphResponse = await _httpClient.GetAsync( ApiEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken) + "&site=" + Uri.EscapeDataString(Options.Site) + "&key=" + Uri.EscapeDataString(Options.Key), Request.CallCancelled); graphResponse.EnsureSuccessStatusCode(); Stream rawStream = await graphResponse.Content.ReadAsStreamAsync(); using (GZipStream gzipStream = new GZipStream(rawStream, CompressionMode.Decompress)) using (StreamReader streamReader = new StreamReader(gzipStream)) { text = await streamReader.ReadToEndAsync(); } JObject info = JObject.Parse(text); JToken items = info["items"]; JToken userToken = items.First; JObject user = userToken as JObject; var context = new StackExchangeAuthenticatedContext(Context, user, accessToken, expires); context.Identity = new ClaimsIdentity( Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); if (!string.IsNullOrEmpty(context.UserId)) { context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserId, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.DisplayName)) { context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.DisplayName, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Email)) { context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.AccountId)) { context.Identity.AddClaim(new Claim("urn:stackexchange:accountId", context.AccountId, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Link)) { context.Identity.AddClaim(new Claim("urn:stackexchange:link", context.Link, XmlSchemaString, Options.AuthenticationType)); } context.Properties = properties; await Options.Provider.Authenticated(context); return(new AuthenticationTicket(context.Identity, context.Properties)); } catch (Exception ex) { _logger.WriteError(ex.Message); } return(new AuthenticationTicket(null, properties)); }